Expand description
Output abstraction for message encoding.
EncodeSink is the byte sink every encode path writes into. Its four
required methods are the BufMut primitives the encoders bottom out
in (the fixed-width signed/float writers are provided on top), plus
put_shared for splicing an owned Bytes
segment into the output without copying it.
Every BufMut implementor is an EncodeSink through a blanket impl,
with put_shared copying. Rope implements the trait directly (it is deliberately
not a BufMut) and captures large segments by reference count instead,
so encoding a message whose dominant content is one large bytes field
costs O(everything-but-the-payload) rather than O(payload).
§One write_to instance per message
Message::write_to is generic over the sink, so a program that encodes
into a Vec<u8> in one place and a BytesMut in another would compile
two copies of every message’s write_to. The provided encode methods of
Message and ViewEncode
(encode, encode_to_vec, and their try_, _with_cache, bounded and
length-delimited variants) therefore write every BufMut through one
shared, pre-sized cursor. They compute the exact size first and ask the
sink for that many contiguous bytes: Vec<u8> and BytesMut offer
their spare capacity, and write_to fills it with stores that are
bounds-checked but never grow the sink. A sink whose current chunk is
shorter than the message (an empty Vec::new() or BytesMut::new()
offers 64 bytes, and a chain of buffers offers its first) is filled
through a scratch Vec of the exact size and appended with one
put_slice, so reserving
encoded_len bytes first avoids the
extra allocation and copy. The length prefix of
encode_length_delimited is written to the sink before the message, so
reserve up to five bytes more for it.
A type that implements EncodeSink and not BufMut, and a segmented
sink (IS_SEGMENTED, such as Rope),
receives every write individually through its own instantiation of
write_to.
Generated lazy views and DynamicMessage have their own encode methods,
which do not use the shared cursor.
Structs§
- Rope
- A segmented encode sink: an ordered sequence of
Bytessegments. - RopeBuf
- A
Bufover a finished rope’s segments, for consumers (hyper, h2, vectored writers) that take anyBufand iterate its chunks.
Constants§
- DEFAULT_
MIN_ SEGMENT - Default minimum segment size for
Rope: payloads below this are copied into the small-write tail buffer rather than kept as their own segment.
Traits§
- Encode
Sink - Byte sink for message encoding.