summaryrefslogtreecommitdiff
path: root/serde_v8/src
diff options
context:
space:
mode:
authorAaron O'Mullan <aaron.omullan@gmail.com>2022-03-07 13:06:50 +0100
committerGitHub <noreply@github.com>2022-03-07 13:06:50 +0100
commit4e1da28b391de0c9ef1911f79d913bf604c0c3ac (patch)
tree75f8785e1931c20374eae463d30cd0531982bc87 /serde_v8/src
parent0b9da1aa7a9bbbdbc5495a172cadd92ee49d7b1f (diff)
perf(serde_v8): avoid SerializablePkg allocs (#13860)
For common return types such as String/ZeroCopyBuf/ByteString
Diffstat (limited to 'serde_v8/src')
-rw-r--r--serde_v8/src/serializable.rs22
1 files changed, 19 insertions, 3 deletions
diff --git a/serde_v8/src/serializable.rs b/serde_v8/src/serializable.rs
index 298fe8c8a..df6912db0 100644
--- a/serde_v8/src/serializable.rs
+++ b/serde_v8/src/serializable.rs
@@ -2,6 +2,9 @@
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))
}