pub trait MessageView<'a>: Sized {
type Owned: Message;
// Required methods
fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError>;
fn merge_view_field(
&mut self,
tag: Tag,
cur: &'a [u8],
before_tag: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<&'a [u8], DecodeError>;
fn to_owned_message(&self) -> Result<Self::Owned, DecodeError>;
// Provided methods
fn decode_view_with_ctx(
buf: &'a [u8],
_ctx: DecodeContext<'_>,
) -> Result<Self, DecodeError> { ... }
fn decode_view_ctx(
buf: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<Self, DecodeError>
where Self: Default { ... }
fn merge_into_view(
&mut self,
buf: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<(), DecodeError> { ... }
fn to_owned_from_source(
&self,
source: Option<&Bytes>,
) -> Result<Self::Owned, DecodeError> { ... }
}Expand description
Trait for zero-copy borrowed message views.
View types borrow from the input buffer and provide read-only access
to message fields without allocation. Each generated MyMessageView<'a>
implements this trait.
The lifetime 'a ties the view to the input buffer — the view cannot
outlive the buffer it was decoded from.
A hand-written implementation that is to be used through OwnedView
must also implement ViewReborrow and the unsafe marker
ViewLifetimeParametric, whose # Safety section states what the
implementation must guarantee.
Generated view structs may gain fields across releases; see the
struct evolution policy on Message.
Required Associated Types§
Required Methods§
Sourcefn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError>
fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError>
Decode a view from a buffer, borrowing string/bytes fields directly.
The returned view borrows from buf’s underlying bytes. The caller
must ensure the buffer is contiguous (e.g., &[u8] or bytes::Bytes).
Decoding validates the whole message tree eagerly. For
decode-on-access of large sub-message trees, see the opt-in
LazyMessageView family (lazy_views codegen option).
Generated impls construct a default DecodeContext
and delegate to decode_view_ctx. (Kept
required, without a Self: Default bound, so generic callers stay
bound-free.)
The default context carries the same three budgets
Message::decode applies:
RECURSION_LIMIT,
DEFAULT_UNKNOWN_FIELD_LIMIT, and
DEFAULT_ELEMENT_MEMORY_LIMIT.
Repeated message, group, string, and bytes elements are charged by the
size of the view element stored in the Vec; map entries are charged by
their key and value slot sizes. Borrowed string and bytes contents are
not charged. Repeated numeric and enum elements are not charged, whether
packed or unpacked. Since a view element can have a different size from
its owned type (&str versus String), a payload near the limit can
have a different result in owned and view decoding.
This method does not enforce a maximum input size; use
DecodeOptions::decode_view when
an input-size cap is required.
Sourcefn merge_view_field(
&mut self,
tag: Tag,
cur: &'a [u8],
before_tag: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<&'a [u8], DecodeError>
fn merge_view_field( &mut self, tag: Tag, cur: &'a [u8], before_tag: &'a [u8], ctx: DecodeContext<'_>, ) -> Result<&'a [u8], DecodeError>
Decode one field’s payload into this view (generated per message).
cur is the input positioned just past tag; the implementation
returns the remaining input after the field’s payload. The
pass-by-value/return shape (rather than &mut &'a [u8]) keeps each
arm’s &mut borrow of the slice local to that arm — sub-message
arms can hand cur slices to recursive decode calls without
fighting a long-lived outer &mut reborrow. before_tag is the
input including the tag bytes, for raw-span unknown-field capture.
Hand-written views must supply this (it is the one method the
provided decode loop requires). A view that instead overrides both
decode_view and
decode_view_with_ctx to decode by hand
never reaches the provided loop, so it can satisfy the trait with a
one-line Ok(cur) stub. The canonical shape is a match on
tag.field_number(). Mark the method #[inline]: the provided loop
calls it once per field across the crate boundary, so the hint lets the
optimizer fold the match into that loop.
#[inline]
fn merge_view_field(
&mut self,
tag: buffa::encoding::Tag,
cur: &'a [u8],
_before_tag: &'a [u8],
ctx: buffa::DecodeContext<'_>,
) -> Result<&'a [u8], buffa::DecodeError> {
let mut cur = cur;
match tag.field_number() {
1 => self.id = buffa::types::decode_int32(&mut cur)?,
2 => self.name = buffa::types::borrow_str(&mut cur)?,
_ => buffa::encoding::skip_unknown_field(tag, &mut cur, ctx)?,
}
Ok(cur)
}Views that preserve unknown fields capture the raw span — tag
included — via before_tag (the span length is measured after the
payload is consumed) and store it with
UnknownFieldsView::push_record, which charges the context’s
unknown-field allowance per field (including fields nested in
unknown groups) so that to_owned_message
cannot exhaust it later; the provided loop stays message-agnostic:
_ => {
buffa::encoding::skip_unknown_field(tag, &mut cur, ctx)?;
let span_len = before_tag.len().checked_sub(cur.len())
.ok_or(buffa::DecodeError::UnexpectedEof)?;
self.unknown_fields.push_record(before_tag, span_len, ctx)?;
}The returned slice must be a suffix of cur (and hence of
before_tag): the provided loop continues from it, and the
unknown-field span is measured as before_tag.len() - cur.len(), which
underflows and panics if the returned slice is longer than the input.
§Errors
Returns a DecodeError on malformed payloads, wire-type mismatches,
or when a configured decode limit is exceeded.
Sourcefn to_owned_message(&self) -> Result<Self::Owned, DecodeError>
fn to_owned_message(&self) -> Result<Self::Owned, DecodeError>
Convert this view to the owned message type.
This allocates and copies all borrowed fields. Equivalent to
to_owned_from_source(None).
For views produced by decode_view (or the
other wire-decoding entry points), this cannot fail: decoding
charged the unknown-field allowance with exactly the slots that
re-materializing preserved unknown fields consumes, every span was
parsed off the wire, and re-materialization replays under the field
budget and group-nesting depth recorded at decode time. The Result
remains for hand-written view impls and for views holding manually
pushed (UnknownFieldsView::push_raw) unknown-field spans.
OwnedView, which always holds a wire-decoded view, exposes this
conversion infallibly — see
OwnedView::to_owned_message (and the
generated FooOwnedView wrappers likewise).
§Errors
Returns an error if re-materializing preserved unknown fields fails — possible only for views not produced by wire decoding, as described above.
Provided Methods§
Sourcefn decode_view_with_ctx(
buf: &'a [u8],
_ctx: DecodeContext<'_>,
) -> Result<Self, DecodeError>
fn decode_view_with_ctx( buf: &'a [u8], _ctx: DecodeContext<'_>, ) -> Result<Self, DecodeError>
Decode a view under custom decode limits.
Used by DecodeOptions::decode_view
to pass a non-default recursion depth, unknown-field allowance, and
element-memory budget.
The default implementation delegates to
decode_view and ignores the context —
a hand-written MessageView that recurses or preserves unknown
fields must override this method to honor the limits configured on
DecodeOptions. Implementing
merge_view_field is not sufficient:
without this override, DecodeOptions limits never reach your
field arms. The one-line override is
Self::decode_view_ctx(buf, ctx) (when Self: Default). Generated
code always overrides it that way.
Not to be confused with decode_view_ctx,
which is the provided decoder that honors the context; this method
is the override point DecodeOptions calls.
Sourcefn decode_view_ctx(
buf: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<Self, DecodeError>where
Self: Default,
fn decode_view_ctx(
buf: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<Self, DecodeError>where
Self: Default,
Decode a view under an explicit DecodeContext
(remaining recursion depth, unknown-field allowance, and element-memory
budget), driving the provided tag loop over
merge_view_field.
This is the bridge a hand-written impl uses to wire its required
decode_view to its required merge_view_field:
fn decode_view(buf: &'a [u8]) -> Result<Self, buffa::DecodeError> {
let limit = core::cell::Cell::new(buffa::DEFAULT_UNKNOWN_FIELD_LIMIT);
let elem = core::cell::Cell::new(buffa::DEFAULT_ELEMENT_MEMORY_LIMIT);
Self::decode_view_ctx(
buf,
buffa::DecodeContext::new(buffa::RECURSION_LIMIT, &limit)
.with_element_memory(&elem),
)
}Attaching the element-memory budget is load-bearing, not decoration.
register_element_memory
returns Ok(()) when no budget is attached, so a context built without
with_element_memory
turns every repeated-element charge in every field arm into a no-op.
Also called by generated sub-message decode arms with a descended
context. Not to be confused with
decode_view_with_ctx, the
DecodeOptions override point whose default ignores the context.
§Errors
Returns a DecodeError on malformed input, a wire-type mismatch, or
when a configured decode limit (recursion depth, unknown-field
allowance, or element-memory budget) is exceeded.
Sourcefn merge_into_view(
&mut self,
buf: &'a [u8],
ctx: DecodeContext<'_>,
) -> Result<(), DecodeError>
fn merge_into_view( &mut self, buf: &'a [u8], ctx: DecodeContext<'_>, ) -> Result<(), DecodeError>
Merge fields from buf into this view (proto merge semantics):
repeated fields append, singular fields last-wins, singular message
fields merge recursively.
The per-message work is the field match in
merge_view_field; this provided method
owns the tag loop that every generated view previously restated.
Each iteration consumes the field’s tag itself, so the loop makes
progress even if an arm consumes no payload bytes.
§Errors
Returns a DecodeError on malformed input, a wire-type mismatch, or
when a configured decode limit (recursion depth, unknown-field
allowance, or element-memory budget) is exceeded.
Sourcefn to_owned_from_source(
&self,
source: Option<&Bytes>,
) -> Result<Self::Owned, DecodeError>
fn to_owned_from_source( &self, source: Option<&Bytes>, ) -> Result<Self::Owned, DecodeError>
Convert this view to the owned message type, optionally slicing
bytes::Bytes-typed fields from source instead of copying.
When source is the Bytes buffer this view was decoded from,
owned fields configured for bytes::Bytes (via the bytes_fields
codegen option) are produced via Bytes::slice_ref — a refcount
bump, no allocation or copy. Borrowed fields that fall outside
source (e.g. on a manually-constructed view) and the None case
fall back to Bytes::copy_from_slice.
Generated view types override this; the default delegates to
to_owned_message so hand-written impls
need only provide that method.
§Errors
Same contract as to_owned_message.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".