perf(serde_v8): avoid SerializablePkg allocs
For common return types such as String/ZeroCopyBuf/ByteString
use std::any::TypeId;
use std::mem::transmute_copy;
+use crate::Buffer;
+use crate::ByteString;
+
/// Serializable exists to allow boxing values as "objects" to be serialized later,
/// this is particularly useful for async op-responses. This trait is a more efficient
/// replacement for erased-serde that makes less allocations, since it's specific to serde_v8
@@ -44,7 +47,6 @@ impl SerializablePkg {
/// Primitive serves as a lightweight serializable wrapper around primitives
/// so that we can use them for async values
-#[derive(Clone, Copy)]
pub enum Primitive {
Unit,
Bool(bool),
@@ -58,6 +60,9 @@ pub enum Primitive {
UInt64(u64),
Float32(f32),
Float64(f64),
+ String(String),
+ Buffer(Buffer),
+ ByteString(ByteString),
}
impl serde::Serialize for Primitive {
@@ -65,7 +70,7 @@ impl serde::Serialize for Primitive {
where
S: serde::Serializer,
{
- match *self {
+ match self {
Self::Unit => ().serialize(s),
Self::Bool(x) => x.serialize(s),
Self::Int8(x) => x.serialize(s),
@@ -78,6 +83,9 @@ impl serde::Serialize for Primitive {
Self::UInt64(x) => x.serialize(s),
Self::Float32(x) => x.serialize(s),
Self::Float64(x) => x.serialize(s),
+ Self::String(x) => x.serialize(s),
+ Self::Buffer(x) => x.serialize(s),
+ Self::ByteString(x) => x.serialize(s),
}
}
}
@@ -86,7 +94,9 @@ impl<T: serde::Serialize + 'static> From<T> for SerializablePkg {
fn from(x: T) -> Self {
#[inline(always)]
fn tc<T, U>(src: T) -> U {
- unsafe { transmute_copy(&src) }
+ let x = unsafe { transmute_copy(&src) };
+ std::mem::forget(src);
+ x
}
let tid = TypeId::of::<T>();
@@ -114,6 +124,12 @@ impl<T: serde::Serialize + 'static> From<T> for SerializablePkg {
Self::Primitive(Primitive::Float32(tc(x)))
} else if tid == TypeId::of::<f64>() {
Self::Primitive(Primitive::Float64(tc(x)))
+ } else if tid == TypeId::of::<String>() {
+ Self::Primitive(Primitive::String(tc(x)))
+ } else if tid == TypeId::of::<Buffer>() {
+ Self::Primitive(Primitive::Buffer(tc(x)))
+ } else if tid == TypeId::of::<ByteString>() {
+ Self::Primitive(Primitive::ByteString(tc(x)))
} else {
Self::Serializable(Box::new(x))
}
