Skip to main content

SerBuffer

Struct SerBuffer 

Source
pub struct SerBuffer;
Expand description

Thread-local reusable serialization buffer.

Avoids the per-call Vec<u8> allocation from serde_json::to_vec(). The buffer is cleared (but not deallocated) between uses, so repeated serializations reuse the same heap allocation.

§Performance impact

  • Small payloads (<256B): Eliminates the 2.3× allocation overhead. serde_json::to_vec allocates a new Vec<u8> with ~80 bytes of initial overhead per call. With SerBuffer, this overhead is paid once.
  • Large payloads (>1KB): Minimal benefit — the buffer grows to match the payload and the fixed overhead is negligible.

§Thread safety

Each thread gets its own buffer via thread_local!. There is no cross-thread contention. The buffer is never shared.

Implementations§

Source§

impl SerBuffer

Source

pub fn serialize<T: Serialize>(value: &T) -> Result<Vec<u8>, Error>

Serializes value into a reusable thread-local buffer and returns the bytes as a new Vec<u8>.

The thread-local buffer is reused across calls — only one allocation occurs per thread (on first use), then the buffer grows as needed but is never deallocated between calls.

§Errors

Returns a serde_json::Error if serialization fails.

Source

pub fn serialize_into<T: Serialize, W: Write>( writer: W, value: &T, ) -> Result<(), Error>

Serializes value directly into the provided writer, avoiding all intermediate buffer allocations.

Prefer this over serialize when you have a writer (e.g. a Vec<u8> you own, a TcpStream, etc.) and don’t need the intermediate copy.

§Errors

Returns a serde_json::Error if serialization fails.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.