mirror of
https://github.com/denoland/deno.git
synced 2025-02-01 12:16:11 -05:00
perf(serde_v8): avoid SerializablePkg allocs (#13860)
For common return types such as String/ZeroCopyBuf/ByteString
This commit is contained in:
parent
0b9da1aa7a
commit
4e1da28b39
1 changed files with 19 additions and 3 deletions
|
@ -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))
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue