Skip to main content

SizeCache

Struct SizeCache 

Source
pub struct SizeCache { /* private fields */ }
Expand description

Transient pre-order cache of nested-message sizes for the two-pass serialization model (compute_size populates, write_to consumes).

Message::encode and friends construct and discard a SizeCache internally — most callers never name this type. It appears in the compute_size / write_to signatures so that manual Message implementations can thread it through nested-message recursion.

Storage is a small inline [u32; 16] array with a Vec<u32> spill for the (uncommon) case of more than 16 nested length-delimited sub-messages, so a fresh cache is allocation-free for typical messages.

Reusable across encodes: call clear between uses to retain the spill allocation. SizeCache is intentionally not Clone — it is transient encode state, not data. Reuse via clear().

§Safety invariant

The inline slots are MaybeUninit to avoid zeroing the whole array on every construction (see the field comment). The invariant that keeps the single unsafe read in consume_next sound is:

every inline slot at an index < len has been initialized.

It is established in exactly one place — reserve writes the slot at index len before incrementing len — and len only ever grows via reserve (which does that write) or resets to 0 via clear. consume_next only reads a slot after checking idx < len. Because all three methods and the fields are private to this module, no external code (generated or hand-written) can break the invariant: the worst a misuse can do is trip the idx >= len overrun panic or read a wrong-but-initialized size — never undefined behavior.

§Panic locations

Generated code calls set once per length-delimited sub-message field and consume_next once as well, so a large schema produces hundreds to thousands of call sites for each. Under #[track_caller] every one of them materializes a Location record. The attribute is therefore gated on debug_assertions and the panic bodies are kept out of line.

The bound checks themselves always run. What changes is the report: without the attribute a violation points inside buffa’s own source rather than at your compute_size / write_to. The gate follows the profile buffa itself was compiled with, not yours. To recover caller locations in a release build, enable them for buffa alone:

[profile.release.package.buffa]
debug-assertions = true

This also turns on buffa’s other debug_assert!s (including a per-slot size check in consume_next), so treat it as a diagnostic setting rather than a permanent one.

Implementations§

Source§

impl SizeCache

Source

pub const fn new() -> Self

Create an empty cache. No heap allocation.

Source

pub fn clear(&mut self)

Clear the cache for reuse. Retains the spill allocation’s capacity.

Source

pub fn with_spill_buffer(spill: Vec<u32>) -> Self

Construct a cache that reuses a caller-supplied spill buffer.

The inline storage is always stack-allocated; only the spill Vec ever heap-allocates, and only for messages with more than 16 nested length-delimited sub-messages. Handing in a previously-grown buffer makes such an encode allocation-free for the cache. The buffer is cleared (its capacity retained). Most callers should reach for a SizeCachePool rather than thread buffers by hand.

Source

pub fn into_spill_buffer(self) -> Vec<u32>

Reclaim the spill buffer for reuse, consuming the cache.

The returned Vec retains whatever capacity the cache grew to; feed it back into with_spill_buffer — or let a SizeCachePool manage it — so the next encode reuses the allocation.

Source

pub fn reserve(&mut self) -> usize

Reserve a slot for a nested message’s size. Call immediately before recursing into child.compute_size(cache), then fill the slot with set after the recursion returns. This reserves the slot in pre-order even though the size is known in post-order.

Used by generated compute_size implementations.

Source

pub fn set(&mut self, idx: usize, size: u32)

Fill a previously-reserved slot.

Used by generated compute_size implementations.

§Panics

Panics if idx was not returned by a prior reserve on this cache (i.e. idx >= len). The check always runs; the caller location is attached only when buffa is compiled with debug_assertions. See Panic locations.

Source

pub fn consume_next(&mut self) -> u32

Consume the next cached size in pre-order.

Used by generated write_to implementations for length-delimited nested message headers.

§Panics

Panics if the cursor runs past the end of the cache — i.e. if write_to traversal diverges from compute_size traversal. For generated code this indicates a codegen bug; for manual Message implementations it indicates a traversal-order mismatch. As for set, the check always runs and only the caller location is gated on debug_assertions. See Panic locations.

In debug builds, also panics if the cached size exceeds the 2 GiB protobuf limit (MAX_MESSAGE_BYTES): every slot is a sub-message length about to become a wire length prefix, and no conforming decoder accepts a prefix above the limit. This can only fire when compute_size/write_to are driven directly with an over-limit sub-message — the provided Message::encode* entry points reject over-limit messages before write_to runs, so (like the two-pass byte ledger) the check is debug-only rather than a release-mode branch on every nested-message write.

Trait Implementations§

Source§

impl Debug for SizeCache

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SizeCache

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.