buffa/view.rs
1// Modified by ReallyMe Technologies Limited.
2//! Zero-copy borrowed message views.
3//!
4//! Buffa generates two representations for each protobuf message:
5//!
6//! - **Owned** (`MyMessage`): uses `String`, `Vec<u8>`, `Vec<T>` for fields.
7//! Suitable for building messages, long-lived storage, and mutation.
8//!
9//! - **Borrowed** (`MyMessageView<'a>`): uses `&'a str`, `&'a [u8]`, and
10//! slice-backed repeated fields. Borrows directly from the input buffer
11//! for zero-copy deserialization on the read path.
12//!
13//! # Motivation
14//!
15//! In a typical RPC handler, the request is parsed from a buffer, fields are
16//! read, and the buffer is discarded. With owned types, every string and bytes
17//! field requires an allocation + copy. With view types, strings and bytes
18//! borrow directly from the input buffer — no allocation at all.
19//!
20//! This is analogous to how Cap'n Proto's Rust implementation works, and how
21//! Go achieves zero-copy string deserialization via its garbage collector.
22//!
23//! # Usage pattern
24//!
25//! ```rust,ignore
26//! // Decode a view (zero-copy, borrows from `wire_bytes`)
27//! let request = MyRequestView::decode_view(&wire_bytes)?;
28//! println!("name: {}", request.name); // &str, no allocation
29//!
30//! // Build an owned response
31//! let response = MyResponse {
32//! id: request.id,
33//! status: "ok".into(),
34//! ..Default::default()
35//! };
36//!
37//! // Convert view to owned if needed for storage
38//! let owned: MyRequest = request.to_owned_message()?;
39//! ```
40//!
41//! # Reborrowing from `OwnedView`
42//!
43//! [`OwnedView<V>`](OwnedView) wraps a decoded view with the lifetime erased
44//! to `'static`. The inner view is reached through
45//! [`OwnedView::reborrow`], which ties the borrow to the `OwnedView` itself —
46//! field reads, assigning the view to a binding, passing it to a function
47//! with a non-`'static` lifetime parameter, and returning a borrowed field
48//! all go through the same call:
49//!
50//! ```no_run
51//! # use buffa::view::OwnedView;
52//! # use buffa::__doctest_fixtures::PersonView;
53//! // reborrow ties the returned borrow to the OwnedView's lifetime.
54//! fn handler<'a>(req: &'a OwnedView<PersonView<'static>>) -> &'a str {
55//! req.reborrow().name
56//! }
57//! ```
58//!
59//! The view is deliberately not exposed as `&V` (e.g. via `Deref`): `V` is
60//! `FooView<'static>`, so its borrowed fields would *appear* `'static` to the
61//! compiler and could outlive the buffer they point into. `reborrow` narrows
62//! that synthetic `'static` down to the `OwnedView`'s real lifetime. Generated
63//! code also provides a per-message `FooOwnedView` wrapper with field accessor
64//! methods, so handler code rarely needs to call `reborrow` directly. See
65//! [`OwnedView`] for details.
66//!
67//! The same synthetic `'static` is what `V::decode_view` sees, so every
68//! `OwnedView` constructor requires `V: `[`ViewLifetimeParametric`] — the
69//! `unsafe` marker asserting that no impl on `V` can let a borrow of that
70//! buffer outlive the view. Codegen emits it for every generated view;
71//! hand-written views opt in with an explicit `unsafe impl`.
72//!
73//! # Generated code shape
74//!
75//! For a message like:
76//! ```protobuf
77//! message Person {
78//! string name = 1;
79//! int32 id = 2;
80//! bytes avatar = 3;
81//! repeated string tags = 4;
82//! Address address = 5;
83//! }
84//! ```
85//!
86//! Buffa generates:
87//! ```rust,ignore
88//! // Owned type (heap-allocated strings and vecs)
89//! pub struct Person {
90//! pub name: String,
91//! pub id: i32,
92//! pub avatar: Vec<u8>,
93//! pub tags: Vec<String>,
94//! pub address: MessageField<Address>,
95//! #[doc(hidden)] pub __buffa_unknown_fields: UnknownFields,
96//! }
97//!
98//! // Borrowed view type (zero-copy from input buffer)
99//! pub struct PersonView<'a> {
100//! pub name: &'a str,
101//! pub id: i32,
102//! pub avatar: &'a [u8],
103//! pub tags: RepeatedView<'a, &'a str>,
104//! pub address: MessageFieldView<AddressView<'a>>,
105//! pub __buffa_unknown_fields: UnknownFieldsView<'a>,
106//! }
107//! ```
108
109use crate::encode_sink::EncodeSink;
110use crate::error::DecodeError;
111use crate::message::Message as _;
112use bytes::Bytes;
113
114/// Trait for zero-copy borrowed message views.
115///
116/// View types borrow from the input buffer and provide read-only access
117/// to message fields without allocation. Each generated `MyMessageView<'a>`
118/// implements this trait.
119///
120/// The lifetime `'a` ties the view to the input buffer — the view cannot
121/// outlive the buffer it was decoded from.
122///
123/// A hand-written implementation that is to be used through [`OwnedView`]
124/// must also implement [`ViewReborrow`] and the `unsafe` marker
125/// [`ViewLifetimeParametric`], whose `# Safety` section states what the
126/// implementation must guarantee.
127///
128/// Generated view structs may gain fields across releases; see the
129/// [struct evolution policy on `Message`](crate::Message#struct-evolution-policy).
130pub trait MessageView<'a>: Sized {
131 /// The corresponding owned message type.
132 type Owned: crate::Message;
133
134 /// Decode a view from a buffer, borrowing string/bytes fields directly.
135 ///
136 /// The returned view borrows from `buf`'s underlying bytes. The caller
137 /// must ensure the buffer is contiguous (e.g., `&[u8]` or `bytes::Bytes`).
138 ///
139 /// Decoding validates the whole message tree eagerly. For
140 /// decode-on-access of large sub-message trees, see the opt-in
141 /// [`LazyMessageView`] family (`lazy_views` codegen option).
142 ///
143 /// Generated impls construct a default [`DecodeContext`](crate::DecodeContext)
144 /// and delegate to [`decode_view_ctx`](Self::decode_view_ctx). (Kept
145 /// required, without a `Self: Default` bound, so generic callers stay
146 /// bound-free.)
147 ///
148 /// The default context carries the same three budgets
149 /// [`Message::decode`](crate::Message::decode) applies:
150 /// [`RECURSION_LIMIT`](crate::RECURSION_LIMIT),
151 /// [`DEFAULT_UNKNOWN_FIELD_LIMIT`](crate::DEFAULT_UNKNOWN_FIELD_LIMIT), and
152 /// [`DEFAULT_ELEMENT_MEMORY_LIMIT`](crate::DEFAULT_ELEMENT_MEMORY_LIMIT).
153 /// Repeated message, group, string, and bytes elements are charged by the
154 /// size of the view element stored in the `Vec`; map entries are charged by
155 /// their key and value slot sizes. Borrowed string and bytes contents are
156 /// not charged. Repeated numeric and enum elements are not charged, whether
157 /// packed or unpacked. Since a view element can have a different size from
158 /// its owned type (`&str` versus `String`), a payload near the limit can
159 /// have a different result in owned and view decoding.
160 ///
161 /// This method does not enforce a maximum input size; use
162 /// [`DecodeOptions::decode_view`](crate::DecodeOptions::decode_view) when
163 /// an input-size cap is required.
164 fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError>;
165
166 /// Decode a view under custom decode limits.
167 ///
168 /// Used by [`DecodeOptions::decode_view`](crate::DecodeOptions::decode_view)
169 /// to pass a non-default recursion depth, unknown-field allowance, and
170 /// element-memory budget.
171 /// The default implementation delegates to
172 /// [`decode_view`](Self::decode_view) and **ignores the context** —
173 /// a hand-written `MessageView` that recurses or preserves unknown
174 /// fields must override this method to honor the limits configured on
175 /// `DecodeOptions`. Implementing
176 /// [`merge_view_field`](Self::merge_view_field) is **not sufficient**:
177 /// without this override, `DecodeOptions` limits never reach your
178 /// field arms. The one-line override is
179 /// `Self::decode_view_ctx(buf, ctx)` (when `Self: Default`). Generated
180 /// code always overrides it that way.
181 ///
182 /// Not to be confused with [`decode_view_ctx`](Self::decode_view_ctx),
183 /// which is the provided decoder that *honors* the context; this method
184 /// is the override point `DecodeOptions` calls.
185 fn decode_view_with_ctx(
186 buf: &'a [u8],
187 _ctx: crate::DecodeContext<'_>,
188 ) -> Result<Self, DecodeError> {
189 Self::decode_view(buf)
190 }
191
192 /// Decode a view under an explicit [`DecodeContext`](crate::DecodeContext)
193 /// (remaining recursion depth, unknown-field allowance, and element-memory
194 /// budget), driving the provided tag loop over
195 /// [`merge_view_field`](Self::merge_view_field).
196 ///
197 /// This is the bridge a hand-written impl uses to wire its required
198 /// `decode_view` to its required `merge_view_field`:
199 ///
200 /// ```rust,ignore
201 /// fn decode_view(buf: &'a [u8]) -> Result<Self, buffa::DecodeError> {
202 /// let limit = core::cell::Cell::new(buffa::DEFAULT_UNKNOWN_FIELD_LIMIT);
203 /// let elem = core::cell::Cell::new(buffa::DEFAULT_ELEMENT_MEMORY_LIMIT);
204 /// Self::decode_view_ctx(
205 /// buf,
206 /// buffa::DecodeContext::new(buffa::RECURSION_LIMIT, &limit)
207 /// .with_element_memory(&elem),
208 /// )
209 /// }
210 /// ```
211 ///
212 /// Attaching the element-memory budget is load-bearing, not decoration.
213 /// [`register_element_memory`](crate::DecodeContext::register_element_memory)
214 /// returns `Ok(())` when no budget is attached, so a context built without
215 /// [`with_element_memory`](crate::DecodeContext::with_element_memory)
216 /// turns every repeated-element charge in every field arm into a no-op.
217 ///
218 /// Also called by generated sub-message decode arms with a descended
219 /// context. Not to be confused with
220 /// [`decode_view_with_ctx`](Self::decode_view_with_ctx), the
221 /// `DecodeOptions` override point whose *default* ignores the context.
222 ///
223 /// # Errors
224 ///
225 /// Returns a [`DecodeError`] on malformed input, a wire-type mismatch, or
226 /// when a configured decode limit (recursion depth, unknown-field
227 /// allowance, or element-memory budget) is exceeded.
228 fn decode_view_ctx(buf: &'a [u8], ctx: crate::DecodeContext<'_>) -> Result<Self, DecodeError>
229 where
230 Self: Default,
231 {
232 let mut view = Self::default();
233 view.merge_into_view(buf, ctx)?;
234 Ok(view)
235 }
236
237 /// Merge fields from `buf` into this view (proto merge semantics):
238 /// repeated fields append, singular fields last-wins, singular message
239 /// fields merge recursively.
240 ///
241 /// The per-message work is the field `match` in
242 /// [`merge_view_field`](Self::merge_view_field); this provided method
243 /// owns the tag loop that every generated view previously restated.
244 /// Each iteration consumes the field's tag itself, so the loop makes
245 /// progress even if an arm consumes no payload bytes.
246 ///
247 /// # Errors
248 ///
249 /// Returns a [`DecodeError`] on malformed input, a wire-type mismatch, or
250 /// when a configured decode limit (recursion depth, unknown-field
251 /// allowance, or element-memory budget) is exceeded.
252 fn merge_into_view(
253 &mut self,
254 buf: &'a [u8],
255 ctx: crate::DecodeContext<'_>,
256 ) -> Result<(), DecodeError> {
257 let mut cur: &'a [u8] = buf;
258 while !cur.is_empty() {
259 // Captured so unknown fields can preserve their raw byte span
260 // (`before_tag.len() - cur.len()` after the payload is consumed).
261 let before_tag = cur;
262 let tag = crate::encoding::Tag::decode(&mut cur)?;
263 cur = self.merge_view_field(tag, cur, before_tag, ctx)?;
264 }
265 Ok(())
266 }
267
268 /// Decode one field's payload into this view (generated per message).
269 ///
270 /// `cur` is the input positioned just past `tag`; the implementation
271 /// returns the remaining input after the field's payload. The
272 /// pass-by-value/return shape (rather than `&mut &'a [u8]`) keeps each
273 /// arm's `&mut` borrow of the slice local to that arm — sub-message
274 /// arms can hand `cur` slices to recursive decode calls without
275 /// fighting a long-lived outer `&mut` reborrow. `before_tag` is the
276 /// input including the tag bytes, for raw-span unknown-field capture.
277 ///
278 /// Hand-written views must supply this (it is the one method the
279 /// provided decode loop requires). A view that instead overrides both
280 /// [`decode_view`](Self::decode_view) and
281 /// [`decode_view_with_ctx`](Self::decode_view_with_ctx) to decode by hand
282 /// never reaches the provided loop, so it can satisfy the trait with a
283 /// one-line `Ok(cur)` stub. The canonical shape is a match on
284 /// `tag.field_number()`. Mark the method `#[inline]`: the provided loop
285 /// calls it once per field across the crate boundary, so the hint lets the
286 /// optimizer fold the match into that loop.
287 ///
288 /// ```rust,ignore
289 /// #[inline]
290 /// fn merge_view_field(
291 /// &mut self,
292 /// tag: buffa::encoding::Tag,
293 /// cur: &'a [u8],
294 /// _before_tag: &'a [u8],
295 /// ctx: buffa::DecodeContext<'_>,
296 /// ) -> Result<&'a [u8], buffa::DecodeError> {
297 /// let mut cur = cur;
298 /// match tag.field_number() {
299 /// 1 => self.id = buffa::types::decode_int32(&mut cur)?,
300 /// 2 => self.name = buffa::types::borrow_str(&mut cur)?,
301 /// _ => buffa::encoding::skip_unknown_field(tag, &mut cur, ctx)?,
302 /// }
303 /// Ok(cur)
304 /// }
305 /// ```
306 ///
307 /// Views that preserve unknown fields capture the raw span — tag
308 /// included — via `before_tag` (the span length is measured *after* the
309 /// payload is consumed) and store it with
310 /// [`UnknownFieldsView::push_record`], which charges the context's
311 /// unknown-field allowance per field (including fields nested in
312 /// unknown groups) so that [`to_owned_message`](Self::to_owned_message)
313 /// cannot exhaust it later; the provided loop stays message-agnostic:
314 ///
315 /// ```rust,ignore
316 /// _ => {
317 /// buffa::encoding::skip_unknown_field(tag, &mut cur, ctx)?;
318 /// let span_len = before_tag.len().checked_sub(cur.len())
319 /// .ok_or(buffa::DecodeError::UnexpectedEof)?;
320 /// self.unknown_fields.push_record(before_tag, span_len, ctx)?;
321 /// }
322 /// ```
323 ///
324 /// The returned slice must be a suffix of `cur` (and hence of
325 /// `before_tag`): the provided loop continues from it, and the
326 /// unknown-field span is measured as `before_tag.len() - cur.len()`, which
327 /// underflows and panics if the returned slice is longer than the input.
328 ///
329 /// # Errors
330 ///
331 /// Returns a [`DecodeError`] on malformed payloads, wire-type mismatches,
332 /// or when a configured decode limit is exceeded.
333 fn merge_view_field(
334 &mut self,
335 tag: crate::encoding::Tag,
336 cur: &'a [u8],
337 before_tag: &'a [u8],
338 ctx: crate::DecodeContext<'_>,
339 ) -> Result<&'a [u8], DecodeError>;
340
341 /// Convert this view to the owned message type.
342 ///
343 /// This allocates and copies all borrowed fields. Equivalent to
344 /// [`to_owned_from_source(None)`](Self::to_owned_from_source).
345 ///
346 /// For views produced by [`decode_view`](Self::decode_view) (or the
347 /// other wire-decoding entry points), this cannot fail: decoding
348 /// charged the unknown-field allowance with exactly the slots that
349 /// re-materializing preserved unknown fields consumes, every span was
350 /// parsed off the wire, and re-materialization replays under the field
351 /// budget and group-nesting depth recorded at decode time. The `Result`
352 /// remains for hand-written view impls and for views holding manually
353 /// pushed ([`UnknownFieldsView::push_raw`]) unknown-field spans.
354 /// [`OwnedView`], which always holds a wire-decoded view, exposes this
355 /// conversion infallibly — see
356 /// [`OwnedView::to_owned_message`](OwnedView::to_owned_message) (and the
357 /// generated `FooOwnedView` wrappers likewise).
358 ///
359 /// # Errors
360 ///
361 /// Returns an error if re-materializing preserved unknown fields fails —
362 /// possible only for views not produced by wire decoding, as described
363 /// above.
364 fn to_owned_message(&self) -> Result<Self::Owned, DecodeError>;
365
366 /// Convert this view to the owned message type, optionally slicing
367 /// `bytes::Bytes`-typed fields from `source` instead of copying.
368 ///
369 /// When `source` is the [`Bytes`] buffer this view was decoded from,
370 /// owned fields configured for `bytes::Bytes` (via the `bytes_fields`
371 /// codegen option) are produced via [`Bytes::slice_ref`] — a refcount
372 /// bump, no allocation or copy. Borrowed fields that fall outside
373 /// `source` (e.g. on a manually-constructed view) and the `None` case
374 /// fall back to [`Bytes::copy_from_slice`].
375 ///
376 /// Generated view types override this; the default delegates to
377 /// [`to_owned_message`](Self::to_owned_message) so hand-written impls
378 /// need only provide that method.
379 ///
380 /// # Errors
381 ///
382 /// Same contract as [`to_owned_message`](Self::to_owned_message).
383 fn to_owned_from_source(&self, source: Option<&Bytes>) -> Result<Self::Owned, DecodeError> {
384 let _ = source;
385 self.to_owned_message()
386 }
387}
388
389/// Exposes the real lifetime of an [`OwnedView`]'s borrows.
390///
391/// `OwnedView<V>` stores `V` with a `'static` lifetime — the actual borrows
392/// point into its internal [`Bytes`] buffer. `ViewReborrow` lets
393/// [`OwnedView::reborrow`] return a reference typed as `&'b V::Reborrowed<'b>`,
394/// tying the borrow to `&'b self` so the compiler can reason about it correctly.
395///
396/// Codegen emits `impl ViewReborrow` automatically for every generated view
397/// type. A hand-written view type used through [`OwnedView`] must provide
398/// it — it is a supertrait of [`ViewLifetimeParametric`], which every
399/// `OwnedView` constructor requires — alongside that `unsafe` marker.
400///
401/// # Soundness
402///
403/// `ViewReborrow` is a **safe** trait. Soundness is established mechanically
404/// by the compiler at each impl site: the [`reborrow`](Self::reborrow) method
405/// body coerces a `&'b Self` (where `Self = FooView<'static>`) to
406/// `&'b Self::Reborrowed<'b>` (= `&'b FooView<'b>`). Rust accepts this only
407/// when `FooView` is **covariant** in its lifetime parameter — a covariant
408/// `FooView<'static>` is a subtype of `FooView<'b>` and the coercion is a
409/// standard subtyping move. Invariant fields (`Cell<&'a T>`, `&'a mut T`,
410/// `fn(&'a T)`) make the type invariant in `'a`; the trait body then fails
411/// to compile and the impl is rejected — which is exactly what should
412/// happen, because narrowing the lifetime of an invariant view *would* be
413/// unsound.
414///
415/// Hand-written impls cannot accidentally introduce undefined behaviour
416/// without writing `unsafe` themselves: the canonical body is just `this`,
417/// which the type checker accepts iff the variance permits the coercion.
418#[rustversion::attr(
419 since(1.78),
420 diagnostic::on_unimplemented(
421 message = "`{Self}` does not implement `ViewReborrow` — required by `OwnedView::reborrow`",
422 note = "for a generated view type, this impl is emitted automatically by codegen",
423 note = "for a hand-written view type `MyView<'a>`, add:\n impl ViewReborrow for MyView<'static> {{\n type Reborrowed<'b> = MyView<'b>;\n fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b> {{ this }}\n }}",
424 note = "your `MessageView` impl must be parametric over the lifetime — `impl<'a> MessageView<'a> for MyView<'a>` — so that both `Self: MessageView<'static>` and `Reborrowed<'b>: MessageView<'b>` hold",
425 note = "`MyView` must be covariant in its lifetime — fields like `&'a T` and `MessageFieldView<...>` are covariant; `Cell<&'a T>` and `&'a mut T` are not, and the trait body `{{ this }}` will fail to compile for invariant types"
426 )
427)]
428pub trait ViewReborrow: MessageView<'static> {
429 /// The same view type with its lifetime shortened to `'b`.
430 ///
431 /// The `Debug` bound is what lets `OwnedView<V>: Debug` hold for every
432 /// `V: ViewReborrow` — generic code needs no `for<'b>` clause of its
433 /// own. Every generated view implements `Debug`.
434 type Reborrowed<'b>: MessageView<'b, Owned = <Self as MessageView<'static>>::Owned>
435 + core::fmt::Debug
436 where
437 Self: 'b;
438
439 /// Coerce `&'b Self` (= `&'b FooView<'static>`) to
440 /// `&'b Self::Reborrowed<'b>` (= `&'b FooView<'b>`). The canonical body
441 /// is just `this`; the compiler accepts it via standard lifetime
442 /// variance for covariant view types.
443 ///
444 /// Called by [`OwnedView::reborrow`]; users shouldn't need to call this
445 /// method directly.
446 fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b>;
447}
448
449/// Implement [`ViewReborrow`] for a generated view type.
450///
451/// Emitted by generated code (one invocation per view struct); the trait's
452/// `on_unimplemented` note shows the equivalent expansion for hand-written
453/// views. A view used through [`OwnedView`] also needs the `unsafe` marker
454/// [`ViewLifetimeParametric`] — see
455/// [`unsafe_impl_view_lifetime_parametric!`](macro@crate::unsafe_impl_view_lifetime_parametric).
456///
457/// ```rust,ignore
458/// buffa::impl_view_reborrow!(MyMessageView);
459/// ```
460#[macro_export]
461macro_rules! impl_view_reborrow {
462 ($ty:ident) => {
463 impl $crate::ViewReborrow for $ty<'static> {
464 type Reborrowed<'b> = $ty<'b>;
465 fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b> {
466 this
467 }
468 }
469 };
470}
471
472/// Marker asserting that a view type is parametric in its buffer lifetime —
473/// the soundness contract behind [`OwnedView`].
474///
475/// `OwnedView<V>` hands `V::decode_view` a slice whose lifetime has been
476/// forged to `'static` while the bytes really live only as long as the
477/// `OwnedView`'s [`Bytes`]. That is sound only if nothing `V` does can let
478/// a borrow of that slice outlive the `V` value itself. Every generated
479/// `FooView<'a>` has this property structurally: the struct is generic
480/// over `'a` and every impl is parametric in it, so no impl can tell
481/// `'static` apart from any other lifetime, and none has a way to stash a
482/// field borrow anywhere that outlives `Self` without writing `unsafe`.
483///
484/// A hand-written `impl MessageView<'static> for MyView` has no such
485/// guarantee: inside `decode_view`, or inside any impl on the view that
486/// `OwnedView` invokes, it can copy a `&'static str` borrowed from the
487/// buffer into a `static`, and the copy dangles once the `OwnedView` drops
488/// — a use-after-free reachable from safe code. Every [`OwnedView`]
489/// constructor therefore requires `V: ViewLifetimeParametric`, so the forged
490/// `'static` slice never reaches a view that has not made this assertion
491/// with an explicit `unsafe impl`.
492///
493/// Codegen emits the impl for every generated view through
494/// [`unsafe_impl_view_lifetime_parametric!`](macro@crate::unsafe_impl_view_lifetime_parametric).
495/// [`ViewReborrow`] is a supertrait:
496/// it is the mechanical witness that the view is covariant in its lifetime,
497/// and it lets `OwnedView` route its own `Debug`, `PartialEq`, `Serialize`
498/// and [`to_owned_message`](OwnedView::to_owned_message) through a
499/// [`reborrow`](ViewReborrow::reborrow)ed `V::Reborrowed<'_>` rather than
500/// the `'static`-typed view (`Clone` is the one impl that must run on `V`
501/// itself, since it has to produce another `V`).
502///
503/// # Safety
504///
505/// Implementors assert that no borrow derived from the `&'static [u8]`
506/// passed to [`MessageView::decode_view`] or
507/// [`decode_view_with_ctx`](MessageView::decode_view_with_ctx) — including
508/// every borrow held in a field of `Self` — can outlive the `Self` value it
509/// was decoded into, nor be exposed at a lifetime longer than a borrow of
510/// that value. Two obligations follow, and they apply to every impl on
511/// `Self` (the lists are illustrative, not exhaustive):
512///
513/// - No impl may copy such a borrow into storage that outlives `Self` — a
514/// `static`, a thread-local, a leaked `Box`, a channel, a longer-lived
515/// struct. That covers the [`MessageView<'static>`](MessageView) impl
516/// (`decode_view`, `decode_view_with_ctx`, `decode_view_ctx`,
517/// `merge_into_view`, `merge_view_field`, `to_owned_message`,
518/// `to_owned_from_source`), `Self`'s `Drop`, `Clone`, `Debug`,
519/// `PartialEq`/`Eq`, `Hash` and (`json` feature) `serde::Serialize`
520/// impls, and anything reachable from those, such as the `Debug` impl of
521/// a field type.
522/// - The [`ViewReborrow`] impl must actually shorten the lifetime:
523/// `Reborrowed<'b>` must be `Self` with its buffer lifetime replaced by
524/// `'b`, exposing no buffer borrow longer than `'b`. (A `MessageView`
525/// impl that is generic over a *second* lifetime can satisfy the GAT's
526/// `MessageView<'b>` bound with `Reborrowed<'b> = Self`, which would let
527/// [`OwnedView::reborrow`] hand out `'static` borrows.)
528///
529/// After `OwnedView`'s reborrow routing, three impls on `V` observe the
530/// forged `'static`: the `MessageView<'static>` decode entry points
531/// (`decode_view` / `decode_view_with_ctx` and what they call), `Clone`, and
532/// [`ViewReborrow::reborrow`] itself, which receives `&'b MyView<'static>`
533/// before shortening it. `Debug`, `PartialEq`, `Serialize` and
534/// `to_owned_message` run on `Reborrowed<'b>` at the real lifetime; a
535/// lifetime-generic view's `Drop` cannot be specialised to `'static` (Rust
536/// requires a `Drop` impl to be as generic as the type), so it is parametric
537/// by construction; and `MessageView::Owned` is `'static` (`Message:
538/// DefaultInstance: 'static`), so `to_owned_message` cannot smuggle a borrow
539/// out through the owned type. An audit of a hand-written view therefore
540/// reduces to: is `decode_view*` parametric (written for `impl<'a>
541/// MessageView<'a>`), is `Clone` derived or parametric, and is `reborrow` the
542/// canonical [`impl_view_reborrow!`] body (`{ this }`), which retains nothing?
543///
544/// The trait is implemented for the `'static` instantiation
545/// (`MyView<'static>`) because that is the type `OwnedView` stores, but the
546/// assertion is about the type constructor `MyView<'_>` and every impl on
547/// it. Prior art: `yoke::Yokeable` is an `unsafe` trait carrying the same
548/// covariance-and-no-capture obligation for the same reason.
549///
550/// The simplest way to satisfy this is the way generated code does: make
551/// the view struct generic over the buffer lifetime (`MyView<'a>`), every
552/// impl other than `ViewReborrow` parametric in it
553/// (`impl<'a> MessageView<'a> for MyView<'a>`,
554/// `impl<'a> Debug for MyView<'a>`, …), and `ViewReborrow` the canonical
555/// [`impl_view_reborrow!`] shape. Parametric code cannot observe that
556/// `'a = 'static`, so the borrow checker itself prevents it from smuggling
557/// a borrow past `Self`'s lifetime. An impl written only for `'static`
558/// (`impl MessageView<'static> for MyView`) may be marked only if the view
559/// holds no borrows from the buffer at all.
560///
561/// # Example
562///
563/// A parametric hand-written view opts in with an `unsafe impl` (the
564/// `SAFETY` comment is the argument above):
565///
566/// ```rust,ignore
567/// // SAFETY: `MyView<'a>` is generic over `'a`; every impl on it other than
568/// // the canonical `impl_view_reborrow!` is parametric in `'a`, so no impl can
569/// // retain a buffer borrow past `Self`.
570/// unsafe impl buffa::ViewLifetimeParametric for MyView<'static> {}
571/// ```
572///
573/// A non-parametric view is rejected at the [`OwnedView::decode`] call
574/// site, so the forged `'static` slice never reaches its `decode_view`:
575///
576/// ```compile_fail,E0277
577/// use buffa::{DecodeContext, DecodeError, MessageView, OwnedView};
578/// use buffa::encoding::Tag;
579/// # use buffa::__doctest_fixtures::Person;
580///
581/// struct Capturing {
582/// name: &'static str,
583/// }
584///
585/// impl MessageView<'static> for Capturing {
586/// type Owned = Person;
587/// fn decode_view(buf: &'static [u8]) -> Result<Self, DecodeError> {
588/// // Sees the forged `'static` and could stash `name` anywhere.
589/// Ok(Self { name: core::str::from_utf8(buf).unwrap_or("") })
590/// }
591/// fn merge_view_field(
592/// &mut self,
593/// _tag: Tag,
594/// cur: &'static [u8],
595/// _before_tag: &'static [u8],
596/// _ctx: DecodeContext<'_>,
597/// ) -> Result<&'static [u8], DecodeError> {
598/// Ok(cur)
599/// }
600/// fn to_owned_message(&self) -> Result<Person, DecodeError> {
601/// Ok(Person::default())
602/// }
603/// }
604///
605/// // error[E0277]: `Capturing` does not implement `ViewLifetimeParametric` —
606/// // required by every `OwnedView` constructor
607/// let _ = OwnedView::<Capturing>::decode(buffa::bytes::Bytes::new());
608/// ```
609#[rustversion::attr(
610 since(1.78),
611 diagnostic::on_unimplemented(
612 message = "`{Self}` does not implement `ViewLifetimeParametric` — required by every `OwnedView` constructor",
613 note = "for a generated view type, this impl is emitted by the matching ReallyMe codegen release: \
614 regenerate the crate that defines `{Self}` with the matching ReallyMe generator release",
615 note = "in code generic over `M: HasMessageView`, add the bound `M::View<'static>: ViewLifetimeParametric` \
616 at the use site — it cannot live on the trait itself",
617 note = "for a hand-written view type, audit it against the trait's `# Safety` section, then add \
618 `unsafe impl buffa::ViewLifetimeParametric for MyView<'static> {{}}` (or \
619 `buffa::unsafe_impl_view_lifetime_parametric!(MyView)`) with a `// SAFETY:` comment stating why \
620 no impl on the view can retain a buffer borrow past the view"
621 )
622)]
623pub unsafe trait ViewLifetimeParametric: ViewReborrow {}
624
625/// Implement [`ViewLifetimeParametric`] for a view type.
626///
627/// Emitted by generated code (one invocation per view struct, next to
628/// [`impl_view_reborrow!`]). It expands to
629/// `unsafe impl ViewLifetimeParametric for $ty<'static> {}`; because the
630/// `unsafe` token originates in this crate's macro rather than in the
631/// consumer's source, the expansion is accepted under
632/// `#![forbid(unsafe_code)]`, which generated code is routinely `include!`d
633/// into.
634///
635/// # Safety
636///
637/// Invoking this macro asserts the [`ViewLifetimeParametric`] contract for
638/// `$ty<'static>` exactly as a hand-written `unsafe impl` would: no impl on
639/// `$ty` may retain a borrow of the decode buffer past the view. Codegen
640/// discharges it structurally — every impl it emits other than the
641/// canonical [`impl_view_reborrow!`] is parametric in the view's lifetime,
642/// and any hand-written view nested as a field is only ever driven through
643/// those parametric impls. A hand-written view type
644/// must be audited against the trait's `# Safety` section before invoking
645/// it, and should carry a `// SAFETY:` comment stating why it holds.
646///
647/// ```rust,ignore
648/// // SAFETY: `MyMessageView<'a>` is generic over `'a` and every impl on it
649/// // is parametric, so no impl can retain a buffer borrow past `Self`.
650/// buffa::unsafe_impl_view_lifetime_parametric!(MyMessageView);
651/// ```
652#[macro_export]
653macro_rules! unsafe_impl_view_lifetime_parametric {
654 (:: $($seg:ident)::+) => {
655 unsafe impl $crate::ViewLifetimeParametric for :: $($seg)::+<'static> {}
656 };
657 ($($seg:ident)::+) => {
658 unsafe impl $crate::ViewLifetimeParametric for $($seg)::+<'static> {}
659 };
660}
661
662/// Links an owned message type to its generated zero-copy view types.
663///
664/// For a message `Foo`, generated code implements this trait as
665/// `View<'a> = FooView<'a>` (the borrowed view) and
666/// `ViewHandle = FooOwnedView` (the self-contained `'static` handle). The
667/// trait lets code that is generic over an owned message name those types —
668/// for example an RPC framework that decodes `M::View<'_>` from a request
669/// body it owns, or holds `M::ViewHandle` items in a stream — without
670/// per-message glue on the consumer's side.
671///
672/// The associated types intentionally carry only structural bounds:
673///
674/// - [`View<'a>`](Self::View) is the message's view, with
675/// [`Owned`](MessageView::Owned)` = Self`.
676/// - [`ViewHandle`](Self::ViewHandle) is convertible from, and exposes via
677/// [`AsRef`], the corresponding `OwnedView<Self::View<'static>>`, so
678/// generic code can reach [`reborrow`](OwnedView::reborrow),
679/// [`bytes`](OwnedView::bytes), and
680/// [`to_owned_message`](OwnedView::to_owned_message) without naming the
681/// concrete wrapper. The wrapper's per-field accessor methods remain
682/// inherent on the concrete type.
683///
684/// Generic code that reaches the view through the handle
685/// (`handle.as_ref().reborrow()` or `.to_owned_message()`) adds
686/// `M::View<'static>: ViewReborrow` as a bound at the use site, and generic
687/// code that decodes a handle
688/// ([`decode_view_handle`](Self::decode_view_handle)) adds
689/// `M::View<'static>: `[`ViewLifetimeParametric`], which implies the former;
690/// every generated view satisfies both. (Neither bound can live on the
691/// trait itself: a `where Self::View<'static>: ViewReborrow` clause
692/// currently trips a GAT normalization error, E0308 "expected
693/// `MessageView<'a>`, found `MessageView<'static>`".)
694///
695/// # Implementing
696///
697/// Implementations are generated alongside the view and owned-view wrapper
698/// (and are therefore gated with them). Hand-written implementations are only
699/// needed for hand-written view types and must follow the same shape.
700#[rustversion::attr(
701 since(1.78),
702 diagnostic::on_unimplemented(
703 message = "`{Self}` does not implement `HasMessageView` — its message-view family was not generated or is not enabled",
704 note = "the `HasMessageView` impl is emitted next to each message's view types: \
705 regenerate the crate that defines `{Self}` with the matching ReallyMe generator release and \
706 views enabled — `generate_views(true)` (on by default) in a buffa-build / \
707 buffa-codegen config, or `views=true` for protoc-gen-reallyme-buffa",
708 note = "if the defining crate feature-gates its generated impls, enabling its views \
709 feature is enough — no regeneration needed"
710 )
711)]
712pub trait HasMessageView: crate::Message + Sized {
713 /// The zero-copy view of `Self`, borrowing from a buffer with lifetime
714 /// `'a`.
715 type View<'a>: MessageView<'a, Owned = Self> + Send + Sync;
716
717 /// The generated `'static` owned-view handle for `Self`
718 /// (`FooOwnedView`).
719 type ViewHandle: From<OwnedView<Self::View<'static>>>
720 + AsRef<OwnedView<Self::View<'static>>>
721 + Send
722 + Sync
723 + 'static;
724
725 /// Decode a borrowed [`View`](Self::View) from a byte slice.
726 ///
727 /// Convenience for generic code: lets a caller bounded only on
728 /// `M: HasMessageView` write `M::decode_view(buf)` instead of the
729 /// associated-type path
730 /// `<M as HasMessageView>::View::decode_view(buf)`. The returned view
731 /// borrows from `buf`. Reading the returned view (e.g.
732 /// [`to_owned_message`](MessageView::to_owned_message)) requires
733 /// [`MessageView`] in scope.
734 ///
735 /// Like the underlying [`MessageView::decode_view`], this does not
736 /// enforce `max_message_size`; use
737 /// [`decode_view_with_options`](Self::decode_view_with_options) for that.
738 ///
739 /// # Errors
740 ///
741 /// Returns [`DecodeError`] if the buffer contains invalid protobuf data or
742 /// exceeds a default recursion, unknown-field, or element-memory limit.
743 #[inline]
744 fn decode_view(buf: &[u8]) -> Result<Self::View<'_>, DecodeError> {
745 <Self::View<'_> as MessageView<'_>>::decode_view(buf)
746 }
747
748 /// Decode a borrowed [`View`](Self::View) under custom
749 /// [`DecodeOptions`](crate::DecodeOptions) (recursion limit, max message
750 /// size, unknown-field limit, and element-memory limit).
751 ///
752 /// Convenience for generic code; equivalent to
753 /// [`DecodeOptions::decode_view::<M::View<'_>>`](crate::DecodeOptions::decode_view).
754 ///
755 /// # Errors
756 ///
757 /// Returns [`DecodeError`] if the buffer is invalid or exceeds the
758 /// configured limits.
759 #[inline]
760 fn decode_view_with_options<'a>(
761 buf: &'a [u8],
762 opts: &crate::DecodeOptions,
763 ) -> Result<Self::View<'a>, DecodeError> {
764 opts.decode_view(buf)
765 }
766
767 /// Decode a [`ViewHandle`](Self::ViewHandle) from a [`Bytes`] buffer.
768 ///
769 /// Convenience for generic code; equivalent to decoding an
770 /// [`OwnedView<Self::View<'static>>`](OwnedView) and converting it with
771 /// `From`.
772 /// Like [`decode_view`](Self::decode_view), this does not enforce
773 /// `max_message_size`; use
774 /// [`decode_view_handle_with_options`](Self::decode_view_handle_with_options)
775 /// for that.
776 ///
777 /// # Errors
778 ///
779 /// Returns [`DecodeError`] if the buffer contains invalid protobuf data or
780 /// exceeds a default recursion, unknown-field, or element-memory limit.
781 fn decode_view_handle(bytes: Bytes) -> Result<Self::ViewHandle, DecodeError>
782 where
783 Self::View<'static>: ViewLifetimeParametric,
784 {
785 Ok(Self::ViewHandle::from(
786 OwnedView::<Self::View<'static>>::decode(bytes)?,
787 ))
788 }
789
790 /// Decode a [`ViewHandle`](Self::ViewHandle) with custom
791 /// [`DecodeOptions`](crate::DecodeOptions) (recursion limit, max message
792 /// size, unknown-field limit, and element-memory limit).
793 ///
794 /// # Errors
795 ///
796 /// Returns [`DecodeError`] if the buffer is invalid or exceeds the
797 /// configured limits.
798 fn decode_view_handle_with_options(
799 bytes: Bytes,
800 opts: &crate::DecodeOptions,
801 ) -> Result<Self::ViewHandle, DecodeError>
802 where
803 Self::View<'static>: ViewLifetimeParametric,
804 {
805 Ok(Self::ViewHandle::from(
806 OwnedView::<Self::View<'static>>::decode_with_options(bytes, opts)?,
807 ))
808 }
809}
810
811/// Produce a [`Bytes`] for a borrowed slice, preferring a zero-copy
812/// [`Bytes::slice_ref`] into `source` when the slice lies within it.
813///
814/// Used by generated [`MessageView::to_owned_from_source`] for
815/// `bytes_fields`. Empty slices return [`Bytes::new`]; slices outside
816/// `source` (or `source = None`) fall back to [`Bytes::copy_from_slice`].
817#[doc(hidden)]
818#[inline]
819pub fn bytes_from_source(source: Option<&Bytes>, slice: &[u8]) -> Bytes {
820 if slice.is_empty() {
821 return Bytes::new();
822 }
823 if let Some(b) = source {
824 if let Some(shared) = try_slice_ref(b, slice) {
825 return shared;
826 }
827 }
828 Bytes::copy_from_slice(slice)
829}
830
831/// Zero-copy [`Bytes::slice_ref`] guarded by `slice_ref`'s own containment
832/// precondition: returns `Some` only when `slice` lies entirely within
833/// `backing`, so callers fall back to a copy rather than panic for slices
834/// from elsewhere. Shared by [`bytes_from_source`] and the
835/// [`Rope`](crate::Rope) backing-buffer capture.
836///
837/// The caller is responsible for excluding empty slices when an empty
838/// result is not wanted (an empty slice's dangling pointer can spuriously
839/// fall inside any range).
840#[inline]
841pub(crate) fn try_slice_ref(backing: &Bytes, slice: &[u8]) -> Option<Bytes> {
842 let b_start = backing.as_ptr() as usize;
843 let s_start = slice.as_ptr() as usize;
844 let b_end = b_start.checked_add(backing.len())?;
845 let s_end = s_start.checked_add(slice.len())?;
846 (s_start >= b_start && s_end <= b_end).then(|| backing.slice_ref(slice))
847}
848
849// The `ViewEncode` twin of `write_sized` in message.rs; the two traits share
850// no supertrait to write it once.
851#[inline]
852fn write_sized<'a, V: ViewEncode<'a>>(
853 view: &V,
854 size: u32,
855 cache: &mut crate::SizeCache,
856 buf: &mut impl EncodeSink,
857) {
858 crate::encode_sink::write_contiguous(
859 size as usize,
860 cache,
861 buf,
862 |cache, sink| view.write_to(cache, sink),
863 |cache, sink| view.write_to(cache, sink),
864 );
865}
866
867/// Serialize a [`MessageView`] directly from its borrowed fields.
868///
869/// Symmetric with [`Message`](crate::Message)'s two-pass
870/// `compute_size` / `write_to` model, but the `&'a str` / `&'a [u8]` /
871/// [`MapView`] / [`RepeatedView`] fields are written by borrow — no
872/// owned-struct intermediary, no per-field `String`/`Vec<u8>` allocations.
873///
874/// Generated `*View<'a>` types implement this trait whenever views are
875/// generated (`generate_views(true)`, the default). Serialization state
876/// lives in the external [`SizeCache`](crate::SizeCache), not the view —
877/// view structs hold no interior mutability and remain `Send + Sync`.
878///
879/// ## When to use
880///
881/// Reach for `ViewEncode` when the source data is already in memory and
882/// you would otherwise allocate an owned message just to encode-then-drop
883/// it — e.g. an RPC handler serializing from app state. If you already
884/// hold the owned message, use [`Message::encode`](crate::Message::encode)
885/// instead; the wire output is identical.
886///
887/// ```rust,ignore
888/// let view = PersonView {
889/// name: "borrowed",
890/// tags: ["a", "b"].iter().copied().collect(),
891/// ..Default::default()
892/// };
893/// let bytes = view.encode_to_vec();
894/// ```
895#[rustversion::attr(
896 since(1.78),
897 diagnostic::on_unimplemented(
898 message = "`{Self}` does not implement `ViewEncode` — view types were not generated for this message",
899 note = "ViewEncode is implemented on every generated `*View<'a>` type; enable `generate_views(true)` (on by default) in your buffa-build / buffa-codegen config"
900 )
901)]
902pub trait ViewEncode<'a>: MessageView<'a> {
903 /// Compute the encoded byte size of this view, recording nested
904 /// sub-message sizes in `cache` for [`write_to`](Self::write_to)
905 /// to consume.
906 ///
907 /// Most callers should use [`encode`](Self::encode) instead, which runs
908 /// both passes with a fresh cache.
909 fn compute_size(&self, cache: &mut crate::SizeCache) -> u32;
910
911 /// Write this view's encoded bytes to a buffer, consuming
912 /// nested-message sizes from `cache` (populated by a prior
913 /// [`compute_size`](Self::compute_size) call on the same cache).
914 ///
915 /// Most callers should use [`encode`](Self::encode) instead. This is a
916 /// low-level primitive: the 2 GiB size check
917 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) lives in the
918 /// provided encode entry points, so callers driving `compute_size` /
919 /// `write_to` directly must validate the size themselves (via
920 /// [`checked_encode_size`](crate::checked_encode_size)).
921 ///
922 /// An implementation must write exactly the number of bytes
923 /// `compute_size` returned. The provided encode methods write a
924 /// `BufMut` into space sized by `compute_size` and panic if `write_to`
925 /// writes more; in debug builds they also panic if it writes fewer.
926 fn write_to(&self, cache: &mut crate::SizeCache, buf: &mut impl EncodeSink);
927
928 /// Compute size, then write. Primary view-encode entry point.
929 ///
930 /// The sink can be any [`BufMut`](bytes::BufMut) (contiguous output) or
931 /// a [`Rope`](crate::Rope); a rope constructed with
932 /// [`with_backing`](crate::Rope::with_backing) on the view's source
933 /// buffer re-encodes large borrowed fields zero-copy.
934 ///
935 /// # Panics
936 ///
937 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
938 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — see
939 /// [`try_encode`](Self::try_encode) for the error-returning variant.
940 /// Also panics, when `buf` is a [`BufMut`](bytes::BufMut), if a manual
941 /// implementation's `write_to` produces more bytes than its
942 /// `compute_size` declared, and in debug builds if it produces a
943 /// different number.
944 #[inline]
945 fn encode(&self, buf: &mut impl EncodeSink) {
946 self.try_encode(buf)
947 .unwrap_or_else(|_| crate::message::encode_size_overflow())
948 }
949
950 /// Encode, returning an error instead of panicking if the encoded size
951 /// exceeds the 2 GiB protobuf limit
952 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
953 ///
954 /// On `Err`, nothing is written to `buf`.
955 ///
956 /// # Errors
957 ///
958 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
959 /// if the encoded size exceeds the limit.
960 fn try_encode(&self, buf: &mut impl EncodeSink) -> Result<(), crate::EncodeError> {
961 let mut cache = crate::SizeCache::new();
962 let size = crate::message::checked_encode_size(self.compute_size(&mut cache))?;
963 write_sized(self, size, &mut cache, buf);
964 Ok(())
965 }
966
967 /// Encode using a caller-supplied [`SizeCache`](crate::SizeCache), for
968 /// reuse across many encodes in a hot loop. Clears the cache first.
969 ///
970 /// # Panics
971 ///
972 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
973 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — see
974 /// [`try_encode_with_cache`](Self::try_encode_with_cache) for the
975 /// error-returning variant.
976 /// Also panics, when `buf` is a [`BufMut`](bytes::BufMut), if a manual
977 /// implementation's `write_to` produces more bytes than its
978 /// `compute_size` declared, and in debug builds if it produces a
979 /// different number.
980 #[inline]
981 fn encode_with_cache(&self, cache: &mut crate::SizeCache, buf: &mut impl EncodeSink) {
982 self.try_encode_with_cache(cache, buf)
983 .unwrap_or_else(|_| crate::message::encode_size_overflow())
984 }
985
986 /// Encode with a caller-supplied [`SizeCache`](crate::SizeCache),
987 /// returning an error instead of panicking if the encoded size exceeds
988 /// the 2 GiB protobuf limit ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
989 /// Clears the cache first.
990 ///
991 /// On `Err`, nothing is written to `buf`.
992 ///
993 /// # Errors
994 ///
995 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
996 /// if the encoded size exceeds the limit.
997 fn try_encode_with_cache(
998 &self,
999 cache: &mut crate::SizeCache,
1000 buf: &mut impl EncodeSink,
1001 ) -> Result<(), crate::EncodeError> {
1002 cache.clear();
1003 let size = crate::message::checked_encode_size(self.compute_size(cache))?;
1004 write_sized(self, size, cache, buf);
1005 Ok(())
1006 }
1007
1008 /// Encode this view into `buf` only if its encoded size fits within
1009 /// `max_bytes`, using a single size pass that is then reused for the write.
1010 ///
1011 /// This avoids the double tree-walk that `try_encoded_len` + `encode`
1012 /// would require: one `compute_size` pass populates the
1013 /// [`SizeCache`](crate::SizeCache); the budget check happens before
1014 /// `write_to` runs, so on `Err` nothing is written to `buf`.
1015 ///
1016 /// Returns the encoded body length on success (excludes any length prefix
1017 /// you add for framing) — useful for metrics or frame sizing. Note that
1018 /// this return type is `u32`, unlike `try_encode`'s `()`. `max_bytes` is
1019 /// also `u32`; callers with a `usize` budget can cast with
1020 /// `u32::try_from(budget).unwrap_or(u32::MAX)`.
1021 ///
1022 /// # Errors
1023 ///
1024 /// - [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
1025 /// if the encoded size exceeds the 2 GiB protobuf limit
1026 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
1027 /// `MessageTooLarge` takes precedence if both limits are exceeded.
1028 /// - [`EncodeError::ExceedsBudget`](crate::EncodeError::ExceedsBudget)
1029 /// if the encoded size is within the protobuf limit but exceeds
1030 /// `max_bytes`.
1031 fn try_encode_bounded(
1032 &self,
1033 max_bytes: u32,
1034 buf: &mut impl EncodeSink,
1035 ) -> Result<u32, crate::EncodeError> {
1036 let mut cache = crate::SizeCache::new();
1037 self.try_encode_bounded_with_cache(max_bytes, &mut cache, buf)
1038 }
1039
1040 /// Like [`try_encode_bounded`](Self::try_encode_bounded) but reuses an
1041 /// existing [`SizeCache`](crate::SizeCache), clearing it first.
1042 ///
1043 /// Prefer
1044 /// [`SizeCachePool::try_encode_view_bounded`](crate::SizeCachePool::try_encode_view_bounded)
1045 /// for hot-loop use — the pool amortizes the cache's spill allocation.
1046 ///
1047 /// # Errors
1048 ///
1049 /// Same as [`try_encode_bounded`](Self::try_encode_bounded).
1050 fn try_encode_bounded_with_cache(
1051 &self,
1052 max_bytes: u32,
1053 cache: &mut crate::SizeCache,
1054 buf: &mut impl EncodeSink,
1055 ) -> Result<u32, crate::EncodeError> {
1056 cache.clear();
1057 let len = crate::message::checked_encode_size(self.compute_size(cache))?;
1058 if len > max_bytes {
1059 return Err(crate::EncodeError::ExceedsBudget { len, max_bytes });
1060 }
1061 write_sized(self, len, cache, buf);
1062 Ok(len)
1063 }
1064
1065 /// Compute the encoded byte size of this view.
1066 ///
1067 /// Walks the view tree, discarding the intermediate
1068 /// [`SizeCache`](crate::SizeCache). If you also intend to encode,
1069 /// prefer [`encode`](Self::encode) or [`encode_to_vec`](Self::encode_to_vec)
1070 /// — they do a single size pass and reuse the cache for the write.
1071 ///
1072 /// # Panics
1073 ///
1074 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
1075 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — see
1076 /// [`try_encoded_len`](Self::try_encoded_len) for the error-returning
1077 /// variant.
1078 #[inline]
1079 #[must_use]
1080 fn encoded_len(&self) -> u32 {
1081 self.try_encoded_len()
1082 .unwrap_or_else(|_| crate::message::encode_size_overflow())
1083 }
1084
1085 /// Compute the encoded byte size, returning an error instead of
1086 /// panicking if it exceeds the 2 GiB protobuf limit
1087 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
1088 ///
1089 /// # Errors
1090 ///
1091 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
1092 /// if the encoded size exceeds the limit.
1093 fn try_encoded_len(&self) -> Result<u32, crate::EncodeError> {
1094 crate::message::checked_encode_size(self.compute_size(&mut crate::SizeCache::new()))
1095 }
1096
1097 /// Encode this view as a length-delimited byte sequence.
1098 ///
1099 /// # Panics
1100 ///
1101 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
1102 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)); the check runs
1103 /// before the length prefix is written, so nothing reaches `buf` on
1104 /// failure. See
1105 /// [`try_encode_length_delimited`](Self::try_encode_length_delimited)
1106 /// for the error-returning variant.
1107 /// Also panics, when `buf` is a [`BufMut`](bytes::BufMut), if a manual
1108 /// implementation's `write_to` produces more bytes than its
1109 /// `compute_size` declared, and in debug builds if it produces a
1110 /// different number.
1111 #[inline]
1112 fn encode_length_delimited(&self, buf: &mut impl EncodeSink) {
1113 self.try_encode_length_delimited(buf)
1114 .unwrap_or_else(|_| crate::message::encode_size_overflow())
1115 }
1116
1117 /// Encode as a length-delimited byte sequence, returning an error
1118 /// instead of panicking if the encoded size exceeds the 2 GiB protobuf
1119 /// limit ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
1120 ///
1121 /// On `Err`, nothing is written to `buf`.
1122 ///
1123 /// # Errors
1124 ///
1125 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
1126 /// if the encoded size exceeds the limit.
1127 fn try_encode_length_delimited(
1128 &self,
1129 buf: &mut impl EncodeSink,
1130 ) -> Result<(), crate::EncodeError> {
1131 let mut cache = crate::SizeCache::new();
1132 let len = crate::message::checked_encode_size(self.compute_size(&mut cache))?;
1133 crate::encoding::encode_varint(u64::from(len), buf);
1134 write_sized(self, len, &mut cache, buf);
1135 Ok(())
1136 }
1137
1138 /// Encode this view to a new `Vec<u8>`.
1139 ///
1140 /// # Panics
1141 ///
1142 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
1143 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — see
1144 /// [`try_encode_to_vec`](Self::try_encode_to_vec) for the
1145 /// error-returning variant. Also panics if a manual
1146 /// implementation's `write_to` produces more bytes than its
1147 /// `compute_size` declared, and in debug builds if it produces a
1148 /// different number.
1149 // Direct body rather than delegating to try_encode_to_vec — the
1150 // Result<Vec<u8>> niche survives inlining and costs measurably in
1151 // callers; see Message::encode_to_vec for the measurement.
1152 #[inline]
1153 #[must_use]
1154 fn encode_to_vec(&self) -> alloc::vec::Vec<u8> {
1155 let mut cache = crate::SizeCache::new();
1156 let size = match crate::message::checked_encode_size(self.compute_size(&mut cache)) {
1157 Ok(size) => size as usize,
1158 Err(_) => crate::message::encode_size_overflow(),
1159 };
1160 let buf =
1161 crate::encode_sink::write_to_new_vec(size, |sink| self.write_to(&mut cache, sink));
1162 crate::message::debug_assert_two_pass(buf.len(), size);
1163 buf
1164 }
1165
1166 /// Encode to a new `Vec<u8>`, returning an error instead of panicking
1167 /// if the encoded size exceeds the 2 GiB protobuf limit
1168 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
1169 ///
1170 /// # Errors
1171 ///
1172 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
1173 /// if the encoded size exceeds the limit.
1174 ///
1175 /// # Panics
1176 ///
1177 /// Panics if a manual implementation's `write_to` produces more
1178 /// bytes than its `compute_size` declared, and in debug builds if it
1179 /// produces a different number.
1180 fn try_encode_to_vec(&self) -> Result<alloc::vec::Vec<u8>, crate::EncodeError> {
1181 let mut cache = crate::SizeCache::new();
1182 let size = crate::message::checked_encode_size(self.compute_size(&mut cache))? as usize;
1183 let buf =
1184 crate::encode_sink::write_to_new_vec(size, |sink| self.write_to(&mut cache, sink));
1185 crate::message::debug_assert_two_pass(buf.len(), size);
1186 Ok(buf)
1187 }
1188
1189 /// Encode this view to a new [`bytes::Bytes`].
1190 ///
1191 /// This is `Bytes::from(self.encode_to_vec())`, zero-copy for the
1192 /// exactly-sized vector; an implementation overriding
1193 /// [`encode_to_vec`](Self::encode_to_vec) must not call this from it.
1194 ///
1195 /// # Panics
1196 ///
1197 /// Panics if the encoded size exceeds the 2 GiB protobuf limit
1198 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — see
1199 /// [`try_encode_to_bytes`](Self::try_encode_to_bytes) for the
1200 /// error-returning variant. Also panics if a manual
1201 /// implementation's `write_to` produces more bytes than its
1202 /// `compute_size` declared, and in debug builds if it produces a
1203 /// different number.
1204 // Via `Vec<u8>` — see `Message::encode_to_bytes`.
1205 #[inline]
1206 #[must_use]
1207 fn encode_to_bytes(&self) -> Bytes {
1208 Bytes::from(self.encode_to_vec())
1209 }
1210
1211 /// Encode to a new [`bytes::Bytes`], returning an error instead of
1212 /// panicking if the encoded size exceeds the 2 GiB protobuf limit
1213 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)).
1214 ///
1215 /// # Errors
1216 ///
1217 /// Returns [`EncodeError::MessageTooLarge`](crate::EncodeError::MessageTooLarge)
1218 /// if the encoded size exceeds the limit.
1219 ///
1220 /// # Panics
1221 ///
1222 /// Panics if a manual implementation's `write_to` produces more
1223 /// bytes than its `compute_size` declared, and in debug builds if it
1224 /// produces a different number.
1225 fn try_encode_to_bytes(&self) -> Result<Bytes, crate::EncodeError> {
1226 self.try_encode_to_vec().map(Bytes::from)
1227 }
1228}
1229
1230/// Provides access to a lazily-initialized default view instance.
1231///
1232/// View types implement this trait so that [`MessageFieldView`] can
1233/// dereference to a default when unset, just as [`MessageField`](crate::MessageField)
1234/// does for owned types via [`DefaultInstance`](crate::DefaultInstance).
1235///
1236/// Generated view types like `FooView<'a>` contain only covariant borrows
1237/// (`&'a str`, `&'a [u8]`, etc.). A default view holds only `'static` data
1238/// (`""`, `&[]`, `0`), so an implementation stores a single
1239/// `&'static FooView<'static>` and returns it at the caller's lifetime via
1240/// ordinary covariant subtyping — the compiler verifies covariance at the
1241/// `impl` site, so no `unsafe` is required.
1242///
1243/// # Recommended implementation
1244///
1245/// The pattern codegen uses (and the recommended pattern for hand-written
1246/// view types) stores the instance in a static
1247/// [`once_cell::race::OnceBox`] (re-exported as
1248/// `::buffa::__private::OnceBox`):
1249///
1250/// ```rust,ignore
1251/// impl<'v> DefaultViewInstance for MyView<'v> {
1252/// fn default_view_instance<'a>() -> &'a Self
1253/// where
1254/// Self: 'a,
1255/// {
1256/// static VALUE: ::buffa::__private::OnceBox<MyView<'static>>
1257/// = ::buffa::__private::OnceBox::new();
1258/// VALUE.get_or_init(|| Box::new(<MyView<'static>>::default()))
1259/// }
1260/// }
1261/// ```
1262///
1263/// The return expression has type `&'static MyView<'static>`; the compiler
1264/// coerces it to `&'a MyView<'v>` iff `MyView` is covariant in `'v` —
1265/// non-covariant view types fail to compile here rather than risk an
1266/// unsound cast.
1267///
1268/// # Non-covariant types are rejected
1269///
1270/// A type that is invariant in its lifetime parameter cannot satisfy the
1271/// recommended pattern, because the `&'static T<'static> → &'a T<'v>`
1272/// coercion is refused:
1273///
1274/// ```compile_fail
1275/// # use core::marker::PhantomData;
1276/// // `fn(&'v ()) -> &'v ()` is invariant in 'v, making `Invariant<'v>` invariant.
1277/// struct Invariant<'v>(PhantomData<fn(&'v ()) -> &'v ()>);
1278/// static INST: Invariant<'static> = Invariant(PhantomData);
1279///
1280/// impl<'v> buffa::view::DefaultViewInstance for Invariant<'v> {
1281/// fn default_view_instance<'a>() -> &'a Self where Self: 'a {
1282/// // error: lifetime may not live long enough
1283/// // note: requirement occurs because of the type `Invariant<'_>`,
1284/// // which makes the generic argument `'_` invariant
1285/// &INST
1286/// }
1287/// }
1288/// ```
1289pub trait DefaultViewInstance {
1290 /// Return a reference to the single default view instance.
1291 ///
1292 /// The lifetime `'a` is caller-chosen up to `Self: 'a`, so a
1293 /// `FooView<'v>` can serve its `'static` default at any `'a ≤ 'v`.
1294 fn default_view_instance<'a>() -> &'a Self
1295 where
1296 Self: 'a;
1297}
1298
1299/// Implement [`DefaultViewInstance`] for a generated view type via a
1300/// lazily-initialized `OnceBox<FooView<'static>>` singleton.
1301///
1302/// Emitted by generated code (one invocation per view struct). The static
1303/// holds the `'static` instantiation; returning it at any shorter `'a` is
1304/// sound because view lifetimes are covariant.
1305///
1306/// ```rust,ignore
1307/// buffa::impl_default_view_instance!(MyMessageView);
1308/// ```
1309#[macro_export]
1310macro_rules! impl_default_view_instance {
1311 ($ty:ident) => {
1312 impl<'v> $crate::DefaultViewInstance for $ty<'v> {
1313 fn default_view_instance<'a>() -> &'a Self
1314 where
1315 Self: 'a,
1316 {
1317 static VALUE: $crate::__private::OnceBox<$ty<'static>> =
1318 $crate::__private::OnceBox::new();
1319 VALUE.get_or_init(|| {
1320 $crate::alloc::boxed::Box::new(
1321 <$ty<'static> as ::core::default::Default>::default(),
1322 )
1323 })
1324 }
1325 }
1326 };
1327}
1328
1329/// A borrowed view of an optional message field.
1330///
1331/// Analogous to [`MessageField<T>`](crate::MessageField) but for the view
1332/// layer. Like `MessageField`, the inner view is **boxed** — recursive
1333/// message types (`Foo { NestedMessage { corecursive: Foo } }`) would
1334/// otherwise have infinite size. The box is API-transparent: `Deref`
1335/// returns `&V`, and `set()` takes `V` by value.
1336///
1337/// When `V` implements [`DefaultViewInstance`], this type implements
1338/// [`Deref<Target = V>`](core::ops::Deref), returning a reference to a
1339/// static default instance when the field is unset — making view code
1340/// identical to owned code for field access:
1341///
1342/// ```rust,ignore
1343/// // Both work the same, regardless of whether `address` is set:
1344/// let city = owned_msg.address.city; // MessageField<Address>
1345/// let city = view_msg.address.city; // MessageFieldView<AddressView>
1346/// ```
1347///
1348/// The lifetime of the contained view type `V` (e.g. `AddressView<'a>`)
1349/// ties this to the input buffer — no separate lifetime parameter is
1350/// needed here.
1351#[derive(Clone, Debug)]
1352pub struct MessageFieldView<V> {
1353 inner: Option<alloc::boxed::Box<V>>,
1354}
1355
1356impl<V> MessageFieldView<V> {
1357 /// An unset field (the default).
1358 #[inline]
1359 pub const fn unset() -> Self {
1360 Self { inner: None }
1361 }
1362
1363 /// A set field with the given view value.
1364 #[inline]
1365 pub fn set(v: V) -> Self {
1366 Self {
1367 inner: Some(alloc::boxed::Box::new(v)),
1368 }
1369 }
1370
1371 /// Alias for [`set`](Self::set), mirroring owned
1372 /// [`MessageField::some`](crate::MessageField::some).
1373 #[inline]
1374 pub fn some(v: V) -> Self {
1375 Self::set(v)
1376 }
1377
1378 /// Returns `true` if the field has a value.
1379 #[inline]
1380 pub const fn is_set(&self) -> bool {
1381 self.inner.is_some()
1382 }
1383
1384 /// Returns `true` if the field has no value.
1385 #[inline]
1386 pub const fn is_unset(&self) -> bool {
1387 self.inner.is_none()
1388 }
1389
1390 /// Get a reference to the inner view, or `None` if unset.
1391 #[inline]
1392 pub fn as_option(&self) -> Option<&V> {
1393 self.inner.as_deref()
1394 }
1395
1396 /// Get a mutable reference to the inner view, or `None` if unset.
1397 ///
1398 /// Used by generated decode code to merge a second occurrence of a
1399 /// message field into an existing value (proto merge semantics).
1400 #[inline]
1401 pub fn as_mut(&mut self) -> Option<&mut V> {
1402 self.inner.as_deref_mut()
1403 }
1404}
1405
1406impl<'a, V: ViewEncode<'a>> MessageFieldView<V> {
1407 /// Forward to the inner view's [`compute_size`](ViewEncode::compute_size),
1408 /// or `0` if unset. Generated `compute_size` calls this for nested-message
1409 /// fields, mirroring [`MessageField`](crate::MessageField) on the owned side.
1410 #[inline]
1411 pub fn compute_size(&self, cache: &mut crate::SizeCache) -> u32 {
1412 self.inner.as_deref().map_or(0, |v| v.compute_size(cache))
1413 }
1414
1415 /// Forward to the inner view's [`write_to`](ViewEncode::write_to);
1416 /// no-op if unset.
1417 #[inline]
1418 pub fn write_to(&self, cache: &mut crate::SizeCache, buf: &mut impl EncodeSink) {
1419 if let Some(v) = self.inner.as_deref() {
1420 v.write_to(cache, buf);
1421 }
1422 }
1423}
1424
1425impl<V> Default for MessageFieldView<V> {
1426 #[inline]
1427 fn default() -> Self {
1428 Self::unset()
1429 }
1430}
1431
1432impl<V> From<V> for MessageFieldView<V> {
1433 #[inline]
1434 fn from(v: V) -> Self {
1435 Self::set(v)
1436 }
1437}
1438
1439impl<V: DefaultViewInstance> core::ops::Deref for MessageFieldView<V> {
1440 type Target = V;
1441
1442 #[inline]
1443 fn deref(&self) -> &V {
1444 self.inner
1445 .as_deref()
1446 .unwrap_or_else(V::default_view_instance)
1447 }
1448}
1449
1450/// Presence-aware equality, matching [`MessageField`](crate::MessageField):
1451/// two unset fields are equal, two set fields are equal when their views are,
1452/// and an unset field never equals a set one, not even one set to the default,
1453/// since only the set field is on the wire. Compare `*a == *b` (needs
1454/// [`DefaultViewInstance`]) to ignore presence.
1455///
1456/// `view_a == view_b` agrees with
1457/// `view_a.to_owned_message() == view_b.to_owned_message()`.
1458impl<V: PartialEq> PartialEq for MessageFieldView<V> {
1459 fn eq(&self, other: &Self) -> bool {
1460 // Presence is part of the value, as for `MessageField`: an unset field
1461 // differs from one set to its default.
1462 match (&self.inner, &other.inner) {
1463 // Two unset fields are equal regardless of whether V::PartialEq is
1464 // reflexive (e.g. a view containing an f64 NaN).
1465 (None, None) => true,
1466 (Some(a), Some(b)) => a == b,
1467 _ => false,
1468 }
1469 }
1470}
1471
1472impl<V: Eq> Eq for MessageFieldView<V> {}
1473
1474/// Hashes presence and the view, as `Option<&V>` does, so that it agrees with
1475/// `==`, like [`MessageField`](crate::MessageField)'s `Hash`.
1476impl<V: core::hash::Hash> core::hash::Hash for MessageFieldView<V> {
1477 #[inline]
1478 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
1479 self.as_option().hash(state);
1480 }
1481}
1482
1483// ---------------------------------------------------------------------------
1484// Lazy views (generated under the `lazy_views` codegen option)
1485// ---------------------------------------------------------------------------
1486
1487/// The trait implemented by generated lazy view types (`FooLazyView<'a>`).
1488///
1489/// Lazy views are a separate, additive type family generated alongside the
1490/// eager `FooView` family under the `lazy_views` codegen option. Where
1491/// [`MessageView`]'s contract is "decode succeeded ⇒ the whole tree was
1492/// validated", a lazy view's [`decode_lazy`](Self::decode_lazy) performs a
1493/// single non-recursive scan over the message's own fields: scalar, string,
1494/// and bytes fields are borrowed exactly as in the eager view, while nested
1495/// and repeated message fields are *recorded* as undecoded byte ranges (see
1496/// [`LazyMessageFieldView`] / [`LazyRepeatedView`]) and decoded only on
1497/// access. Deferred validation is therefore visible in the type and trait
1498/// bound — generic code over `MessageView` never silently inherits it.
1499///
1500/// Generated lazy-view structs may gain fields across releases; see the
1501/// [struct evolution policy on `Message`](crate::Message#struct-evolution-policy).
1502pub trait LazyMessageView<'a>: Sized {
1503 /// The corresponding owned message type.
1504 type Owned: crate::Message;
1505
1506 /// Decode a lazy view from `buf`: one scan over the message's own
1507 /// fields, deferring nested message fields.
1508 ///
1509 /// # Errors
1510 ///
1511 /// Returns [`DecodeError`] if the message's *own* fields are malformed,
1512 /// or [`DecodeError::ElementMemoryLimitExceeded`] if recording its
1513 /// repeated elements exceeds the default element-memory budget — the
1514 /// `Vec` of deferred byte ranges is real memory even though the elements
1515 /// themselves are not decoded yet. Deferred sub-message bytes are
1516 /// **not** validated here; they surface errors on access.
1517 fn decode_lazy(buf: &'a [u8]) -> Result<Self, DecodeError>;
1518
1519 /// Decode a lazy view under custom decode limits.
1520 ///
1521 /// Used by [`DecodeOptions::decode_lazy_view`](crate::DecodeOptions::decode_lazy_view).
1522 /// The budgets remaining at each deferred field's position are recorded
1523 /// and charged when that field is accessed, so custom limits flow through
1524 /// deferred decoding. The default implementation delegates to
1525 /// [`decode_lazy`](Self::decode_lazy) and **ignores the context**;
1526 /// generated code always overrides it.
1527 ///
1528 /// # Errors
1529 ///
1530 /// Same contract as [`decode_lazy`](Self::decode_lazy), plus
1531 /// [`DecodeError::RecursionLimitExceeded`],
1532 /// [`DecodeError::UnknownFieldLimitExceeded`], or
1533 /// [`DecodeError::ElementMemoryLimitExceeded`] when `ctx`'s budgets are
1534 /// exhausted by the message's own fields.
1535 fn decode_lazy_with_ctx(
1536 buf: &'a [u8],
1537 ctx: crate::DecodeContext<'_>,
1538 ) -> Result<Self, DecodeError> {
1539 let _ = ctx;
1540 Self::decode_lazy(buf)
1541 }
1542
1543 /// Merge fields decoded from `buf` into this view (proto merge
1544 /// semantics: singular scalars last-wins, repeated append, deferred
1545 /// message fragments accumulate).
1546 ///
1547 /// Used by [`LazyMessageFieldView::get`] to reassemble a field whose
1548 /// value was split across multiple wire occurrences — application code
1549 /// rarely calls this directly.
1550 ///
1551 /// # Errors
1552 ///
1553 /// Same contract as [`decode_lazy_with_ctx`](Self::decode_lazy_with_ctx).
1554 fn merge_lazy(
1555 &mut self,
1556 buf: &'a [u8],
1557 ctx: crate::DecodeContext<'_>,
1558 ) -> Result<(), DecodeError>;
1559
1560 /// Convert this view to the owned message type.
1561 ///
1562 /// This decodes every deferred sub-message, so it is where deferred
1563 /// validation errors surface. Each deferred subtree decodes under its
1564 /// own replayed unknown-field allowance (see
1565 /// [`LazyMessageFieldView::get`]), so the conversion's total
1566 /// unknown-field records are bounded per subtree, not globally as in an
1567 /// eager decode.
1568 ///
1569 /// # Errors
1570 ///
1571 /// Returns the [`DecodeError`] that accessing a malformed or
1572 /// over-budget deferred field would have reported. Unlike
1573 /// [`MessageView::to_owned_message`], this conversion can genuinely
1574 /// fail for a wire-decoded lazy view: deferred subtrees were never
1575 /// validated (or charged against the unknown-field allowance) at
1576 /// decode time, so their errors surface here.
1577 fn to_owned_message(&self) -> Result<Self::Owned, DecodeError>;
1578}
1579
1580/// Fragments of one singular message field. `Many` only arises when an
1581/// encoder split the field across occurrences, keeping the common
1582/// single-occurrence path allocation-free.
1583#[derive(Clone)]
1584enum LazyFragments<'a> {
1585 None,
1586 One(&'a [u8]),
1587 Many(alloc::vec::Vec<&'a [u8]>),
1588}
1589
1590/// A deferred view of a singular message field on a lazy view.
1591///
1592/// Unlike [`MessageFieldView`] — which eagerly decodes (and boxes) the
1593/// sub-message during decode — this stores only the field's undecoded wire
1594/// bytes and decodes a fresh `V` on each [`get`](Self::get), so decoding the
1595/// enclosing message does not allocate or recurse into sub-messages the
1596/// caller never reads.
1597///
1598/// `get` returns a freshly-decoded view each call (views are thin borrows,
1599/// so this is cheap) and does not cache — bind the result when reading
1600/// several fields.
1601///
1602/// # Merge semantics
1603///
1604/// A singular message field may legally appear more than once on the wire;
1605/// decoders must merge the occurrences. This type stores each occurrence's
1606/// bytes as a separate fragment and [`get`](Self::get) replays them in order
1607/// (decode the first, [`LazyMessageView::merge_lazy`] the rest), so the
1608/// result matches the eager and owned decoders.
1609///
1610/// # Deferred validation and budgets
1611///
1612/// The fragment bytes are *not* validated when the enclosing view is
1613/// decoded; a malformed sub-message surfaces as a [`DecodeError`] from
1614/// [`get`](Self::get). The recursion budget, unknown-field allowance, and
1615/// element-memory budget remaining when the field was recorded are stored
1616/// alongside the fragments,
1617/// and each access replays them as a fresh per-subtree budget (see
1618/// [`get`](Self::get) for the approximation this implies). Deep lazy chains
1619/// fail with [`DecodeError::RecursionLimitExceeded`] at the same boundary as
1620/// the eager decoder, and custom limits passed to the enclosing
1621/// [`decode_lazy_with_ctx`](LazyMessageView::decode_lazy_with_ctx) flow
1622/// through.
1623///
1624/// # Re-encoding
1625///
1626/// `ViewEncode` on the enclosing lazy view replays the recorded fragments
1627/// byte-for-byte **without validating them** — re-encoding a never-accessed
1628/// malformed field round-trips its bytes silently.
1629pub struct LazyMessageFieldView<'a, V> {
1630 raw: LazyFragments<'a>,
1631 depth: u32,
1632 allowance: usize,
1633 elem_allowance: usize,
1634 reject_unknown_fields: bool,
1635 _marker: core::marker::PhantomData<fn() -> V>,
1636}
1637
1638impl<'a, V> LazyMessageFieldView<'a, V> {
1639 /// An unset field (the default).
1640 #[inline]
1641 pub const fn unset() -> Self {
1642 Self {
1643 raw: LazyFragments::None,
1644 // Sentinels: the first `push_fragment` lowers these to its
1645 // recorded budgets, so custom limits above the defaults aren't
1646 // clamped.
1647 depth: u32::MAX,
1648 allowance: usize::MAX,
1649 elem_allowance: usize::MAX,
1650 reject_unknown_fields: false,
1651 _marker: core::marker::PhantomData,
1652 }
1653 }
1654
1655 /// A set field carrying the sub-message's undecoded wire bytes, with the
1656 /// default recursion, unknown-field, and element-memory budgets for
1657 /// access.
1658 #[inline]
1659 pub const fn from_bytes(raw: &'a [u8]) -> Self {
1660 Self {
1661 raw: LazyFragments::One(raw),
1662 depth: crate::RECURSION_LIMIT,
1663 allowance: crate::DEFAULT_UNKNOWN_FIELD_LIMIT,
1664 elem_allowance: crate::DEFAULT_ELEMENT_MEMORY_LIMIT,
1665 reject_unknown_fields: false,
1666 _marker: core::marker::PhantomData,
1667 }
1668 }
1669
1670 /// Append one wire occurrence of the field (used by generated
1671 /// `decode_lazy`). Fragments accumulate in wire order; [`get`](Self::get)
1672 /// merges them. `ctx` carries the recursion budget and unknown-field
1673 /// allowance remaining at the record site; the smallest pushed budgets
1674 /// are charged on access.
1675 #[doc(hidden)]
1676 #[inline]
1677 pub fn push_fragment(&mut self, raw: &'a [u8], ctx: crate::DecodeContext<'_>) {
1678 self.depth = self.depth.min(ctx.depth());
1679 self.allowance = self.allowance.min(ctx.remaining_unknown_fields());
1680 self.reject_unknown_fields |= ctx.rejects_unknown_fields();
1681 if let Some(remaining) = ctx.remaining_element_memory() {
1682 self.elem_allowance = self.elem_allowance.min(remaining);
1683 }
1684 self.raw = match core::mem::replace(&mut self.raw, LazyFragments::None) {
1685 LazyFragments::None => LazyFragments::One(raw),
1686 LazyFragments::One(first) => LazyFragments::Many(alloc::vec![first, raw]),
1687 LazyFragments::Many(mut frags) => {
1688 frags.push(raw);
1689 LazyFragments::Many(frags)
1690 }
1691 };
1692 }
1693
1694 /// Whether the field is present.
1695 #[inline]
1696 pub const fn is_set(&self) -> bool {
1697 !matches!(self.raw, LazyFragments::None)
1698 }
1699
1700 /// Whether the field has no value.
1701 #[inline]
1702 pub const fn is_unset(&self) -> bool {
1703 matches!(self.raw, LazyFragments::None)
1704 }
1705
1706 /// The undecoded wire fragments, in wire order (empty if unset).
1707 ///
1708 /// A singular message field that appeared exactly once on the wire — the
1709 /// common case — yields one fragment. Encoders that split the field
1710 /// across multiple occurrences yield one fragment per occurrence;
1711 /// [`get`](Self::get) merges them per proto semantics.
1712 #[inline]
1713 pub fn fragments(&self) -> &[&'a [u8]] {
1714 match &self.raw {
1715 LazyFragments::None => &[],
1716 LazyFragments::One(raw) => core::slice::from_ref(raw),
1717 LazyFragments::Many(frags) => frags,
1718 }
1719 }
1720}
1721
1722impl<'a, V: LazyMessageView<'a>> LazyMessageFieldView<'a, V> {
1723 /// Decode and return the sub-message view, or `None` if unset.
1724 ///
1725 /// Multiple wire fragments are merged per proto semantics (see the type
1726 /// docs). The view is re-decoded on every call; there is no cache — bind
1727 /// the result when reading several fields. Note the shape difference
1728 /// from [`LazyRepeatedView::get`], which returns `Option<Result<V, _>>`.
1729 ///
1730 /// Each access rebuilds a fresh decode context from the budgets recorded
1731 /// at decode time, so every deferred subtree independently gets the full
1732 /// recorded unknown-field allowance and element-memory budget rather than
1733 /// sharing one pool with its siblings (the original decode call's shared
1734 /// budgets are gone by access time). Both are therefore *per-subtree*
1735 /// bounds on the lazy path, not the global decode-time caps the eager
1736 /// decoder enforces: a full traversal can materialize records
1737 /// proportional to input size, where eager
1738 /// [`decode_view`](crate::DecodeOptions::decode_view) rejects such input
1739 /// up front. Prefer the eager path for untrusted input if that global
1740 /// bound matters.
1741 ///
1742 /// # Errors
1743 ///
1744 /// Returns [`DecodeError`] if the deferred bytes are not a valid
1745 /// encoding of `V` — validation happens here, not when the enclosing
1746 /// view was decoded — [`DecodeError::RecursionLimitExceeded`] when the
1747 /// recursion budget recorded at decode time is exhausted,
1748 /// [`DecodeError::UnknownFieldLimitExceeded`] when the unknown-field
1749 /// allowance is, or [`DecodeError::ElementMemoryLimitExceeded`] when the
1750 /// element-memory budget is.
1751 #[inline]
1752 pub fn get(&self) -> Result<Option<V>, DecodeError> {
1753 let allowance = core::cell::Cell::new(self.allowance);
1754 let elem = core::cell::Cell::new(self.elem_allowance);
1755 let ctx = crate::DecodeContext::new(self.depth, &allowance)
1756 .with_unknown_field_rejection(self.reject_unknown_fields)
1757 .with_element_memory(&elem);
1758 match &self.raw {
1759 LazyFragments::None => Ok(None),
1760 LazyFragments::One(raw) => V::decode_lazy_with_ctx(raw, ctx).map(Some),
1761 LazyFragments::Many(frags) => {
1762 // `Many` always holds ≥ 2 fragments (see `push_fragment`);
1763 // the guard is belt-and-suspenders.
1764 let mut iter = frags.iter();
1765 let Some(first) = iter.next() else {
1766 return Ok(None);
1767 };
1768 let mut view = V::decode_lazy_with_ctx(first, ctx)?;
1769 for frag in iter {
1770 view.merge_lazy(frag, ctx)?;
1771 }
1772 Ok(Some(view))
1773 }
1774 }
1775 }
1776
1777 /// Like [`get`](Self::get), but an unset field decodes to the default
1778 /// view — the lazy analogue of [`MessageFieldView`]'s deref-to-default,
1779 /// for the common read path:
1780 ///
1781 /// ```rust,ignore
1782 /// let city = view.address.get_or_default()?.city;
1783 /// ```
1784 ///
1785 /// # Errors
1786 ///
1787 /// Same as [`get`](Self::get).
1788 #[inline]
1789 pub fn get_or_default(&self) -> Result<V, DecodeError>
1790 where
1791 V: Default,
1792 {
1793 Ok(self.get()?.unwrap_or_default())
1794 }
1795}
1796
1797impl<V> Clone for LazyMessageFieldView<'_, V> {
1798 #[inline]
1799 fn clone(&self) -> Self {
1800 Self {
1801 raw: self.raw.clone(),
1802 depth: self.depth,
1803 allowance: self.allowance,
1804 elem_allowance: self.elem_allowance,
1805 reject_unknown_fields: self.reject_unknown_fields,
1806 _marker: core::marker::PhantomData,
1807 }
1808 }
1809}
1810impl<V> Default for LazyMessageFieldView<'_, V> {
1811 #[inline]
1812 fn default() -> Self {
1813 Self::unset()
1814 }
1815}
1816impl<V> core::fmt::Debug for LazyMessageFieldView<'_, V> {
1817 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1818 f.debug_struct("LazyMessageFieldView")
1819 .field("is_set", &self.is_set())
1820 .field("fragments", &self.fragments().len())
1821 .finish()
1822 }
1823}
1824
1825/// A deferred view of a repeated message field on a lazy view.
1826///
1827/// Holds the wire byte-slice of each element (cheap pointers) and decodes a
1828/// fresh element view on access ([`get`](Self::get)) or iteration
1829/// ([`iter`](Self::iter)), instead of eagerly decoding every element into a
1830/// `Vec` like [`RepeatedView`].
1831///
1832/// Element bytes are *not* validated when the enclosing view is decoded; a
1833/// malformed element surfaces as a [`DecodeError`] from `get`/`iter`. Unlike
1834/// [`RepeatedView`], this type is not slice-backed: there is no `Deref` or
1835/// indexing, use `get`/`iter`/`len`. Budgets and re-encoding behave as on
1836/// [`LazyMessageFieldView`].
1837pub struct LazyRepeatedView<'a, V> {
1838 elements: alloc::vec::Vec<&'a [u8]>,
1839 depth: u32,
1840 allowance: usize,
1841 elem_allowance: usize,
1842 reject_unknown_fields: bool,
1843 _marker: core::marker::PhantomData<fn() -> V>,
1844}
1845
1846impl<'a, V> LazyRepeatedView<'a, V> {
1847 /// An empty repeated field.
1848 #[inline]
1849 pub fn new() -> Self {
1850 Self {
1851 elements: alloc::vec::Vec::new(),
1852 // Sentinels — see `LazyMessageFieldView::unset`.
1853 depth: u32::MAX,
1854 allowance: usize::MAX,
1855 elem_allowance: usize::MAX,
1856 reject_unknown_fields: false,
1857 _marker: core::marker::PhantomData,
1858 }
1859 }
1860
1861 /// Number of elements.
1862 #[inline]
1863 pub fn len(&self) -> usize {
1864 self.elements.len()
1865 }
1866
1867 /// Whether the field has no elements.
1868 #[inline]
1869 pub fn is_empty(&self) -> bool {
1870 self.elements.is_empty()
1871 }
1872
1873 /// The undecoded wire bytes of each element, in wire order.
1874 #[inline]
1875 pub fn raw_elements(&self) -> &[&'a [u8]] {
1876 &self.elements
1877 }
1878
1879 /// Append an element's undecoded bytes (used by generated `decode_lazy`).
1880 /// `ctx` carries the recursion budget, unknown-field allowance, and
1881 /// element-memory budget remaining at the record site; the smallest
1882 /// pushed budgets are charged on access.
1883 #[doc(hidden)]
1884 #[inline]
1885 pub fn push_bytes(&mut self, raw: &'a [u8], ctx: crate::DecodeContext<'_>) {
1886 self.depth = self.depth.min(ctx.depth());
1887 self.allowance = self.allowance.min(ctx.remaining_unknown_fields());
1888 self.reject_unknown_fields |= ctx.rejects_unknown_fields();
1889 if let Some(remaining) = ctx.remaining_element_memory() {
1890 self.elem_allowance = self.elem_allowance.min(remaining);
1891 }
1892 self.elements.push(raw);
1893 }
1894}
1895
1896/// Decode one deferred element under a fresh context carrying the budgets
1897/// recorded at decode time. Each access decodes independently, so each gets
1898/// the full recorded allowance — a per-subtree bound, not the eager
1899/// decoder's shared global pool (see [`LazyMessageFieldView::get`]).
1900#[inline]
1901fn decode_deferred<'a, V: LazyMessageView<'a>>(
1902 raw: &'a [u8],
1903 depth: u32,
1904 allowance: usize,
1905 elem_allowance: usize,
1906 reject_unknown_fields: bool,
1907) -> Result<V, DecodeError> {
1908 let cell = core::cell::Cell::new(allowance);
1909 let elem = core::cell::Cell::new(elem_allowance);
1910 V::decode_lazy_with_ctx(
1911 raw,
1912 crate::DecodeContext::new(depth, &cell)
1913 .with_unknown_field_rejection(reject_unknown_fields)
1914 .with_element_memory(&elem),
1915 )
1916}
1917
1918impl<'a, V: LazyMessageView<'a>> LazyRepeatedView<'a, V> {
1919 /// Decode the element at `index`, or `None` if out of range.
1920 ///
1921 /// Re-decodes on every call (no cache) — bind the result when reading
1922 /// multiple fields, and avoid calling it inside a tight loop over the
1923 /// same index. Note the shape difference from
1924 /// [`LazyMessageFieldView::get`], which returns `Result<Option<V>, _>`.
1925 #[inline]
1926 pub fn get(&self, index: usize) -> Option<Result<V, DecodeError>> {
1927 self.elements.get(index).map(|b| {
1928 decode_deferred(
1929 b,
1930 self.depth,
1931 self.allowance,
1932 self.elem_allowance,
1933 self.reject_unknown_fields,
1934 )
1935 })
1936 }
1937
1938 /// Like [`get`](Self::get) with the layers flipped to match
1939 /// [`LazyMessageFieldView::get`]'s `Result<Option<_>, _>` shape:
1940 /// out-of-range yields `Ok(None)`.
1941 ///
1942 /// # Errors
1943 ///
1944 /// Same as [`get`](Self::get).
1945 #[inline]
1946 pub fn try_get(&self, index: usize) -> Result<Option<V>, DecodeError> {
1947 self.get(index).transpose()
1948 }
1949
1950 /// Iterate the elements, decoding each on the fly.
1951 ///
1952 /// Yields `Result<V, DecodeError>` — element bytes are validated here,
1953 /// not when the enclosing view was decoded. Each pass over the iterator
1954 /// re-decodes the elements (no cache).
1955 #[inline]
1956 pub fn iter(&self) -> LazyRepeatedIter<'_, 'a, V> {
1957 LazyRepeatedIter {
1958 inner: self.elements.iter(),
1959 depth: self.depth,
1960 allowance: self.allowance,
1961 elem_allowance: self.elem_allowance,
1962 reject_unknown_fields: self.reject_unknown_fields,
1963 _marker: core::marker::PhantomData,
1964 }
1965 }
1966}
1967
1968impl<'s, 'a, V: LazyMessageView<'a>> IntoIterator for &'s LazyRepeatedView<'a, V> {
1969 type Item = Result<V, DecodeError>;
1970 type IntoIter = LazyRepeatedIter<'s, 'a, V>;
1971
1972 #[inline]
1973 fn into_iter(self) -> Self::IntoIter {
1974 self.iter()
1975 }
1976}
1977
1978/// Iterator over a [`LazyRepeatedView`], decoding each element on access.
1979///
1980/// [`nth`](Iterator::nth), [`nth_back`](DoubleEndedIterator::nth_back),
1981/// [`count`](Iterator::count) and [`last`](Iterator::last) skip elements
1982/// without decoding them, so a skipped element is not validated: a malformed
1983/// element is reported only when it is yielded.
1984#[derive(Clone, Debug)]
1985pub struct LazyRepeatedIter<'s, 'a, V> {
1986 inner: core::slice::Iter<'s, &'a [u8]>,
1987 depth: u32,
1988 allowance: usize,
1989 elem_allowance: usize,
1990 reject_unknown_fields: bool,
1991 _marker: core::marker::PhantomData<fn() -> V>,
1992}
1993
1994impl<'a, V: LazyMessageView<'a>> Iterator for LazyRepeatedIter<'_, 'a, V> {
1995 type Item = Result<V, DecodeError>;
1996
1997 #[inline]
1998 fn next(&mut self) -> Option<Self::Item> {
1999 self.inner.next().map(|b| {
2000 decode_deferred(
2001 b,
2002 self.depth,
2003 self.allowance,
2004 self.elem_allowance,
2005 self.reject_unknown_fields,
2006 )
2007 })
2008 }
2009
2010 #[inline]
2011 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2012 self.inner.nth(n).map(|b| {
2013 decode_deferred(
2014 b,
2015 self.depth,
2016 self.allowance,
2017 self.elem_allowance,
2018 self.reject_unknown_fields,
2019 )
2020 })
2021 }
2022
2023 #[inline]
2024 fn count(self) -> usize {
2025 self.inner.count()
2026 }
2027
2028 #[inline]
2029 fn last(mut self) -> Option<Self::Item> {
2030 self.next_back()
2031 }
2032
2033 #[inline]
2034 fn size_hint(&self) -> (usize, Option<usize>) {
2035 self.inner.size_hint()
2036 }
2037}
2038
2039impl<'a, V: LazyMessageView<'a>> DoubleEndedIterator for LazyRepeatedIter<'_, 'a, V> {
2040 #[inline]
2041 fn next_back(&mut self) -> Option<Self::Item> {
2042 self.inner.next_back().map(|b| {
2043 decode_deferred(
2044 b,
2045 self.depth,
2046 self.allowance,
2047 self.elem_allowance,
2048 self.reject_unknown_fields,
2049 )
2050 })
2051 }
2052
2053 #[inline]
2054 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2055 self.inner.nth_back(n).map(|b| {
2056 decode_deferred(
2057 b,
2058 self.depth,
2059 self.allowance,
2060 self.elem_allowance,
2061 self.reject_unknown_fields,
2062 )
2063 })
2064 }
2065}
2066
2067impl<'a, V: LazyMessageView<'a>> ExactSizeIterator for LazyRepeatedIter<'_, 'a, V> {}
2068
2069impl<V> Clone for LazyRepeatedView<'_, V> {
2070 #[inline]
2071 fn clone(&self) -> Self {
2072 Self {
2073 elements: self.elements.clone(),
2074 depth: self.depth,
2075 allowance: self.allowance,
2076 elem_allowance: self.elem_allowance,
2077 reject_unknown_fields: self.reject_unknown_fields,
2078 _marker: core::marker::PhantomData,
2079 }
2080 }
2081}
2082impl<V> Default for LazyRepeatedView<'_, V> {
2083 #[inline]
2084 fn default() -> Self {
2085 Self::new()
2086 }
2087}
2088impl<V> core::fmt::Debug for LazyRepeatedView<'_, V> {
2089 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2090 f.debug_struct("LazyRepeatedView")
2091 .field("len", &self.len())
2092 .finish()
2093 }
2094}
2095
2096/// A borrowed view of a repeated field.
2097///
2098/// For scalar repeated fields, this is backed by a decoded `Vec` (scalars
2099/// can't be zero-copy because they require varint decoding). For string and
2100/// bytes repeated fields, elements borrow from the input buffer.
2101#[derive(Clone, Debug, PartialEq, Eq)]
2102pub struct RepeatedView<'a, T> {
2103 elements: alloc::vec::Vec<T>,
2104 _marker: core::marker::PhantomData<&'a ()>,
2105}
2106
2107impl<'a, T> RepeatedView<'a, T> {
2108 /// Create from a vec of decoded elements.
2109 pub fn new(elements: alloc::vec::Vec<T>) -> Self {
2110 Self {
2111 elements,
2112 _marker: core::marker::PhantomData,
2113 }
2114 }
2115
2116 /// Returns the number of elements.
2117 pub fn len(&self) -> usize {
2118 self.elements.len()
2119 }
2120
2121 /// Returns `true` if the repeated field contains no elements.
2122 pub fn is_empty(&self) -> bool {
2123 self.elements.is_empty()
2124 }
2125
2126 /// Append an element (used by generated `decode_view` code).
2127 #[doc(hidden)]
2128 pub fn push(&mut self, elem: T) {
2129 self.elements.push(elem);
2130 }
2131
2132 /// Reserve capacity for at least `additional` more elements (used by
2133 /// generated `decode_view` code as a pre-allocation hint for packed
2134 /// repeated scalars). For varint elements the hint is an upper bound
2135 /// (every element occupies at least one byte on the wire); for fixed-
2136 /// size elements it is the exact remaining element count.
2137 #[doc(hidden)]
2138 pub fn reserve(&mut self, additional: usize) {
2139 self.elements.reserve(additional);
2140 }
2141
2142 /// Mutable access to the backing vec (used by generated `decode_view`
2143 /// code to decode packed fixed-width payloads in one bulk call).
2144 #[doc(hidden)]
2145 pub fn as_mut_vec(&mut self) -> &mut alloc::vec::Vec<T> {
2146 &mut self.elements
2147 }
2148
2149 /// Returns an iterator over the elements.
2150 pub fn iter(&self) -> core::slice::Iter<'_, T> {
2151 self.elements.iter()
2152 }
2153}
2154
2155impl<'a, T> Default for RepeatedView<'a, T> {
2156 fn default() -> Self {
2157 Self {
2158 elements: alloc::vec::Vec::new(),
2159 _marker: core::marker::PhantomData,
2160 }
2161 }
2162}
2163
2164impl<'a, T> core::ops::Deref for RepeatedView<'a, T> {
2165 type Target = [T];
2166
2167 fn deref(&self) -> &[T] {
2168 &self.elements
2169 }
2170}
2171
2172impl<'a, T> IntoIterator for RepeatedView<'a, T> {
2173 type Item = T;
2174 type IntoIter = alloc::vec::IntoIter<T>;
2175
2176 fn into_iter(self) -> Self::IntoIter {
2177 self.elements.into_iter()
2178 }
2179}
2180
2181impl<'b, 'a, T> IntoIterator for &'b RepeatedView<'a, T> {
2182 type Item = &'b T;
2183 type IntoIter = core::slice::Iter<'b, T>;
2184
2185 fn into_iter(self) -> Self::IntoIter {
2186 self.elements.iter()
2187 }
2188}
2189
2190impl<'a, T> From<alloc::vec::Vec<T>> for RepeatedView<'a, T> {
2191 fn from(elements: alloc::vec::Vec<T>) -> Self {
2192 Self::new(elements)
2193 }
2194}
2195
2196impl<'a, T> FromIterator<T> for RepeatedView<'a, T> {
2197 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2198 Self::new(iter.into_iter().collect())
2199 }
2200}
2201
2202/// A borrowed view of a map field.
2203///
2204/// Protobuf `map<K, V>` fields are encoded as repeated sub-messages, each
2205/// containing a key (field 1) and value (field 2). This type stores the
2206/// decoded entries in a `Vec<(K, V)>`, borrowing string and bytes keys/values
2207/// directly from the input buffer.
2208///
2209/// Lookup is O(n) linear scan, which is appropriate for the typically small
2210/// maps found in protobuf messages (metadata labels, headers, etc.).
2211/// If duplicate keys appear on the wire, [`get`](MapView::get) returns the
2212/// last occurrence (last-write-wins, per the protobuf spec). That rule is
2213/// about whole entries; *within* one entry, a repeated scalar key or value
2214/// also last-wins, while a repeated message value merges — the same as the
2215/// owned decoder.
2216///
2217/// For larger maps where O(1) lookup matters, collect into a `HashMap`:
2218///
2219/// ```ignore
2220/// use std::collections::HashMap;
2221/// let index: HashMap<&str, &str> = view.labels.into_iter().collect();
2222/// ```
2223///
2224/// Duplicate keys resolve last-write-wins in the collected map (matching
2225/// proto map semantics), since `HashMap::from_iter` keeps the last value.
2226///
2227/// # Allocation
2228///
2229/// Like [`RepeatedView`], the `Vec` backing store requires allocation.
2230/// The individual keys and values borrow from the input buffer where possible
2231/// (string keys as `&'a str`, bytes values as `&'a [u8]`).
2232#[derive(Clone, Debug, PartialEq, Eq)]
2233pub struct MapView<'a, K, V> {
2234 entries: alloc::vec::Vec<(K, V)>,
2235 _marker: core::marker::PhantomData<&'a ()>,
2236}
2237
2238impl<'a, K, V> MapView<'a, K, V> {
2239 /// Construct from a `Vec` of entries, for [`ViewEncode`] use.
2240 ///
2241 /// Duplicate keys are kept and all encoded — valid protobuf wire data
2242 /// (decoders apply last-write-wins). Mirrors [`RepeatedView::new`].
2243 pub fn new(entries: alloc::vec::Vec<(K, V)>) -> Self {
2244 Self {
2245 entries,
2246 _marker: core::marker::PhantomData,
2247 }
2248 }
2249
2250 /// Returns the number of entries (including duplicates).
2251 pub fn len(&self) -> usize {
2252 self.entries.len()
2253 }
2254
2255 /// Returns `true` if there are no entries.
2256 pub fn is_empty(&self) -> bool {
2257 self.entries.is_empty()
2258 }
2259
2260 /// Append a key-value pair (used by generated `decode_view` code).
2261 #[doc(hidden)]
2262 pub fn push(&mut self, key: K, value: V) {
2263 self.entries.push((key, value));
2264 }
2265
2266 /// Iterate over all entries in wire order.
2267 ///
2268 /// If duplicate keys exist, all occurrences are yielded.
2269 pub fn iter(&self) -> core::slice::Iter<'_, (K, V)> {
2270 self.entries.iter()
2271 }
2272
2273 /// Iterate over all keys in wire order.
2274 pub fn keys(&self) -> impl Iterator<Item = &K> {
2275 self.entries.iter().map(|(k, _)| k)
2276 }
2277
2278 /// Iterate over all values in wire order.
2279 pub fn values(&self) -> impl Iterator<Item = &V> {
2280 self.entries.iter().map(|(_, v)| v)
2281 }
2282
2283 /// Look up a value by key, returning the last occurrence (last-write-wins).
2284 ///
2285 /// Accepts any type that `K` can borrow as, so `map.get("key")` works
2286 /// when `K` is `&str`. O(n) scan.
2287 pub fn get<Q>(&self, key: &Q) -> Option<&V>
2288 where
2289 K: core::borrow::Borrow<Q>,
2290 Q: PartialEq + ?Sized,
2291 {
2292 self.entries
2293 .iter()
2294 .rev()
2295 .find(|(k, _)| k.borrow() == key)
2296 .map(|(_, v)| v)
2297 }
2298
2299 /// Returns `true` if an entry with the given key exists.
2300 pub fn contains_key<Q>(&self, key: &Q) -> bool
2301 where
2302 K: core::borrow::Borrow<Q>,
2303 Q: PartialEq + ?Sized,
2304 {
2305 self.entries.iter().any(|(k, _)| k.borrow() == key)
2306 }
2307
2308 /// Iterate over key-value pairs with duplicate keys removed.
2309 ///
2310 /// Each distinct key is yielded **exactly once, at the position of its
2311 /// last wire occurrence, carrying that occurrence's value** — i.e.
2312 /// last-write-wins, mirroring the merge semantics that an owned
2313 /// `HashMap` decode applies. Callers that need first-occurrence position
2314 /// should use [`iter`](Self::iter) and filter themselves.
2315 ///
2316 /// Used by the generated view `Serialize` impl: a JSON object cannot
2317 /// hold duplicate keys, but `MapView` preserves all wire entries
2318 /// (including malformed duplicates), so the JSON encode path must
2319 /// deduplicate.
2320 ///
2321 /// The work happens when this is called, not lazily: it sorts an index
2322 /// vector, `O(n log n)` over the wire-entry count regardless of how many
2323 /// entries are duplicates, allocating one `Vec<usize>`. Survivors are
2324 /// yielded in wire order. A map with at most one entry skips the sort.
2325 ///
2326 /// # Panics
2327 ///
2328 /// Only if `K`'s [`Ord`] is not a total order, in which case the
2329 /// underlying `sort_unstable_by` may panic.
2330 #[must_use = "the deduplication runs when this is called; dropping the iterator wastes it"]
2331 pub fn iter_unique(&self) -> impl ExactSizeIterator<Item = &(K, V)>
2332 where
2333 K: Ord,
2334 {
2335 let entries = &self.entries;
2336 last_occurrence_indices(entries)
2337 .into_iter()
2338 .map(move |i| &entries[i])
2339 }
2340
2341 /// Count of distinct keys (`iter_unique().len()`). Same cost as
2342 /// [`iter_unique`](Self::iter_unique); a caller that needs both should
2343 /// call `iter_unique` once and take its `len()`.
2344 ///
2345 /// # Panics
2346 ///
2347 /// As [`iter_unique`](Self::iter_unique).
2348 #[must_use]
2349 pub fn len_unique(&self) -> usize
2350 where
2351 K: Ord,
2352 {
2353 last_occurrence_indices(&self.entries).len()
2354 }
2355}
2356
2357/// Indices of the last occurrence of each distinct key, in ascending index
2358/// order.
2359///
2360/// Sorting by `(key, index)` groups equal keys into contiguous runs whose
2361/// final element is the last wire occurrence, which is the one last-write-wins
2362/// keeps. Compacting those in place and re-sorting by index restores wire
2363/// order for the caller.
2364///
2365/// Sorting rather than hashing because `K` carries no `Hash` bound, `no_std`
2366/// builds have no `HashSet`, and these keys come off the wire — hashing them
2367/// with buffa's default `foldhash`, which does not advertise HashDoS
2368/// resistance, would trade a quadratic scan for a collision-flooding one.
2369fn last_occurrence_indices<K: Ord, V>(entries: &[(K, V)]) -> alloc::vec::Vec<usize> {
2370 let n = entries.len();
2371 if n <= 1 {
2372 // Nothing to deduplicate, and the common tiny-map case skips the sort.
2373 return (0..n).collect();
2374 }
2375 let mut order: alloc::vec::Vec<usize> = (0..n).collect();
2376 order.sort_unstable_by(|&a, &b| entries[a].0.cmp(&entries[b].0).then_with(|| a.cmp(&b)));
2377 let mut kept = 0usize;
2378 for r in 0..n {
2379 // `cmp` rather than `!=`, so grouping uses the same relation the sort did.
2380 let last_of_run = r + 1 == n || entries[order[r + 1]].0.cmp(&entries[order[r]].0).is_ne();
2381 if last_of_run {
2382 order[kept] = order[r];
2383 kept += 1;
2384 }
2385 }
2386 order.truncate(kept);
2387 order.sort_unstable();
2388 order
2389}
2390
2391impl<'a, K, V> From<alloc::vec::Vec<(K, V)>> for MapView<'a, K, V> {
2392 fn from(entries: alloc::vec::Vec<(K, V)>) -> Self {
2393 Self::new(entries)
2394 }
2395}
2396
2397/// Duplicate keys are kept and all encoded; see [`MapView::new`].
2398impl<'a, K, V> FromIterator<(K, V)> for MapView<'a, K, V> {
2399 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
2400 Self::new(iter.into_iter().collect())
2401 }
2402}
2403
2404impl<'a, K, V> Default for MapView<'a, K, V> {
2405 fn default() -> Self {
2406 Self {
2407 entries: alloc::vec::Vec::new(),
2408 _marker: core::marker::PhantomData,
2409 }
2410 }
2411}
2412
2413impl<'b, 'a, K, V> IntoIterator for &'b MapView<'a, K, V> {
2414 type Item = &'b (K, V);
2415 type IntoIter = core::slice::Iter<'b, (K, V)>;
2416
2417 fn into_iter(self) -> Self::IntoIter {
2418 self.entries.iter()
2419 }
2420}
2421
2422impl<'a, K, V> IntoIterator for MapView<'a, K, V> {
2423 type Item = (K, V);
2424 type IntoIter = alloc::vec::IntoIter<(K, V)>;
2425
2426 fn into_iter(self) -> Self::IntoIter {
2427 self.entries.into_iter()
2428 }
2429}
2430
2431/// One unknown-field wire record: either a span borrowed from the input
2432/// buffer, or synthetic bytes for a value with no borrowable source span.
2433#[derive(Clone, Debug)]
2434enum UnknownFieldsViewRecord<'a> {
2435 Borrowed(&'a [u8]),
2436 Owned(alloc::vec::Vec<u8>),
2437}
2438
2439impl UnknownFieldsViewRecord<'_> {
2440 fn as_slice(&self) -> &[u8] {
2441 match self {
2442 Self::Borrowed(span) => span,
2443 Self::Owned(bytes) => bytes,
2444 }
2445 }
2446}
2447
2448/// A borrowed view of unknown fields.
2449///
2450/// Stores unknown fields as wire records rather than decoded values, enabling
2451/// zero-copy round-tripping for borrowable input spans. Borrowed spans may
2452/// hold **one or more consecutive** complete `(tag, value)` records: adjacent
2453/// unknown fields are coalesced into a single span, so a long run of unknown
2454/// fields costs one `Vec` slot rather than one per field. Synthetic records
2455/// cover cases where the view decoder must preserve a value that has no
2456/// borrowable source span.
2457/// Coalescing bounds the view's memory only — the decode-time
2458/// unknown-field allowance is still charged per field (see
2459/// [`push_record`](Self::push_record)).
2460#[derive(Clone, Default)]
2461pub struct UnknownFieldsView<'a> {
2462 // Boxed, so this type is one pointer wide and holds no inline heap owner.
2463 // Every generated view embeds one by value; with the records inline, the
2464 // view becomes an owning aggregate that the compiler moves with
2465 // out-of-line `memcpy` calls instead of inline vector stores, which costs
2466 // view-decode throughput on message-dense shapes even when no unknown
2467 // field is ever pushed. The allocation happens on the first push.
2468 state: Option<alloc::boxed::Box<UnknownFieldsState<'a>>>,
2469}
2470
2471/// The records and replay accounting, allocated once a view turns out to
2472/// carry an unknown field.
2473#[derive(Clone, Default)]
2474struct UnknownFieldsState<'a> {
2475 /// Unknown wire records in decode order. Borrowed records may each hold
2476 /// one or more complete `(tag, value)` records; owned records are
2477 /// synthetic wire bytes for values that have no borrowable source span.
2478 records: alloc::vec::Vec<UnknownFieldsViewRecord<'a>>,
2479 /// The input-buffer tail starting at the first byte of the last span,
2480 /// kept so [`push_record`](Self::push_record) can extend that span over
2481 /// an adjacent record by re-slicing `last_tail` — never by widening the
2482 /// narrowed span reference, which would be provenance-unsound.
2483 last_tail: Option<&'a [u8]>,
2484 /// Total slots charged against the decode-time unknown-field allowance
2485 /// across every [`push_record`](Self::push_record) — exactly the number
2486 /// of `UnknownField`s [`to_owned`](Self::to_owned) re-materializes, so
2487 /// replay runs under precisely this budget and cannot exhaust it.
2488 to_owned_budget: usize,
2489 /// Deepest group nesting across all pushed records — the recursion
2490 /// depth [`to_owned`](Self::to_owned)'s replay needs, regardless of the
2491 /// (possibly larger) recursion limit the view was decoded under.
2492 to_owned_depth: u32,
2493 /// Set by [`push_raw`](Self::push_raw): the view holds spans that were
2494 /// never charged at decode time, so [`to_owned`](Self::to_owned) grants
2495 /// the default limits on top of the tracked budget and can fail.
2496 manual_spans: bool,
2497}
2498
2499// Manual impl: `last_tail` is an internal coalescing cursor that extends to
2500// the end of the input buffer — deriving Debug would dump the remaining
2501// message bytes on every `{:?}` print.
2502impl core::fmt::Debug for UnknownFieldsView<'_> {
2503 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2504 f.debug_struct("UnknownFieldsView")
2505 .field("records", &self.records_slice())
2506 .finish_non_exhaustive()
2507 }
2508}
2509
2510impl<'a> UnknownFieldsView<'a> {
2511 /// The state, created on first use.
2512 ///
2513 /// The `Some` test inlines and only the allocation is out of line, so a
2514 /// run of unknown records pays the branch once per record rather than a
2515 /// call: every push after the first finds the state already there.
2516 #[inline]
2517 fn state_mut(&mut self) -> &mut UnknownFieldsState<'a> {
2518 self.state.get_or_insert_with(Self::alloc_state)
2519 }
2520
2521 /// Out of line: this runs once, when a message turns out to carry an
2522 /// unknown field at all.
2523 #[cold]
2524 fn alloc_state() -> alloc::boxed::Box<UnknownFieldsState<'a>> {
2525 alloc::boxed::Box::default()
2526 }
2527
2528 /// The records, or an empty slice when nothing was ever pushed.
2529 #[inline]
2530 fn records_slice(&self) -> &[UnknownFieldsViewRecord<'a>] {
2531 self.state.as_ref().map_or(&[], |st| st.records.as_slice())
2532 }
2533
2534 /// Creates an empty view.
2535 pub fn new() -> Self {
2536 Self::default()
2537 }
2538
2539 #[doc(hidden)]
2540 pub fn push_raw(&mut self, span: &'a [u8]) {
2541 let st = self.state_mut();
2542 st.records.push(UnknownFieldsViewRecord::Borrowed(span));
2543 // A manually pushed span has no known position in the input buffer,
2544 // so coalescing must not extend it — and it was never charged
2545 // against a decode allowance, so to_owned falls back to the default
2546 // limits for it.
2547 st.last_tail = None;
2548 st.manual_spans = true;
2549 }
2550
2551 /// Record one unknown wire record of `span_len` bytes starting at the
2552 /// head of `tail`, where `tail` extends from the record's first byte to
2553 /// the end of the input buffer.
2554 ///
2555 /// Every record charges `ctx`'s unknown-field allowance with exactly the
2556 /// slots [`to_owned`](Self::to_owned) will re-materialize it into — one
2557 /// for the record's field plus, for group records, one per nested field.
2558 /// The charge total (and the deepest group nesting) is accumulated on
2559 /// the view as the conversion replay budget, so a view that decoded
2560 /// successfully always converts.
2561 ///
2562 /// If the record starts exactly where the previous one ended, the
2563 /// previous span is extended in place instead of pushing a new one —
2564 /// coalescing saves memory (no allocation, no `Vec` slot), not
2565 /// allowance.
2566 ///
2567 /// Marked `#[cold]`: every caller is an exceptional-value route — the
2568 /// unrecognized-field arm of a generated view merge, and the arms that
2569 /// preserve an unrecognized value of a closed enum (singular and map
2570 /// entry). None runs when the payload matches the schema, so the loop
2571 /// that inlines around them is laid out as though they never do.
2572 /// Decoding from a newer producer does take these routes, once per field
2573 /// it added, and pays for that choice.
2574 ///
2575 /// # Errors
2576 ///
2577 /// Returns [`DecodeError::UnknownFieldLimitExceeded`] when the allowance
2578 /// is exhausted, or [`DecodeError::UnexpectedEof`] if `span_len` exceeds
2579 /// `tail`.
2580 #[doc(hidden)]
2581 #[cold]
2582 pub fn push_record(
2583 &mut self,
2584 tail: &'a [u8],
2585 span_len: usize,
2586 ctx: crate::DecodeContext<'_>,
2587 ) -> Result<(), crate::DecodeError> {
2588 if span_len > tail.len() {
2589 return Err(crate::DecodeError::UnexpectedEof);
2590 }
2591 let charge = crate::encoding::register_unknown_record(&tail[..span_len], ctx)?;
2592 self.push_borrowed_record(tail, span_len, charge.fields, charge.depth)
2593 }
2594
2595 fn push_borrowed_record(
2596 &mut self,
2597 tail: &'a [u8],
2598 span_len: usize,
2599 fields: usize,
2600 depth: u32,
2601 ) -> Result<(), crate::DecodeError> {
2602 let st = self.state_mut();
2603 st.to_owned_budget = st
2604 .to_owned_budget
2605 .checked_add(fields)
2606 .ok_or(crate::DecodeError::MessageTooLarge)?;
2607 st.to_owned_depth = st.to_owned_depth.max(depth);
2608 if let (Some(UnknownFieldsViewRecord::Borrowed(last)), Some(prev_tail)) =
2609 (st.records.last_mut(), st.last_tail)
2610 {
2611 let prev_len = last.len();
2612 // Contiguous if the new record begins exactly one past the end
2613 // of the previous span. Both checks are plain pointer/length
2614 // comparisons; the extension below re-slices `prev_tail`, whose
2615 // provenance covers the combined range.
2616 let combined = prev_len
2617 .checked_add(span_len)
2618 .ok_or(crate::DecodeError::MessageTooLarge)?;
2619 if prev_tail.len() >= combined
2620 && core::ptr::eq(prev_tail[prev_len..].as_ptr(), tail.as_ptr())
2621 {
2622 *last = &prev_tail[..combined];
2623 return Ok(());
2624 }
2625 }
2626 st.records
2627 .push(UnknownFieldsViewRecord::Borrowed(&tail[..span_len]));
2628 st.last_tail = Some(tail);
2629 Ok(())
2630 }
2631
2632 /// Preserve one unrecognized value of a closed enum as synthetic varint
2633 /// wire bytes.
2634 ///
2635 /// Marked `#[cold]`: the sole caller is the per-element route for a closed
2636 /// enum whose wire value names no variant — reached from a *recognized*
2637 /// field, including inside a packed element loop, so it can run more than
2638 /// once per message against a newer producer's data. It builds a `Vec` per
2639 /// value regardless, which dwarfs what the size-optimized body this
2640 /// attribute asks for costs.
2641 #[doc(hidden)]
2642 #[cold]
2643 pub fn push_varint(
2644 &mut self,
2645 field_number: u32,
2646 value: u64,
2647 ctx: crate::DecodeContext<'_>,
2648 ) -> Result<(), crate::DecodeError> {
2649 use crate::encoding::{encode_varint, Tag, WireType};
2650
2651 ctx.register_unknown_field()?;
2652 let st = self.state_mut();
2653 st.to_owned_budget = st.to_owned_budget.saturating_add(1);
2654
2655 let mut bytes = alloc::vec::Vec::new();
2656 Tag::new(field_number, WireType::Varint).encode(&mut bytes);
2657 encode_varint(value, &mut bytes);
2658 st.records.push(UnknownFieldsViewRecord::Owned(bytes));
2659 // Synthetic bytes have no position in the input buffer, so a later
2660 // borrowed record must start a fresh span.
2661 st.last_tail = None;
2662 Ok(())
2663 }
2664
2665 /// Returns `true` if no unknown fields were recorded.
2666 pub fn is_empty(&self) -> bool {
2667 self.records_slice().is_empty()
2668 }
2669
2670 /// Total byte length of all unknown field data.
2671 pub fn encoded_len(&self) -> usize {
2672 self.records_slice()
2673 .iter()
2674 .map(|record| record.as_slice().len())
2675 .sum()
2676 }
2677
2678 /// Write all unknown-field bytes in decode order. Each record holds one
2679 /// or more complete `(tag, value)` records, so concatenating them
2680 /// produces a valid encoding.
2681 pub fn write_to(&self, buf: &mut impl EncodeSink) {
2682 for record in self.records_slice() {
2683 buf.put_slice(record.as_slice());
2684 }
2685 }
2686
2687 /// Convert to an owned [`UnknownFields`](crate::UnknownFields) by parsing all stored wire records.
2688 ///
2689 /// Each record holds one or more consecutive (tag + value) records as
2690 /// they should be re-emitted. Parsing uses
2691 /// [`crate::encoding::decode_unknown_field`] under exactly the budget
2692 /// [`push_record`](Self::push_record) and [`push_varint`](Self::push_varint)
2693 /// charged at decode time — the same field count and group-nesting depth —
2694 /// so replay cannot exhaust either. Views holding manually pushed spans
2695 /// (via [`push_raw`](Self::push_raw)) additionally get
2696 /// [`DEFAULT_UNKNOWN_FIELD_LIMIT`](crate::DEFAULT_UNKNOWN_FIELD_LIMIT)
2697 /// slots and the full [`RECURSION_LIMIT`](crate::RECURSION_LIMIT), since
2698 /// those spans were never charged.
2699 /// A coalesced borrowed span re-materializes one owned `UnknownField` per
2700 /// wire record, so this conversion is where a long run of unknown fields
2701 /// actually allocates.
2702 ///
2703 /// # Errors
2704 ///
2705 /// Returns `Err` if a stored record is malformed or exceeds the replay
2706 /// budget. Neither can occur when the view was produced by wire decoding
2707 /// — every borrowed record was parsed off the wire, and the budget equals
2708 /// what decoding charged — so any such view converts successfully. Only
2709 /// views holding [`push_raw`](Self::push_raw) spans can fail here.
2710 pub fn to_owned(&self) -> Result<crate::UnknownFields, crate::DecodeError> {
2711 use crate::encoding::{decode_unknown_field, Tag};
2712
2713 let Some(state) = self.state.as_deref() else {
2714 return Ok(crate::UnknownFields::new());
2715 };
2716 let (budget, depth) = if state.manual_spans {
2717 (
2718 state
2719 .to_owned_budget
2720 .saturating_add(crate::DEFAULT_UNKNOWN_FIELD_LIMIT),
2721 state.to_owned_depth.max(crate::RECURSION_LIMIT),
2722 )
2723 } else {
2724 (state.to_owned_budget, state.to_owned_depth)
2725 };
2726 let limit = core::cell::Cell::new(budget);
2727 let ctx = crate::DecodeContext::new(depth, &limit);
2728 let mut out = crate::UnknownFields::new();
2729 for record in &state.records {
2730 let mut cur = record.as_slice();
2731 while !cur.is_empty() {
2732 let tag = Tag::decode(&mut cur)?;
2733 let field = decode_unknown_field(tag, &mut cur, ctx)?;
2734 out.push(field);
2735 }
2736 }
2737 Ok(out)
2738 }
2739}
2740
2741/// An owned, `'static` container for a decoded message view.
2742///
2743/// `OwnedView` holds a [`Bytes`] buffer alongside the decoded view, ensuring
2744/// the view's borrows remain valid for the container's lifetime. The inner
2745/// view is reached through [`reborrow()`](OwnedView::reborrow), which returns
2746/// it with a lifetime tied to `&self`.
2747///
2748/// This type is `Send + Sync + 'static`, making it suitable for use across
2749/// async boundaries, in tower services, and anywhere a `'static` bound is
2750/// required.
2751///
2752/// # When to use
2753///
2754/// Use `OwnedView` when you need a zero-copy view that outlives the scope
2755/// where the buffer was received — for example, in an RPC handler where the
2756/// framework requires `'static` types:
2757///
2758/// ```rust,ignore
2759/// use buffa::view::OwnedView;
2760/// use bytes::Bytes;
2761///
2762/// let bytes: Bytes = receive_request_body().await;
2763/// let view = OwnedView::<PersonView>::decode(bytes)?;
2764///
2765/// // Field access through reborrow — the borrow is tied to `view`.
2766/// let person = view.reborrow();
2767/// println!("name: {}", person.name);
2768/// println!("id: {}", person.id);
2769///
2770/// // Convert to owned if you need to store or mutate — infallible, since
2771/// // an OwnedView always holds a wire-decoded view.
2772/// let owned: Person = view.to_owned_message();
2773/// ```
2774///
2775/// Generated code additionally provides a per-message `FooOwnedView` wrapper
2776/// around `OwnedView<FooView<'static>>` with per-field accessor methods
2777/// (`owned.name()`, `owned.id()`, …), so most handler code never touches
2778/// `OwnedView` or `reborrow` directly.
2779///
2780/// For scoped access where the buffer's lifetime is known, use
2781/// [`MessageView::decode_view`] directly — it has zero overhead beyond the
2782/// decode itself.
2783///
2784/// # Why field access goes through `reborrow`
2785///
2786/// `OwnedView` stores `V = FooView<'static>`: the view's borrows really point
2787/// into `self`'s [`Bytes`] buffer, and the `'static` is a synthetic lifetime
2788/// established by the constructor. Exposing `&V` directly (for example via a
2789/// `Deref` impl) would let borrowed fields *appear* `'static` to the
2790/// compiler and escape the `OwnedView`'s scope, dangling once it drops.
2791/// [`reborrow()`](OwnedView::reborrow) narrows the synthetic `'static` down
2792/// to the `OwnedView`'s real lifetime, so the borrow checker enforces the
2793/// actual validity of every field borrow:
2794///
2795/// ```no_run
2796/// # use buffa::view::OwnedView;
2797/// # use buffa::__doctest_fixtures::PersonView;
2798/// // Inline reads: reborrow once, then use plain field access.
2799/// fn log(owned: &OwnedView<PersonView<'static>>) {
2800/// let person = owned.reborrow();
2801/// println!("{}", person.name);
2802/// }
2803///
2804/// // Returning a borrowed field: the result is tied to the OwnedView.
2805/// fn name<'a>(owned: &'a OwnedView<PersonView<'static>>) -> &'a str {
2806/// owned.reborrow().name // &'a str tied to the OwnedView's lifetime
2807/// }
2808/// ```
2809///
2810/// View fields are not reachable directly on the handle — this fails to
2811/// compile rather than handing out a `'static` borrow into the buffer:
2812///
2813/// ```compile_fail,E0609
2814/// # use buffa::view::OwnedView;
2815/// # use buffa::__doctest_fixtures::PersonView;
2816/// fn field(owned: &OwnedView<PersonView<'static>>) -> &'static str {
2817/// owned.name // error[E0609]: no field `name` on type `&OwnedView<...>`
2818/// }
2819/// ```
2820///
2821/// # Safety
2822///
2823/// Internally, `OwnedView` extends the view's lifetime to `'static` via
2824/// `transmute` in its constructors. This is sound because:
2825///
2826/// 1. [`Bytes`] is reference-counted — its heap data pointer is stable across
2827/// moves. The view's borrows always point into valid memory.
2828/// 2. [`Bytes`] is immutable — the underlying data cannot be modified while
2829/// borrowed.
2830/// 3. The view is declared before the buffer, and the compiler's drop glue
2831/// drops fields in declaration order, so the view is always gone before
2832/// the buffer it borrows from is released — on a normal drop and during
2833/// an unwind; [`into_bytes`](OwnedView::into_bytes) drops it explicitly
2834/// before handing the buffer back.
2835/// 4. The view is stored in a private `MaybeDangling` wrapper (an in-tree
2836/// stand-in for RFC 3336), which tells the aliasing model that its forged
2837/// `'static` borrows carry no validity guarantees of their own while an
2838/// `OwnedView` is moved around by value.
2839/// 5. Every constructor requires `V: `[`ViewLifetimeParametric`], the
2840/// `unsafe` marker asserting that no impl on `V` can let a borrow of the
2841/// forged-`'static` buffer outlive the view (its `# Safety` section is
2842/// the contract). `Debug`, `PartialEq`, `Serialize` and
2843/// [`to_owned_message`](OwnedView::to_owned_message) additionally go
2844/// through [`reborrow`](OwnedView::reborrow), so `V`'s own impls are
2845/// only ever invoked on a `V::Reborrowed<'b>` with the real lifetime.
2846///
2847/// [`reborrow`](OwnedView::reborrow) is a plain Rust subtype coercion (no
2848/// `unsafe`, no pointer cast): the [`ViewReborrow`] trait method coerces
2849/// `&'b FooView<'static>` into `&'b FooView<'b>` via standard lifetime
2850/// variance for covariant view types. See [`ViewReborrow`]'s docs for the
2851/// soundness argument.
2852pub struct OwnedView<V> {
2853 // INVARIANT: `view` borrows from `bytes`. FIELD ORDER IS LOAD-BEARING:
2854 // drop glue runs in declaration order, so `view` must stay declared
2855 // before `bytes` for the view to be dropped while its buffer is still
2856 // alive. There is deliberately no `Drop` impl on `OwnedView` — with one,
2857 // `into_bytes` could not move `bytes` out, and a panic in `V::drop`
2858 // could unwind into it and drop the view a second time (#377).
2859 //
2860 // CONSTRUCTORS: any constructor added here MUST ensure the view's
2861 // borrows point into `self.bytes` (not into caller-owned memory), and
2862 // MUST carry `where V: ViewLifetimeParametric` — every way to obtain an
2863 // `OwnedView<V>` from a buffer goes through that bound, so no
2864 // `OwnedView<V>` can exist for a `V` that has not asserted the contract.
2865 // (The bound sits on each constructor rather than on the impl block so
2866 // that a missing impl reports E0277 with the trait's `on_unimplemented`
2867 // notes, rather than E0599, which suppresses them.)
2868 // The auto-`Send`/`Sync` derivation is only sound under the first
2869 // invariant — there is no longer a `V: 'static` bound on `Send` to act
2870 // as a second gate. See the comment block above `send_sync_assertions`
2871 // below.
2872 view: MaybeDangling<V>,
2873 bytes: Bytes,
2874}
2875
2876/// An in-tree stand-in for the `MaybeDangling<T>` proposed in [RFC 3336],
2877/// modelled on `yoke`'s `KindaSortaDangling` (minus the `into_inner` and
2878/// `DerefMut` this crate has no caller for).
2879///
2880/// The view inside an [`OwnedView`] carries `&'static` borrows that really
2881/// point into the sibling `Bytes` buffer. Storing it behind a
2882/// [`MaybeUninit`](core::mem::MaybeUninit) tells the aliasing model that the
2883/// value has no memory-dependent validity properties (`dereferenceable`,
2884/// `noalias`) of its own. Without the wrapper, Miri's field retagging puts a
2885/// protector on each forged `&'static` whenever an `OwnedView` is passed by
2886/// value, and freeing the buffer inside that call — a plain `drop(owned)` in
2887/// the callee, or the unwind path of [`OwnedView::into_bytes`] — is reported
2888/// as undefined behaviour. [icu4x #3696] is the `yoke` test case for exactly
2889/// this.
2890///
2891/// Once RFC 3336 lands this can become the standard library type.
2892///
2893/// [RFC 3336]: https://github.com/rust-lang/rfcs/pull/3336
2894/// [icu4x #3696]: https://github.com/unicode-org/icu4x/issues/3696
2895#[repr(transparent)]
2896struct MaybeDangling<T> {
2897 /// INVARIANT: always holds an initialized `T`. Its drop glue runs from
2898 /// [`Drop::drop`] below rather than from `MaybeUninit` (which has none),
2899 /// so nothing may treat `inner` as initialized after that point — and
2900 /// nothing does, because the only code that runs afterwards is the
2901 /// empty drop glue of `MaybeUninit`.
2902 inner: core::mem::MaybeUninit<T>,
2903}
2904
2905impl<T> MaybeDangling<T> {
2906 #[inline]
2907 const fn new(value: T) -> Self {
2908 Self {
2909 inner: core::mem::MaybeUninit::new(value),
2910 }
2911 }
2912}
2913
2914impl<T> core::ops::Deref for MaybeDangling<T> {
2915 type Target = T;
2916 #[inline]
2917 fn deref(&self) -> &T {
2918 // SAFETY: `inner` is initialized (the type invariant); `deref` is
2919 // never reachable once `Drop::drop` has run.
2920 unsafe { self.inner.assume_init_ref() }
2921 }
2922}
2923
2924impl<T> Drop for MaybeDangling<T> {
2925 #[inline]
2926 fn drop(&mut self) {
2927 // SAFETY: `inner` is initialized (the type invariant) and is dropped
2928 // exactly once here — `MaybeUninit` has no drop glue, so nothing runs
2929 // it again afterwards. `drop_in_place` rather than
2930 // `assume_init_read` so the `T` is never moved into an unwrapped
2931 // local, which would reassert the validity properties this wrapper
2932 // exists to suppress.
2933 unsafe { self.inner.as_mut_ptr().drop_in_place() }
2934 }
2935}
2936
2937/// Panic path for [`OwnedView::to_owned_message`], hoisted out of the
2938/// generic method so the format machinery is emitted once rather than per
2939/// monomorphization — the branch is unreachable for generated view types.
2940#[cold]
2941#[inline(never)]
2942fn convert_contract_violated(e: DecodeError) -> ! {
2943 panic!(
2944 "OwnedView conversion failed ({e:?}): the wrapped MessageView \
2945 impl violates the wire-decode => convert contract"
2946 )
2947}
2948
2949// Every constructor carries `where V: ViewLifetimeParametric` individually
2950// rather than on this impl block: a bound on the block makes a missing impl
2951// surface as E0599 ("function exists but its trait bounds were not
2952// satisfied"), which suppresses the trait's `on_unimplemented` notes; a
2953// per-fn where-clause reports E0277 with them. Any constructor added here
2954// MUST carry the same clause.
2955impl<V> OwnedView<V>
2956where
2957 V: MessageView<'static>,
2958{
2959 /// Decode a view from a [`Bytes`] buffer.
2960 ///
2961 /// The view borrows directly from the buffer's data. Because [`Bytes`] is
2962 /// reference-counted and its data pointer is stable across moves, the
2963 /// view's borrows remain valid for the lifetime of this `OwnedView`.
2964 /// This method does not enforce an input-size cap; use
2965 /// [`decode_with_options`](Self::decode_with_options) when one is required.
2966 ///
2967 /// # Errors
2968 ///
2969 /// Returns [`DecodeError`] if the buffer contains invalid protobuf data or
2970 /// exceeds a default recursion, unknown-field, or element-memory limit.
2971 pub fn decode(bytes: Bytes) -> Result<Self, DecodeError>
2972 where
2973 V: ViewLifetimeParametric,
2974 {
2975 // SAFETY: `Bytes` is StableDeref — its heap data never moves or is
2976 // freed while we hold the `Bytes` value. We hold it in `self.bytes`,
2977 // and declaration-order drop glue (`OwnedView` has no `Drop` impl)
2978 // guarantees `view` drops first. The forged `'static` is only ever
2979 // observed by `V`, whose `ViewLifetimeParametric` impl asserts that
2980 // no borrow of `slice` escapes the returned view.
2981 let view = unsafe {
2982 let slice: &'static [u8] = core::mem::transmute::<&[u8], &'static [u8]>(&bytes);
2983 V::decode_view(slice)?
2984 };
2985 Ok(Self {
2986 view: MaybeDangling::new(view),
2987 bytes,
2988 })
2989 }
2990
2991 /// Decode a view with custom [`DecodeOptions`](crate::DecodeOptions)
2992 /// (recursion limit, max message size, unknown-field limit, and
2993 /// element-memory limit).
2994 ///
2995 /// # Errors
2996 ///
2997 /// Returns [`DecodeError`] if the buffer is invalid or exceeds the
2998 /// configured limits.
2999 pub fn decode_with_options(
3000 bytes: Bytes,
3001 opts: &crate::DecodeOptions,
3002 ) -> Result<Self, DecodeError>
3003 where
3004 V: ViewLifetimeParametric,
3005 {
3006 // SAFETY: Same invariants as `decode` — see above.
3007 let view = unsafe {
3008 let slice: &'static [u8] = core::mem::transmute::<&[u8], &'static [u8]>(&bytes);
3009 opts.decode_view::<V>(slice)?
3010 };
3011 Ok(Self {
3012 view: MaybeDangling::new(view),
3013 bytes,
3014 })
3015 }
3016
3017 /// Create an `OwnedView` from an owned message by encoding then decoding.
3018 ///
3019 /// This performs a full **encode → decode** round-trip: the message is
3020 /// serialized to protobuf bytes, then a zero-copy view is decoded from
3021 /// those bytes. This is useful when the original wire bytes are not
3022 /// available (e.g., after JSON deserialization or programmatic construction),
3023 /// but note the cost: one allocation + O(n) encode + O(n) decode.
3024 ///
3025 /// For the common case where you already have wire bytes, prefer
3026 /// [`decode`](Self::decode) instead.
3027 ///
3028 /// # Errors
3029 ///
3030 /// Returns [`DecodeError::MessageTooLarge`] if the message's encoded
3031 /// size exceeds the 2 GiB protobuf limit
3032 /// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)), or another
3033 /// [`DecodeError`] if the re-encoded bytes are somehow invalid (should
3034 /// not happen for well-formed messages).
3035 pub fn from_owned(msg: &V::Owned) -> Result<Self, DecodeError>
3036 where
3037 V: ViewLifetimeParametric,
3038 {
3039 let bytes = Bytes::from(
3040 msg.try_encode_to_vec()
3041 .map_err(|_| DecodeError::MessageTooLarge)?,
3042 );
3043 Self::decode(bytes)
3044 }
3045
3046 /// Create an `OwnedView` from a buffer and a pre-decoded view.
3047 ///
3048 /// This avoids re-decoding when you already hold a decoded view and want
3049 /// to wrap it for `'static` use.
3050 ///
3051 /// # Safety
3052 ///
3053 /// The caller must ensure that `view` was produced by **wire-decoding**
3054 /// `bytes` (or a sub-slice that `bytes` fully contains) — e.g. via
3055 /// [`MessageView::decode_view`]. This guarantees both that all borrows
3056 /// in `view` point into the data region of `bytes` (violating that
3057 /// causes undefined behavior — dangling references) and that
3058 /// [`to_owned_message`](Self::to_owned_message)'s infallible-conversion
3059 /// contract holds (a manually assembled view merely borrowing from
3060 /// `bytes` satisfies the borrow requirement but can make conversion
3061 /// panic).
3062 pub unsafe fn from_parts(bytes: Bytes, view: V) -> Self
3063 where
3064 V: ViewLifetimeParametric,
3065 {
3066 Self {
3067 view: MaybeDangling::new(view),
3068 bytes,
3069 }
3070 }
3071}
3072
3073impl<V> OwnedView<V> {
3074 /// Get a reference to the underlying bytes buffer.
3075 pub fn bytes(&self) -> &Bytes {
3076 &self.bytes
3077 }
3078
3079 /// Consume the `OwnedView`, returning the underlying [`Bytes`] buffer.
3080 ///
3081 /// The view is dropped before the buffer is returned.
3082 ///
3083 /// # Panics
3084 ///
3085 /// Propagates a panic from `V`'s destructor; the buffer is then released
3086 /// by the unwind instead of being returned.
3087 pub fn into_bytes(self) -> Bytes {
3088 // Destructuring is only legal because `OwnedView` has no `Drop` impl
3089 // of its own. Moving the `Bytes` handle out first is fine: the heap
3090 // data the view borrows stays put (`Bytes` is `StableDeref`), and
3091 // the local keeps it alive. Dropping the view explicitly before
3092 // `bytes` moves into the return slot keeps the buffer a plain local
3093 // while `V::drop` runs: if that panics, the unwind frees `bytes` (a
3094 // value already in the return slot would be leaked instead), and
3095 // `view` has been moved into `drop`, so nothing can drop it twice.
3096 let Self { view, bytes } = self;
3097 drop(view);
3098 bytes
3099 }
3100}
3101
3102// The accessors that reach `V` need only `ViewReborrow` — a supertrait of
3103// `ViewLifetimeParametric`, so every constructible `OwnedView<V>` has it, and
3104// generic code holding a handle can call them under that one bound.
3105impl<V> OwnedView<V>
3106where
3107 V: ViewReborrow,
3108{
3109 /// Convert the view to the corresponding owned message type.
3110 ///
3111 /// `bytes::Bytes`-typed fields are produced via [`Bytes::slice_ref`]
3112 /// into the retained buffer (zero-copy); other borrowed fields are
3113 /// allocated and copied.
3114 ///
3115 /// Infallible: every `OwnedView` constructor wire-decodes its view
3116 /// ([`decode`](Self::decode), [`decode_with_options`](Self::decode_with_options),
3117 /// [`from_owned`](Self::from_owned)) or requires wire-decode provenance
3118 /// as part of its safety contract ([`from_parts`](Self::from_parts)),
3119 /// and a view produced by wire decoding always converts (see
3120 /// [`MessageView::to_owned_message`]).
3121 ///
3122 /// # Panics
3123 ///
3124 /// Panics if `V`'s [`MessageView`] implementation violates the
3125 /// wire-decode ⇒ convert contract. Generated view types cannot trigger
3126 /// this; only a buggy hand-written impl (or a
3127 /// [`from_parts`](Self::from_parts) view that breaches its safety
3128 /// contract) can.
3129 #[must_use]
3130 pub fn to_owned_message(&self) -> V::Owned {
3131 V::reborrow(&self.view)
3132 .to_owned_from_source(Some(&self.bytes))
3133 .unwrap_or_else(|e| convert_contract_violated(e))
3134 }
3135
3136 /// Reborrow the view with a lifetime tied to `&'b self`.
3137 ///
3138 /// `OwnedView<V>` stores `V` with a `'static` lifetime — the actual borrows
3139 /// point into `self`'s internal [`Bytes`] buffer and are only valid while
3140 /// `self` is alive. `reborrow` makes that real lifetime visible to the borrow
3141 /// checker: the returned `&'b V::Reborrowed<'b>` cannot outlive `&'b self`.
3142 ///
3143 /// # Example
3144 ///
3145 /// ```no_run
3146 /// # use buffa::view::OwnedView;
3147 /// # use buffa::__doctest_fixtures::PersonView;
3148 /// fn handler<'a>(req: &'a OwnedView<PersonView<'static>>) -> &'a str {
3149 /// // The explicit annotation is for emphasis; inference works without it.
3150 /// // If you need to name the lifetime, store the reborrow in a `let` first.
3151 /// let req_view: &PersonView<'a> = req.reborrow();
3152 /// req_view.name // zero-copy from the OwnedView's buffer
3153 /// }
3154 /// ```
3155 ///
3156 /// The returned reference is tied to `&'b self` — the borrow checker
3157 /// prevents the reborrowed view from outliving the `OwnedView`:
3158 ///
3159 /// ```compile_fail,E0597
3160 /// # use buffa::view::OwnedView;
3161 /// # use buffa::__doctest_fixtures::PersonView;
3162 /// let name: &str;
3163 /// {
3164 /// // SAFETY: empty Bytes, no borrows — safe to construct directly.
3165 /// let owned = unsafe {
3166 /// OwnedView::<PersonView<'static>>::from_parts(
3167 /// ::buffa::bytes::Bytes::new(),
3168 /// PersonView::default(),
3169 /// )
3170 /// };
3171 /// name = owned.reborrow().name; // error[E0597]: `owned` does not live long enough
3172 /// }
3173 /// println!("{name}"); // name is dangling — borrow checker rejects this
3174 /// ```
3175 ///
3176 /// # How it works
3177 ///
3178 /// The trait method [`ViewReborrow::reborrow`] is a plain Rust subtype
3179 /// coercion: `&'b V` (where `V = FooView<'static>`) flows into the
3180 /// return slot `&'b V::Reborrowed<'b>` (= `&'b FooView<'b>`). Variance
3181 /// makes this safe — covariant view types narrow `'static` down to
3182 /// `'b` automatically. No `unsafe`, no pointer cast, no layout
3183 /// assertions. `OwnedView`'s own invariant (every borrow in `view`
3184 /// points into `self.bytes`, established by `decode` or upheld by the
3185 /// `unsafe from_parts` caller) guarantees the pointed-to data lives
3186 /// at least as long as `'b`.
3187 #[must_use = "reborrow returns a tied-lifetime view; discarding it is a no-op"]
3188 pub fn reborrow<'b>(&'b self) -> &'b V::Reborrowed<'b> {
3189 V::reborrow(&self.view)
3190 }
3191}
3192
3193// Deliberately NO `Deref<Target = V>` impl: `V` is `FooView<'static>`, so a
3194// `&V` return would expose the synthetic `'static` on every borrowed field
3195// and let it escape the OwnedView's scope (dangling once the buffer drops).
3196// All access goes through `reborrow()`, which ties the borrow to `&self`.
3197
3198// `Debug`, `PartialEq`, `Eq` and `Serialize` delegate through
3199// `ViewReborrow::reborrow` rather than to `V`'s own impl: the `'static`-typed
3200// `V` reaches no impl other than `ViewReborrow::reborrow` (whose canonical
3201// body returns `this` and retains nothing), and the
3202// bounds on `V::Reborrowed<'b>` mechanically require those impls to be
3203// parametric in it (`impl<'a> Debug for FooView<'a>`), which is the shape
3204// codegen emits. This is defence in depth behind the `ViewLifetimeParametric`
3205// contract on `V`. `Clone` and `Drop` are the exceptions — `Clone` must
3206// produce another `V`, and `Drop` runs on the stored value — so they invoke
3207// `V`'s own impls on the `'static`-typed value and rely on the contract
3208// alone (`Drop` structurally so: Rust forbids a lifetime-specialised `Drop`
3209// impl, so `V`'s destructor is parametric whether or not `V` is marked).
3210// `Clone` carries the marker bound anyway, so that it cannot mint an
3211// `OwnedView<V>` for an unmarked `V` even in principle. `Debug` needs no
3212// `for<'b>` clause because the `Reborrowed` GAT carries the bound.
3213impl<V> core::fmt::Debug for OwnedView<V>
3214where
3215 V: ViewReborrow,
3216{
3217 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3218 V::reborrow(&self.view).fmt(f)
3219 }
3220}
3221
3222impl<V> Clone for OwnedView<V>
3223where
3224 V: Clone + ViewLifetimeParametric,
3225{
3226 fn clone(&self) -> Self {
3227 // SAFETY: `Bytes::clone()` is a refcount bump — both the original and
3228 // the clone share the same backing heap allocation. The cloned view's
3229 // `'static` references remain valid because they point into data that
3230 // is now kept alive by the cloned `Bytes` handle. This would be
3231 // unsound if `Bytes::clone()` performed a deep copy to a new address.
3232 Self {
3233 view: MaybeDangling::new((*self.view).clone()),
3234 bytes: self.bytes.clone(),
3235 }
3236 }
3237}
3238
3239impl<V> PartialEq for OwnedView<V>
3240where
3241 V: ViewReborrow,
3242 for<'b> V::Reborrowed<'b>: PartialEq,
3243{
3244 fn eq(&self, other: &Self) -> bool {
3245 V::reborrow(&self.view) == V::reborrow(&other.view)
3246 }
3247}
3248
3249impl<V> Eq for OwnedView<V>
3250where
3251 V: ViewReborrow,
3252 for<'b> V::Reborrowed<'b>: Eq,
3253{
3254}
3255
3256/// Serialize an `OwnedView<V>` by delegating to the inner view's `Serialize`
3257/// impl.
3258///
3259/// Equivalent to serializing `owned_view.reborrow()` directly, so
3260/// `serde_json::to_string(&owned_view)` works on the handle itself. When
3261/// `V` is a buffa-generated view with `generate_json` enabled, this produces
3262/// protobuf JSON; the impl itself just forwards to whatever `V::serialize`
3263/// does.
3264///
3265/// Only available when the `json` feature is enabled.
3266#[cfg(feature = "json")]
3267impl<V> ::serde::Serialize for OwnedView<V>
3268where
3269 V: ViewReborrow,
3270 for<'b> V::Reborrowed<'b>: ::serde::Serialize,
3271{
3272 fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
3273 ::serde::Serialize::serialize(V::reborrow(&self.view), s)
3274 }
3275}
3276
3277// `OwnedView<V>` is auto-`Send`/`Sync` when `V` is — `MaybeDangling<V>` (a
3278// `MaybeUninit<V>`) and `Bytes` both forward auto-traits. No manual
3279// `unsafe impl` is needed, and adding one with a `V: 'static` bound is
3280// actively harmful: it is precisely what triggers E0477 when `async fn` is
3281// used in a trait impl against an RPITIT `+ Send` return type
3282// (rust-lang/rust#128095). The RPITIT desugaring introduces a fresh lifetime
3283// for the `'static` in `FooView<'static>`, and then cannot prove that fresh
3284// lifetime satisfies `'static` to discharge the manual impl's bound.
3285//
3286// The bound was defensive — intended to prevent `OwnedView<FooView<'short>>`
3287// from being `Send` when the view borrows from something outside `self.bytes`.
3288// But that type is already unconstructible: every constructor is gated on
3289// `V: MessageView<'static> + ViewLifetimeParametric`, and the fields are private.
3290// The short-lifetime case the bound guards against cannot exist in safe
3291// code.
3292//
3293// Auto-trait soundness: `Bytes` is `Send + Sync`. The view's `&'static [u8]`
3294// borrows point into `Bytes`'s heap allocation, which is immutable,
3295// `StableDeref`, and moves with the struct. Sending the whole pair to another
3296// thread preserves the invariant. The `'static` in `V` being a lie is about
3297// *where* the reference points, not about thread safety.
3298#[cfg(test)]
3299mod send_sync_assertions {
3300 use super::*;
3301 fn assert_send<T: Send>() {}
3302 fn assert_sync<T: Sync>() {}
3303
3304 // Any `V: Send + Sync` suffices — generated `FooView<'static>` types are
3305 // auto-`Send + Sync` via their `&'static str` / `&'static [u8]` fields.
3306 #[allow(dead_code)]
3307 fn owned_view_is_send_sync<V: Send + Sync>() {
3308 assert_send::<OwnedView<V>>();
3309 assert_sync::<OwnedView<V>>();
3310 }
3311
3312 // `OwnedView<FooView<'static>>` must keep coercing to
3313 // `OwnedView<FooView<'a>>`: `MaybeUninit<V>` is covariant in `V` like the
3314 // `ManuallyDrop<V>` it replaced, but that is a derived property of the
3315 // union, not a documented guarantee, so pin it here.
3316 #[allow(dead_code)]
3317 fn owned_view_is_covariant<'a>(
3318 v: OwnedView<super::tests::TinyView<'static>>,
3319 ) -> OwnedView<super::tests::TinyView<'a>> {
3320 v
3321 }
3322
3323 // Concrete-type regression: `TinyView` is declared in the `tests` module
3324 // below and has the same shape as generated view types (one `&'a str`).
3325 #[allow(dead_code)]
3326 fn owned_tiny_view_is_send_sync() {
3327 assert_send::<OwnedView<super::tests::TinyView<'static>>>();
3328 assert_sync::<OwnedView<super::tests::TinyView<'static>>>();
3329 }
3330
3331 // `ViewReborrow::Reborrowed<'b>` must also be Send + Sync so that a
3332 // reborrowed view can be passed across threads (e.g. into a Tokio task).
3333 #[allow(dead_code)]
3334 fn reborrowed_view_is_send_sync<V>()
3335 where
3336 V: ViewReborrow + Send + Sync,
3337 for<'b> V::Reborrowed<'b>: Send + Sync,
3338 {
3339 assert_send::<OwnedView<V>>();
3340 assert_sync::<OwnedView<V>>();
3341 }
3342}
3343
3344#[cfg(test)]
3345mod tests {
3346 #[test]
3347 fn unknown_map_records_use_one_storage_slot_and_replay_owned_unknowns() {
3348 let wire = &[0x1a, 4, 0x10, 99, 0x10, 98][..];
3349 let mut fields = UnknownFieldsView::new();
3350 let allowance = core::cell::Cell::new(1);
3351 fields
3352 .push_record(wire, wire.len(), crate::DecodeContext::new(8, &allowance))
3353 .unwrap();
3354 assert_eq!(allowance.get(), 0);
3355 let owned = fields.to_owned().unwrap();
3356 assert_eq!(owned.iter().count(), 1);
3357 assert_eq!(owned.iter().next().unwrap().number, 3);
3358 for (wire, length) in [
3359 (&[0x80][..], 1),
3360 (&[0x1a, 2, 0x10][..], 3),
3361 (&[0x1a, 0][..], 3),
3362 ] {
3363 let allowance = core::cell::Cell::new(8);
3364 assert!(UnknownFieldsView::new()
3365 .push_record(wire, length, crate::DecodeContext::new(8, &allowance))
3366 .is_err());
3367 }
3368 }
3369
3370 use super::*;
3371
3372 // ── MessageFieldView ─────────────────────────────────────────────────
3373
3374 #[test]
3375 fn message_field_view_default_is_unset() {
3376 let v: MessageFieldView<i32> = MessageFieldView::default();
3377 assert!(v.is_unset());
3378 assert!(!v.is_set());
3379 assert_eq!(v.as_option(), None);
3380 }
3381
3382 #[test]
3383 fn message_field_view_set_value() {
3384 let v = MessageFieldView::set(42);
3385 assert!(v.is_set());
3386 assert!(!v.is_unset());
3387 assert_eq!(v.as_option(), Some(&42));
3388 }
3389
3390 #[test]
3391 fn message_field_view_with_non_copy_type() {
3392 let v = MessageFieldView::set(alloc::string::String::from("hello"));
3393 assert!(v.is_set());
3394 assert_eq!(v.as_option().map(|s| s.as_str()), Some("hello"));
3395
3396 let unset: MessageFieldView<alloc::string::String> = MessageFieldView::unset();
3397 assert!(unset.is_unset());
3398 assert_eq!(unset.as_option(), None);
3399 }
3400
3401 // ── MessageFieldView Deref ─────────────────────────────────────────
3402
3403 /// A trivial view type for testing MessageFieldView Deref.
3404 #[derive(Clone, Debug, Default, PartialEq)]
3405 pub(super) struct TinyView<'a> {
3406 pub value: &'a str,
3407 }
3408
3409 // Via the exported macro, which doubles as its unit test (hygiene and
3410 // `$crate` path resolution).
3411 crate::impl_default_view_instance!(TinyView);
3412
3413 #[test]
3414 fn impl_default_view_instance_macro_returns_singleton() {
3415 let a: &TinyView<'_> = TinyView::default_view_instance();
3416 let b: &TinyView<'_> = TinyView::default_view_instance();
3417 assert!(core::ptr::eq(a, b), "singleton must be a single allocation");
3418 assert_eq!(a, &TinyView::default());
3419 }
3420
3421 #[test]
3422 fn message_field_view_deref_set() {
3423 let v = MessageFieldView::set(TinyView { value: "hello" });
3424 // Deref gives access to the inner view
3425 assert_eq!(v.value, "hello");
3426 }
3427
3428 #[test]
3429 fn message_field_view_deref_unset_returns_default() {
3430 let v: MessageFieldView<TinyView<'_>> = MessageFieldView::unset();
3431 // Deref transparently returns the default instance
3432 assert_eq!(v.value, "");
3433 }
3434
3435 #[test]
3436 fn message_field_view_deref_chained_access() {
3437 // Simulates accessing a nested field through an unset sub-message
3438 let v: MessageFieldView<TinyView<'_>> = MessageFieldView::unset();
3439 let len = v.value.len();
3440 assert_eq!(len, 0);
3441 }
3442
3443 // ── MessageFieldView PartialEq (presence-aware) ────────────────────
3444
3445 #[test]
3446 fn message_field_view_equality() {
3447 // None = Unset, Some(s) = Set(TinyView { value: s }).
3448 // TinyView::default() has value == "", so Some("") encodes Set(default).
3449 fn mk(c: Option<&str>) -> MessageFieldView<TinyView<'_>> {
3450 match c {
3451 None => MessageFieldView::unset(),
3452 Some(v) => MessageFieldView::set(TinyView { value: v }),
3453 }
3454 }
3455
3456 #[rustfmt::skip]
3457 let cases: &[(Option<&str>, Option<&str>, bool)] = &[
3458 // Presence is part of the value, matching MessageField::PartialEq
3459 // on the owned side: Set(default) is on the wire, Unset is not.
3460 (None, None, true ), // Unset == Unset
3461 (None, Some(""), false), // Unset != Set(default)
3462 (Some(""), None, false), // Set(default) != Unset (symmetric)
3463 (Some(""), Some(""), true ), // Set(default) == Set(default)
3464 (None, Some("x"), false), // Unset != Set(nondefault)
3465 (Some("x"), None, false), // Set(nondefault) != Unset (symmetric)
3466 (Some("x"), Some("x"), true ), // Set == Set (same)
3467 (Some("x"), Some("y"), false), // Set != Set (different)
3468 ];
3469
3470 for &(l, r, expect) in cases {
3471 assert_eq!(
3472 mk(l) == mk(r),
3473 expect,
3474 "({l:?} == {r:?}) should be {expect}"
3475 );
3476 }
3477
3478 // `==` needs no `DefaultViewInstance`.
3479 assert!(MessageFieldView::set(1i32) == MessageFieldView::set(1));
3480 assert!(MessageFieldView::set(1i32) != MessageFieldView::unset());
3481 }
3482
3483 #[test]
3484 fn message_field_view_hash_agrees_with_equality() {
3485 fn hash_of<H: core::hash::Hash>(value: &H) -> u64 {
3486 use core::hash::Hasher;
3487 let mut hasher = std::collections::hash_map::DefaultHasher::new();
3488 value.hash(&mut hasher);
3489 hasher.finish()
3490 }
3491 let unset: MessageFieldView<i32> = MessageFieldView::unset();
3492 assert_eq!(hash_of(&unset), hash_of(&None::<&i32>));
3493 assert_eq!(hash_of(&MessageFieldView::set(7i32)), hash_of(&Some(&7i32)));
3494 assert_ne!(hash_of(&unset), hash_of(&MessageFieldView::set(0i32)));
3495 }
3496
3497 // ── RepeatedView ─────────────────────────────────────────────────────
3498
3499 #[test]
3500 fn repeated_view_new_and_accessors() {
3501 let rv = RepeatedView::new(alloc::vec![10, 20, 30]);
3502 assert_eq!(rv.len(), 3);
3503 assert!(!rv.is_empty());
3504 assert_eq!(&*rv, &[10, 20, 30]);
3505 }
3506
3507 #[test]
3508 fn repeated_view_default_is_empty() {
3509 let rv: RepeatedView<'_, u8> = RepeatedView::default();
3510 assert!(rv.is_empty());
3511 assert_eq!(rv.len(), 0);
3512 }
3513
3514 #[test]
3515 fn repeated_view_push_and_iter() {
3516 let mut rv = RepeatedView::<i32>::default();
3517 rv.push(1);
3518 rv.push(2);
3519 let collected: alloc::vec::Vec<_> = rv.iter().copied().collect();
3520 assert_eq!(collected, alloc::vec![1, 2]);
3521 }
3522
3523 // ── UnknownFieldsView::push_record (coalescing + limit) ────────────
3524
3525 /// A test context at full depth with `n` unknown-field slots, leaking
3526 /// the cell so the context can outlive this helper.
3527 fn record_ctx(n: usize) -> crate::DecodeContext<'static> {
3528 let limit = alloc::boxed::Box::leak(alloc::boxed::Box::new(core::cell::Cell::new(n)));
3529 crate::DecodeContext::new(crate::RECURSION_LIMIT, limit)
3530 }
3531
3532 #[test]
3533 fn push_record_coalesces_adjacent_records() {
3534 // Buffer holds three consecutive 2-byte records: they coalesce into
3535 // a single span, but each still consumes one allowance slot.
3536 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01, 0x08, 0x02];
3537 let ctx = record_ctx(3);
3538 let mut ufv = UnknownFieldsView::new();
3539 ufv.push_record(&buf[0..], 2, ctx).unwrap();
3540 ufv.push_record(&buf[2..], 2, ctx).unwrap();
3541 ufv.push_record(&buf[4..], 2, ctx).unwrap();
3542 assert_eq!(ufv.encoded_len(), 6);
3543 assert_eq!(ufv.records_slice().len(), 1, "coalesced into one span");
3544 let mut out = alloc::vec::Vec::new();
3545 ufv.write_to(&mut out);
3546 assert_eq!(out, buf);
3547 assert_eq!(ctx.remaining_unknown_fields(), 0, "one slot per record");
3548 }
3549
3550 #[test]
3551 fn push_record_non_adjacent_records_use_separate_slots() {
3552 let buf: &[u8] = &[0x08, 0x00, 0xFF, 0x08, 0x01];
3553 let ctx = record_ctx(2);
3554 let mut ufv = UnknownFieldsView::new();
3555 ufv.push_record(&buf[0..], 2, ctx).unwrap();
3556 // Skip buf[2] — the next record is not adjacent to the previous one.
3557 ufv.push_record(&buf[3..], 2, ctx).unwrap();
3558 assert_eq!(ufv.encoded_len(), 4);
3559 assert_eq!(ctx.remaining_unknown_fields(), 0, "two slots consumed");
3560 }
3561
3562 #[test]
3563 fn push_record_enforces_limit_per_record() {
3564 // Before the per-record accounting fix, a coalesced run consumed
3565 // one slot at decode and one slot per record at conversion, so an
3566 // over-limit contiguous run decoded as a view and then failed to
3567 // convert. Now it fails at push time.
3568 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01, 0x08, 0x02];
3569 let ctx = record_ctx(1);
3570 let mut ufv = UnknownFieldsView::new();
3571 ufv.push_record(&buf[0..], 2, ctx).unwrap();
3572 // Non-adjacent record (the one at buf[2..4] was skipped): new span.
3573 assert_eq!(
3574 ufv.push_record(&buf[4..], 2, ctx),
3575 Err(crate::DecodeError::UnknownFieldLimitExceeded)
3576 );
3577 // Coalescing saves a span slot, not allowance: at zero remaining
3578 // even an adjacent record is rejected, keeping the decode-time
3579 // count equal to the count to_owned re-materializes.
3580 assert_eq!(
3581 ufv.push_record(&buf[2..], 2, ctx),
3582 Err(crate::DecodeError::UnknownFieldLimitExceeded)
3583 );
3584 }
3585
3586 #[test]
3587 fn push_record_charges_group_records_per_nested_field() {
3588 // One group record (field 1) holding two nested varint fields:
3589 // to_owned materializes three UnknownFields (group + 2 nested), so
3590 // decode must charge three slots.
3591 let buf: &[u8] = &[0x0b, 0x08, 0x00, 0x08, 0x01, 0x0c];
3592 let ctx = record_ctx(2);
3593 let mut ufv = UnknownFieldsView::new();
3594 assert_eq!(
3595 ufv.push_record(buf, buf.len(), ctx),
3596 Err(crate::DecodeError::UnknownFieldLimitExceeded)
3597 );
3598
3599 let ctx = record_ctx(3);
3600 let mut ufv = UnknownFieldsView::new();
3601 ufv.push_record(buf, buf.len(), ctx).unwrap();
3602 assert_eq!(ctx.remaining_unknown_fields(), 0, "group + 2 nested");
3603 let owned = ufv.to_owned().expect("decode allowance covers replay");
3604 assert_eq!(owned.iter().count(), 1, "one top-level group field");
3605 }
3606
3607 #[test]
3608 fn push_record_charges_nested_groups_recursively() {
3609 // group 1 { varint; group 2 { varint } } — four materializable
3610 // fields, so four slots.
3611 let buf: &[u8] = &[0x0b, 0x08, 0x00, 0x13, 0x08, 0x01, 0x14, 0x0c];
3612 let ctx = record_ctx(3);
3613 let mut ufv = UnknownFieldsView::new();
3614 assert_eq!(
3615 ufv.push_record(buf, buf.len(), ctx),
3616 Err(crate::DecodeError::UnknownFieldLimitExceeded)
3617 );
3618
3619 let ctx = record_ctx(4);
3620 let mut ufv = UnknownFieldsView::new();
3621 ufv.push_record(buf, buf.len(), ctx).unwrap();
3622 assert_eq!(ctx.remaining_unknown_fields(), 0);
3623 ufv.to_owned().expect("decode allowance covers replay");
3624 }
3625
3626 #[test]
3627 fn push_raw_disables_coalescing_for_next_record() {
3628 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01];
3629 let ctx = record_ctx(2);
3630 let mut ufv = UnknownFieldsView::new();
3631 ufv.push_raw(&buf[0..2]);
3632 // Adjacent on the wire, but push_raw cleared the tail, so this must
3633 // open a fresh span (a manual span has no trusted buffer position).
3634 ufv.push_record(&buf[2..], 2, ctx).unwrap();
3635 assert_eq!(ctx.remaining_unknown_fields(), 1);
3636 assert_eq!(ufv.encoded_len(), 4);
3637 }
3638
3639 #[test]
3640 fn push_record_rejects_span_past_tail_end() {
3641 let buf: &[u8] = &[0x08, 0x00];
3642 let ctx = record_ctx(1);
3643 let mut ufv = UnknownFieldsView::new();
3644 assert_eq!(
3645 ufv.push_record(buf, 3, ctx),
3646 Err(crate::DecodeError::UnexpectedEof)
3647 );
3648 }
3649
3650 #[test]
3651 fn coalesced_span_to_owned_parses_every_record() {
3652 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01, 0x08, 0x02];
3653 let ctx = record_ctx(3);
3654 let mut ufv = UnknownFieldsView::new();
3655 for i in 0..3 {
3656 ufv.push_record(&buf[2 * i..], 2, ctx).unwrap();
3657 }
3658 let owned = ufv.to_owned().unwrap();
3659 assert_eq!(owned.iter().count(), 3, "all records parsed");
3660 }
3661
3662 #[test]
3663 fn decode_time_allowance_always_covers_to_owned() {
3664 // The invariant push_record's accounting exists for: any run that
3665 // decodes within the allowance converts within the captured
3666 // allowance. Here the record count exactly exhausts the limit and
3667 // the run coalesces into one span.
3668 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01, 0x08, 0x02];
3669 let ctx = record_ctx(3);
3670 let mut ufv = UnknownFieldsView::new();
3671 for i in 0..3 {
3672 ufv.push_record(&buf[2 * i..], 2, ctx).unwrap();
3673 }
3674 assert_eq!(ufv.records_slice().len(), 1, "coalesced into one span");
3675 assert_eq!(ctx.remaining_unknown_fields(), 0, "limit exactly used");
3676 let owned = ufv.to_owned().expect("decode succeeded, so convert must");
3677 assert_eq!(owned.iter().count(), 3);
3678 }
3679
3680 #[test]
3681 fn to_owned_of_manual_view_uses_default_allowance() {
3682 // push_raw spans are never charged at decode time; to_owned grants
3683 // the default limit for them.
3684 let mut ufv = UnknownFieldsView::new();
3685 ufv.push_raw(&[0x08, 0x00]);
3686 let owned = ufv.to_owned().unwrap();
3687 assert_eq!(owned.iter().count(), 1);
3688 }
3689
3690 #[test]
3691 fn to_owned_covers_records_pushed_under_different_contexts() {
3692 // The replay budget is the accumulated charge total, not a snapshot
3693 // of any single context's remaining allowance — so a view merged
3694 // across decode passes with unrelated contexts still converts.
3695 let buf: &[u8] = &[0x08, 0x00, 0x08, 0x01, 0x08, 0x02];
3696 let mut ufv = UnknownFieldsView::new();
3697 let tight = record_ctx(1);
3698 ufv.push_record(&buf[0..], 2, tight).unwrap();
3699 let fresh = record_ctx(2);
3700 ufv.push_record(&buf[2..], 2, fresh).unwrap();
3701 ufv.push_record(&buf[4..], 2, fresh).unwrap();
3702 let owned = ufv.to_owned().expect("every push succeeded");
3703 assert_eq!(owned.iter().count(), 3);
3704 }
3705
3706 #[test]
3707 fn to_owned_replays_deep_groups_decoded_under_raised_recursion_limit() {
3708 // Replay depth comes from the nesting tracked at decode time, not
3709 // the fixed RECURSION_LIMIT — a group nested deeper than the
3710 // default (decodable only under a raised recursion limit) must
3711 // still convert.
3712 let deep = crate::RECURSION_LIMIT as usize + 20;
3713 let mut buf = alloc::vec![0x0bu8; deep]; // StartGroup ×deep
3714 buf.resize(2 * deep, 0x0c); // EndGroup ×deep
3715 let ctx = record_ctx(deep);
3716 let mut ufv = UnknownFieldsView::new();
3717 ufv.push_record(&buf, buf.len(), ctx).unwrap();
3718 assert_eq!(ctx.remaining_unknown_fields(), 0, "one slot per group");
3719 ufv.to_owned().expect("decode succeeded, so convert must");
3720 }
3721
3722 #[test]
3723 fn to_owned_of_malformed_manual_span_fails() {
3724 // The replay error path stays live for manually built views: a
3725 // push_raw span that is not a complete record fails to parse.
3726 let mut ufv = UnknownFieldsView::new();
3727 ufv.push_raw(&[0xFF]);
3728 assert!(ufv.to_owned().is_err());
3729 }
3730
3731 #[test]
3732 fn to_owned_of_manual_flood_over_default_limit_fails() {
3733 // The replay limit stays live for manually built views: push_raw
3734 // spans get the default allowance, no more — the memory-
3735 // amplification bound survives even though wire-decoded views
3736 // cannot hit it (decode charges the allowance up front).
3737 let n = crate::DEFAULT_UNKNOWN_FIELD_LIMIT + 1;
3738 let mut buf = alloc::vec::Vec::with_capacity(2 * n);
3739 for _ in 0..n {
3740 buf.extend_from_slice(&[0x08, 0x00]);
3741 }
3742 let mut ufv = UnknownFieldsView::new();
3743 ufv.push_raw(&buf);
3744 assert_eq!(
3745 ufv.to_owned(),
3746 Err(crate::DecodeError::UnknownFieldLimitExceeded)
3747 );
3748 }
3749
3750 #[test]
3751 fn repeated_view_reserve_grows_capacity() {
3752 let mut rv = RepeatedView::<u32>::default();
3753 rv.reserve(64);
3754 assert!(rv.elements.capacity() >= 64);
3755 // Reserve must not produce visible elements.
3756 assert!(rv.is_empty());
3757 // reserve(0) is a no-op and must not panic.
3758 rv.reserve(0);
3759 // Reserve after pushes adds capacity above current len.
3760 rv.push(1);
3761 rv.push(2);
3762 rv.reserve(100);
3763 assert_eq!(rv.len(), 2);
3764 assert!(rv.elements.capacity() >= 102);
3765 // Subsequent reserve calls must not corrupt the existing elements.
3766 let collected: alloc::vec::Vec<_> = rv.iter().copied().collect();
3767 assert_eq!(collected, alloc::vec![1, 2]);
3768 }
3769
3770 #[test]
3771 fn repeated_view_with_borrowed_str() {
3772 let data = alloc::string::String::from("hello world");
3773 let parts: alloc::vec::Vec<&str> = data.split_whitespace().collect();
3774 let rv = RepeatedView::new(parts);
3775 assert_eq!(rv.len(), 2);
3776 assert_eq!(rv[0], "hello");
3777 assert_eq!(rv[1], "world");
3778 }
3779
3780 #[test]
3781 fn repeated_view_into_iter_by_ref() {
3782 let rv = RepeatedView::new(alloc::vec![1, 2, 3]);
3783 let sum: i32 = (&rv).into_iter().sum();
3784 assert_eq!(sum, 6);
3785 // `for x in &rv` syntax works:
3786 let mut count = 0;
3787 for _ in &rv {
3788 count += 1;
3789 }
3790 assert_eq!(count, 3);
3791 }
3792
3793 #[test]
3794 fn repeated_view_into_iter_by_value() {
3795 let rv = RepeatedView::new(alloc::vec![
3796 alloc::string::String::from("a"),
3797 alloc::string::String::from("b"),
3798 ]);
3799 let collected: alloc::vec::Vec<_> = rv.into_iter().collect();
3800 assert_eq!(collected, alloc::vec!["a".to_string(), "b".to_string()]);
3801 }
3802
3803 // ── MapView ──────────────────────────────────────────────────────────
3804
3805 #[test]
3806 fn map_view_get_with_borrow() {
3807 let mut mv = MapView::<&str, i32>::default();
3808 mv.push("apples", 3);
3809 mv.push("bananas", 5);
3810
3811 // Ergonomic: get("key") works via Borrow<str> on &str
3812 assert_eq!(mv.get("apples"), Some(&3));
3813 assert_eq!(mv.get("bananas"), Some(&5));
3814 assert_eq!(mv.get("oranges"), None);
3815
3816 // Old style still works
3817 assert_eq!(mv.get(&"apples"), Some(&3));
3818 }
3819
3820 #[test]
3821 fn map_view_contains_key_with_borrow() {
3822 let mut mv = MapView::<&str, i32>::default();
3823 mv.push("key", 1);
3824
3825 assert!(mv.contains_key("key"));
3826 assert!(!mv.contains_key("missing"));
3827 }
3828
3829 #[test]
3830 fn map_view_get_last_write_wins() {
3831 let mut mv = MapView::<&str, i32>::default();
3832 mv.push("x", 1);
3833 mv.push("x", 2);
3834 assert_eq!(mv.get("x"), Some(&2));
3835 }
3836
3837 #[test]
3838 fn map_view_iter_unique_dedups_last_write_wins() {
3839 let mut mv = MapView::<&str, i32>::default();
3840 mv.push("a", 1);
3841 mv.push("b", 2);
3842 mv.push("a", 3); // duplicate key — only this entry survives for "a"
3843 mv.push("c", 4);
3844 mv.push("b", 5); // duplicate key — only this entry survives for "b"
3845
3846 assert_eq!(mv.len(), 5, "iter() preserves all wire entries");
3847 assert_eq!(mv.len_unique(), 3, "len_unique() counts distinct keys");
3848
3849 let unique: alloc::vec::Vec<_> = mv.iter_unique().collect();
3850 assert_eq!(unique, [&("a", 3), &("c", 4), &("b", 5)]);
3851 }
3852
3853 #[test]
3854 fn map_view_iter_unique_all_duplicates() {
3855 let mut mv = MapView::<&str, i32>::default();
3856 mv.push("a", 1);
3857 mv.push("a", 2);
3858 mv.push("a", 3);
3859 assert_eq!(mv.len_unique(), 1);
3860 assert_eq!(
3861 mv.iter_unique().collect::<alloc::vec::Vec<_>>(),
3862 [&("a", 3)]
3863 );
3864 }
3865
3866 #[test]
3867 fn map_view_iter_unique_no_duplicates() {
3868 let mut mv = MapView::<i32, &str>::default();
3869 mv.push(1, "x");
3870 mv.push(2, "y");
3871 assert_eq!(mv.len_unique(), 2);
3872 assert_eq!(
3873 mv.iter_unique().collect::<alloc::vec::Vec<_>>(),
3874 [&(1, "x"), &(2, "y")]
3875 );
3876 }
3877
3878 #[test]
3879 fn map_view_iter_unique_empty() {
3880 let mv = MapView::<&str, i32>::default();
3881 assert_eq!(mv.len_unique(), 0);
3882 assert_eq!(mv.iter_unique().count(), 0);
3883 }
3884
3885 /// A key that counts how many times it is compared, so the dedup's
3886 /// complexity can be asserted without timing anything.
3887 ///
3888 /// Both `eq` and `cmp` are counted. Counting only `cmp` would miss an
3889 /// equality-based pairwise scan entirely — which is exactly the shape
3890 /// this guard exists to catch.
3891 #[derive(Debug, Clone, Copy, Eq)]
3892 struct CountingKey(u32);
3893
3894 // Process-global and tests run in parallel: only one test may use
3895 // `CountingKey`, or the counts interleave.
3896 static CMPS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
3897
3898 fn bump() {
3899 CMPS.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3900 }
3901
3902 impl PartialEq for CountingKey {
3903 fn eq(&self, other: &Self) -> bool {
3904 bump();
3905 self.0 == other.0
3906 }
3907 }
3908 impl PartialOrd for CountingKey {
3909 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
3910 Some(self.cmp(other))
3911 }
3912 }
3913 impl Ord for CountingKey {
3914 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
3915 bump();
3916 self.0.cmp(&other.0)
3917 }
3918 }
3919
3920 #[test]
3921 fn map_view_iter_unique_is_not_quadratic_on_distinct_keys() {
3922 use core::sync::atomic::Ordering;
3923
3924 // All-distinct keys are what ordinary well-formed wire data looks
3925 // like, and they are the shape a pairwise scan handles worst: its
3926 // early exit only fires on a duplicate, so having none means every
3927 // scan runs to the end. That is what this guard watches for.
3928 const N: u32 = 4096;
3929 let entries: alloc::vec::Vec<_> = (0..N).map(|i| (CountingKey(i), i)).collect();
3930 let mv = MapView::new(entries);
3931
3932 CMPS.store(0, Ordering::Relaxed);
3933 let seen = mv.iter_unique().count();
3934 let cmps = CMPS.load(Ordering::Relaxed);
3935
3936 assert_eq!(seen, N as usize, "every distinct key survives");
3937 // n log2 n is ~49k here; the pairwise scan would be ~8.4M. Two orders
3938 // of magnitude apart, so this bound is loose enough not to be brittle
3939 // and tight enough that a return to quadratic cannot slip past.
3940 let budget = 100 * N as usize;
3941 assert!(
3942 cmps < budget,
3943 "dedup of {N} distinct keys took {cmps} comparisons, over the {budget} budget — \
3944 this is the quadratic regression guard"
3945 );
3946 }
3947
3948 #[test]
3949 fn map_view_iter_unique_keeps_last_occurrence_across_many_duplicates() {
3950 // Interleaved duplicates, with the final round written in a scrambled
3951 // key order so that wire order of the survivors differs from key
3952 // order — the assertion can then tell the two apart.
3953 let mut mv = MapView::<i32, i32>::default();
3954 for round in 0..3 {
3955 for key in 0..8 {
3956 mv.push(key, round * 100 + key);
3957 }
3958 }
3959 let last_round = [5, 2, 7, 0, 3, 6, 1, 4];
3960 for key in last_round {
3961 mv.push(key, 300 + key);
3962 }
3963 let unique: alloc::vec::Vec<_> = mv.iter_unique().copied().collect();
3964 let expected: alloc::vec::Vec<(i32, i32)> =
3965 last_round.iter().map(|&k| (k, 300 + k)).collect();
3966 assert_eq!(unique, expected, "last write wins, survivors in wire order");
3967 assert_eq!(mv.len_unique(), 8);
3968 assert_eq!(mv.iter_unique().len(), 8, "exact size hint");
3969 assert_eq!(mv.len(), 32, "iter() still sees every wire entry");
3970 }
3971
3972 #[test]
3973 fn map_view_iter_unique_small_maps() {
3974 // n = 1 takes the no-sort early return; n = 2 with a duplicate is the
3975 // smallest input that reaches the sort and the run compaction.
3976 let one = MapView::new(alloc::vec![("k", 1)]);
3977 assert_eq!(
3978 one.iter_unique().copied().collect::<alloc::vec::Vec<_>>(),
3979 [("k", 1)]
3980 );
3981 assert_eq!(one.len_unique(), 1);
3982
3983 let two_dup = MapView::new(alloc::vec![("k", 1), ("k", 2)]);
3984 assert_eq!(
3985 two_dup
3986 .iter_unique()
3987 .copied()
3988 .collect::<alloc::vec::Vec<_>>(),
3989 [("k", 2)]
3990 );
3991 assert_eq!(two_dup.len_unique(), 1);
3992
3993 let two_distinct = MapView::new(alloc::vec![("b", 1), ("a", 2)]);
3994 assert_eq!(
3995 two_distinct
3996 .iter_unique()
3997 .copied()
3998 .collect::<alloc::vec::Vec<_>>(),
3999 [("b", 1), ("a", 2)],
4000 "wire order, not key order"
4001 );
4002 }
4003
4004 #[test]
4005 fn map_view_keys_and_values() {
4006 let mut mv = MapView::<&str, i32>::default();
4007 mv.push("a", 1);
4008 mv.push("b", 2);
4009 mv.push("c", 3);
4010
4011 let keys: alloc::vec::Vec<_> = mv.keys().copied().collect();
4012 assert_eq!(keys, alloc::vec!["a", "b", "c"]);
4013
4014 let values: alloc::vec::Vec<_> = mv.values().copied().collect();
4015 assert_eq!(values, alloc::vec![1, 2, 3]);
4016 }
4017
4018 #[test]
4019 fn map_view_keys_and_values_empty() {
4020 let mv = MapView::<&str, i32>::default();
4021 assert_eq!(mv.keys().count(), 0);
4022 assert_eq!(mv.values().count(), 0);
4023 }
4024
4025 #[test]
4026 fn map_view_into_iter_collect_to_hashmap() {
4027 let mut mv = MapView::<&str, i32>::default();
4028 mv.push("a", 1);
4029 mv.push("b", 2);
4030 mv.push("a", 3); // duplicate — last-write-wins on collect
4031 let m: crate::__private::HashMap<&str, i32> = mv.into_iter().collect();
4032 assert_eq!(m.len(), 2);
4033 assert_eq!(m.get("a"), Some(&3)); // last value kept
4034 assert_eq!(m.get("b"), Some(&2));
4035 }
4036
4037 // ── bytes_from_source ────────────────────────────────────────────────
4038
4039 #[test]
4040 fn bytes_from_source_none_copies() {
4041 let data: &[u8] = b"hello";
4042 let out = bytes_from_source(None, data);
4043 assert_eq!(&out[..], data);
4044 assert_ne!(out.as_ptr(), data.as_ptr()); // distinct allocation
4045 }
4046
4047 #[test]
4048 fn bytes_from_source_some_within_is_slice_ref() {
4049 let parent = Bytes::copy_from_slice(b"hello world");
4050 let slice = &parent[6..11];
4051 let out = bytes_from_source(Some(&parent), slice);
4052 assert_eq!(&out[..], b"world");
4053 // slice_ref shares the same backing storage — same pointer.
4054 assert_eq!(out.as_ptr(), slice.as_ptr());
4055 }
4056
4057 #[test]
4058 fn bytes_from_source_some_outside_falls_back_to_copy() {
4059 let parent = Bytes::copy_from_slice(b"hello");
4060 let outside: &[u8] = b"world"; // static, not in `parent`
4061 let out = bytes_from_source(Some(&parent), outside);
4062 assert_eq!(&out[..], b"world");
4063 assert_ne!(out.as_ptr(), outside.as_ptr());
4064 }
4065
4066 #[test]
4067 fn bytes_from_source_empty_returns_new() {
4068 let parent = Bytes::copy_from_slice(b"hello");
4069 assert!(bytes_from_source(Some(&parent), &[]).is_empty());
4070 assert!(bytes_from_source(None, &[]).is_empty());
4071 }
4072
4073 #[test]
4074 fn bytes_from_source_full_range() {
4075 let parent = Bytes::copy_from_slice(b"hello");
4076 let out = bytes_from_source(Some(&parent), &parent[..]);
4077 assert_eq!(out.as_ptr(), parent.as_ptr());
4078 assert_eq!(out.len(), parent.len());
4079 }
4080
4081 // ── UnknownFieldsView ────────────────────────────────────────────────
4082
4083 #[test]
4084 fn unknown_fields_view_new_is_empty() {
4085 let uf = UnknownFieldsView::new();
4086 assert!(uf.is_empty());
4087 assert_eq!(uf.encoded_len(), 0);
4088 }
4089
4090 #[test]
4091 fn unknown_fields_view_push_raw_and_encoded_len() {
4092 let mut uf = UnknownFieldsView::new();
4093 uf.push_raw(&[0x08, 0x01]); // field 1, varint 1
4094 uf.push_raw(&[0x10, 0x02]); // field 2, varint 2
4095 assert!(!uf.is_empty());
4096 assert_eq!(uf.encoded_len(), 4);
4097 }
4098
4099 #[test]
4100 fn unknown_fields_view_to_owned_single_field() {
4101 // Build a valid unknown field: tag for field 99, varint wire type,
4102 // value 42. Tag = (99 << 3) | 0 = 792 = varint bytes [0x98, 0x06].
4103 let span: &[u8] = &[0x98, 0x06, 0x2A];
4104 let mut uf = UnknownFieldsView::new();
4105 uf.push_raw(span);
4106
4107 let owned = uf.to_owned().expect("valid wire data");
4108 assert_eq!(owned.len(), 1);
4109 let field = owned.iter().next().unwrap();
4110 assert_eq!(field.number, 99);
4111 assert_eq!(
4112 field.data,
4113 crate::unknown_fields::UnknownFieldData::Varint(42)
4114 );
4115 }
4116
4117 #[test]
4118 fn unknown_fields_view_to_owned_multiple_fields() {
4119 let mut uf = UnknownFieldsView::new();
4120 // Field 1, varint, value 7: tag = (1<<3)|0 = 0x08, value = 0x07
4121 uf.push_raw(&[0x08, 0x07]);
4122 // Field 2, fixed32, value 0x01020304:
4123 // tag = (2<<3)|5 = 0x15, then 4 LE bytes
4124 uf.push_raw(&[0x15, 0x04, 0x03, 0x02, 0x01]);
4125
4126 let owned = uf.to_owned().expect("valid wire data");
4127 assert_eq!(owned.len(), 2);
4128
4129 let mut it = owned.iter();
4130 let f1 = it.next().unwrap();
4131 assert_eq!(f1.number, 1);
4132 assert_eq!(f1.data, crate::unknown_fields::UnknownFieldData::Varint(7));
4133
4134 let f2 = it.next().unwrap();
4135 assert_eq!(f2.number, 2);
4136 assert_eq!(
4137 f2.data,
4138 crate::unknown_fields::UnknownFieldData::Fixed32(0x01020304)
4139 );
4140 }
4141
4142 #[test]
4143 fn unknown_fields_view_to_owned_malformed_returns_error() {
4144 // A truncated tag (high continuation bit, then EOF).
4145 let mut uf = UnknownFieldsView::new();
4146 uf.push_raw(&[0x80]);
4147 assert!(uf.to_owned().is_err());
4148 }
4149
4150 #[test]
4151 fn unknown_fields_view_to_owned_includes_synthetic_varint_records() {
4152 let ctx = record_ctx(1);
4153 let mut uf = UnknownFieldsView::new();
4154 uf.push_varint(3, 99, ctx).unwrap();
4155 assert_eq!(ctx.remaining_unknown_fields(), 0);
4156
4157 let owned = uf.to_owned().expect("owned unknown field");
4158 let fields: Vec<_> = owned.iter().collect();
4159 assert_eq!(fields.len(), 1);
4160 assert_eq!(fields[0].number, 3);
4161 assert!(matches!(
4162 fields[0].data,
4163 crate::UnknownFieldData::Varint(99)
4164 ));
4165 }
4166
4167 // ── OwnedView ──────────────────────────────────────────────────────
4168
4169 // Minimal types to test OwnedView without depending on generated code.
4170
4171 use crate::message::Message;
4172
4173 /// A trivial "message" for the owned side of the view contract.
4174 #[derive(Clone, Debug, Default, PartialEq)]
4175 struct SimpleMessage {
4176 pub id: i32,
4177 pub name: alloc::string::String,
4178 }
4179
4180 impl crate::DefaultInstance for SimpleMessage {
4181 fn default_instance() -> &'static Self {
4182 static INST: crate::__private::OnceBox<SimpleMessage> =
4183 crate::__private::OnceBox::new();
4184 INST.get_or_init(|| alloc::boxed::Box::new(SimpleMessage::default()))
4185 }
4186 }
4187
4188 impl crate::Message for SimpleMessage {
4189 fn compute_size(&self, _cache: &mut crate::SizeCache) -> u32 {
4190 let mut size = 0u32;
4191 if self.id != 0 {
4192 size += 1 + crate::types::int32_encoded_len(self.id) as u32;
4193 }
4194 if !self.name.is_empty() {
4195 size += 1 + crate::types::string_encoded_len(&self.name) as u32;
4196 }
4197 size
4198 }
4199
4200 fn write_to(&self, _cache: &mut crate::SizeCache, buf: &mut impl crate::EncodeSink) {
4201 if self.id != 0 {
4202 crate::encoding::Tag::new(1, crate::encoding::WireType::Varint).encode(buf);
4203 crate::types::encode_int32(self.id, buf);
4204 }
4205 if !self.name.is_empty() {
4206 crate::encoding::Tag::new(2, crate::encoding::WireType::LengthDelimited)
4207 .encode(buf);
4208 crate::types::encode_string(&self.name, buf);
4209 }
4210 }
4211
4212 fn merge_field(
4213 &mut self,
4214 tag: crate::encoding::Tag,
4215 buf: &mut impl bytes::Buf,
4216 _ctx: crate::DecodeContext<'_>,
4217 ) -> Result<(), DecodeError> {
4218 match tag.field_number() {
4219 1 => self.id = crate::types::decode_int32(buf)?,
4220 2 => crate::types::merge_string(&mut self.name, buf)?,
4221 _ => crate::encoding::skip_field(tag, buf)?,
4222 }
4223 Ok(())
4224 }
4225
4226 fn clear(&mut self) {
4227 self.id = 0;
4228 self.name.clear();
4229 }
4230 }
4231
4232 /// A zero-copy view of `SimpleMessage`. Borrows `name` as `&str`.
4233 #[derive(Clone, Debug, Default, PartialEq)]
4234 struct SimpleMessageView<'a> {
4235 pub id: i32,
4236 pub name: &'a str,
4237 }
4238
4239 // Via the exported macro, which doubles as its unit test.
4240 crate::impl_view_reborrow!(SimpleMessageView);
4241
4242 // Via the exported macro, which doubles as its unit test.
4243 // SAFETY: `SimpleMessageView<'a>` is generic over `'a`; every impl on it
4244 // other than the canonical `impl_view_reborrow!` is parametric in `'a`,
4245 // so none can retain a buffer borrow past `Self`.
4246 crate::unsafe_impl_view_lifetime_parametric!(SimpleMessageView);
4247
4248 #[cfg(feature = "json")]
4249 impl ::serde::Serialize for SimpleMessageView<'_> {
4250 fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
4251 use ::serde::ser::SerializeStruct as _;
4252 let mut st = s.serialize_struct("SimpleMessage", 2)?;
4253 st.serialize_field("id", &self.id)?;
4254 st.serialize_field("name", self.name)?;
4255 st.end()
4256 }
4257 }
4258
4259 impl<'a> MessageView<'a> for SimpleMessageView<'a> {
4260 type Owned = SimpleMessage;
4261 fn merge_view_field(
4262 &mut self,
4263 _tag: crate::encoding::Tag,
4264 cur: &'a [u8],
4265 _before_tag: &'a [u8],
4266 _ctx: crate::DecodeContext<'_>,
4267 ) -> Result<&'a [u8], DecodeError> {
4268 Ok(cur)
4269 }
4270
4271 fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError> {
4272 let mut view = SimpleMessageView::default();
4273 let mut cursor: &'a [u8] = buf;
4274 while !cursor.is_empty() {
4275 let tag = crate::encoding::Tag::decode(&mut cursor)?;
4276 match tag.field_number() {
4277 1 => view.id = crate::types::decode_int32(&mut cursor)?,
4278 2 => view.name = crate::types::borrow_str(&mut cursor)?,
4279 _ => crate::encoding::skip_field(tag, &mut cursor)?,
4280 }
4281 }
4282 Ok(view)
4283 }
4284
4285 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
4286 Ok(SimpleMessage {
4287 id: self.id,
4288 name: self.name.into(),
4289 })
4290 }
4291 }
4292
4293 impl<'a> ViewEncode<'a> for SimpleMessageView<'a> {
4294 fn compute_size(&self, _cache: &mut crate::SizeCache) -> u32 {
4295 let mut size = 0u32;
4296 if self.id != 0 {
4297 size += 1 + crate::types::int32_encoded_len(self.id) as u32;
4298 }
4299 if !self.name.is_empty() {
4300 size += 1 + crate::types::string_encoded_len(self.name) as u32;
4301 }
4302 size
4303 }
4304
4305 fn write_to(&self, _cache: &mut crate::SizeCache, buf: &mut impl crate::EncodeSink) {
4306 if self.id != 0 {
4307 crate::encoding::Tag::new(1, crate::encoding::WireType::Varint).encode(buf);
4308 crate::types::encode_int32(self.id, buf);
4309 }
4310 if !self.name.is_empty() {
4311 crate::encoding::Tag::new(2, crate::encoding::WireType::LengthDelimited)
4312 .encode(buf);
4313 crate::types::encode_string(self.name, buf);
4314 }
4315 }
4316 }
4317
4318 /// Encode a SimpleMessage to Bytes for testing.
4319 fn encode_simple(id: i32, name: &str) -> Bytes {
4320 let msg = SimpleMessage {
4321 id,
4322 name: name.into(),
4323 };
4324 Bytes::from(msg.encode_to_vec())
4325 }
4326
4327 // The `contiguous_sink_` prefix is the filter for the `Miri` CI step that
4328 // covers the pre-sized cursor.
4329 #[test]
4330 fn contiguous_sink_view_encode_matches_owned() {
4331 let view = SimpleMessageView {
4332 id: 300,
4333 name: "view",
4334 };
4335 let owned = SimpleMessage {
4336 id: 300,
4337 name: "view".into(),
4338 };
4339 let expected = owned.encode_to_vec();
4340 assert_eq!(view.encode_to_vec(), expected);
4341
4342 let mut bytes_mut = bytes::BytesMut::new();
4343 view.encode(&mut bytes_mut);
4344 assert_eq!(&bytes_mut[..], &expected[..]);
4345
4346 let mut roomy = alloc::vec::Vec::with_capacity(64);
4347 view.encode_length_delimited(&mut roomy);
4348 assert_eq!(roomy[0] as usize, expected.len());
4349 assert_eq!(&roomy[1..], &expected[..]);
4350
4351 let mut rope = crate::Rope::new();
4352 view.encode(&mut rope);
4353 assert_eq!(&rope.to_contiguous_bytes()[..], &expected[..]);
4354
4355 let mut bounded = alloc::vec::Vec::new();
4356 let len = view.try_encode_bounded(64, &mut bounded);
4357 assert_eq!(len, Ok(expected.len() as u32));
4358 assert_eq!(bounded, expected);
4359 }
4360
4361 /// A `BufMut` with room receives the view through `advance_mut`, not
4362 /// through `put_*`.
4363 #[test]
4364 fn contiguous_sink_view_encode_writes_in_place() {
4365 let view = SimpleMessageView {
4366 id: 300,
4367 name: "view",
4368 };
4369 let mut probe = crate::test_doubles::Probe::default();
4370 probe.inner.reserve(64);
4371 view.encode(&mut probe);
4372 assert_eq!((probe.advance_mut_calls, probe.put_slice_calls), (1, 0));
4373 assert_eq!(probe.inner.len(), view.encoded_len() as usize);
4374 }
4375
4376 #[test]
4377 fn owned_view_decode_and_reborrow() {
4378 let bytes = encode_simple(42, "hello");
4379 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4380
4381 // Field access via reborrow — the borrow is tied to `view`.
4382 assert_eq!(view.reborrow().id, 42);
4383 assert_eq!(view.reborrow().name, "hello");
4384 }
4385
4386 #[test]
4387 fn owned_view_to_owned_message() {
4388 let bytes = encode_simple(7, "world");
4389 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4390 let owned = view.to_owned_message();
4391
4392 assert_eq!(owned.id, 7);
4393 assert_eq!(owned.name, "world");
4394 }
4395
4396 /// A view whose `to_owned_message` breaks the wire-decode ⇒ convert
4397 /// contract, standing in for a buggy hand-written impl.
4398 #[derive(Clone, Debug, Default, PartialEq)]
4399 struct ContractBreakingView<'a>(core::marker::PhantomData<&'a ()>);
4400
4401 crate::impl_view_reborrow!(ContractBreakingView);
4402
4403 // SAFETY: holds no borrows at all (`PhantomData` only); every impl is
4404 // parametric in `'a`.
4405 unsafe impl ViewLifetimeParametric for ContractBreakingView<'static> {}
4406
4407 impl<'a> MessageView<'a> for ContractBreakingView<'a> {
4408 type Owned = SimpleMessage;
4409 fn merge_view_field(
4410 &mut self,
4411 _tag: crate::encoding::Tag,
4412 cur: &'a [u8],
4413 _before_tag: &'a [u8],
4414 _ctx: crate::DecodeContext<'_>,
4415 ) -> Result<&'a [u8], DecodeError> {
4416 Ok(cur)
4417 }
4418 fn decode_view(_buf: &'a [u8]) -> Result<Self, DecodeError> {
4419 Ok(Self(core::marker::PhantomData))
4420 }
4421 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
4422 Err(DecodeError::UnknownFieldLimitExceeded)
4423 }
4424 }
4425
4426 #[test]
4427 #[should_panic(expected = "wire-decode => convert contract")]
4428 fn owned_view_panics_when_impl_breaks_convert_contract() {
4429 // The infallible signature rests on the decode ⇒ convert invariant;
4430 // an impl that violates it must fail loudly, not silently.
4431 let view = OwnedView::<ContractBreakingView<'static>>::decode(Bytes::new()).unwrap();
4432 let _ = view.to_owned_message();
4433 }
4434
4435 /// Every `OwnedView` path that touches `V` — decode, `Debug`, `Clone`,
4436 /// `PartialEq`, `reborrow`, `to_owned_message`, drop — on a hand-written
4437 /// parametric view, so Miri can confirm none of them reads the buffer
4438 /// after its handle drops (CI runs this under Miri; see
4439 /// `.github/workflows/ci.yml`). The negative case — a non-parametric
4440 /// view reaching the forged `'static` buffer — is the `compile_fail`
4441 /// doctest on [`ViewLifetimeParametric`].
4442 ///
4443 /// Handles go out of scope instead of being passed to `drop`: Miri
4444 /// protects the forged `&'static [u8]` inside a by-value `OwnedView`
4445 /// argument for the callee's whole frame, so freeing the `Bytes` in that
4446 /// frame is reported as UB even though nothing reads through it.
4447 #[test]
4448 fn owned_view_lifetime_parametric_contract() {
4449 let bytes = encode_simple(9, "parametric");
4450 let (cloned, owned) = {
4451 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4452 let cloned = view.clone();
4453 assert_eq!(view, cloned);
4454 assert_eq!(alloc::format!("{view:?}"), alloc::format!("{cloned:?}"));
4455 assert_eq!(view.reborrow().name, "parametric");
4456 (cloned, view.to_owned_message())
4457 // `view` drops here, before the clone is read.
4458 };
4459 // The clone holds its own `Bytes` handle, so its buffer is still alive.
4460 assert_eq!(cloned.reborrow().name, "parametric");
4461 {
4462 let _last = cloned;
4463 // The last handle drops here; `owned` copied the string out.
4464 }
4465 assert_eq!(owned.id, 9);
4466 assert_eq!(owned.name, "parametric");
4467 }
4468
4469 /// `OwnedView`'s `Serialize` goes through `reborrow`, so the view's own
4470 /// impl is invoked on `SimpleMessageView<'b>`, never on the
4471 /// `'static`-typed value.
4472 #[cfg(feature = "json")]
4473 #[test]
4474 fn owned_view_serialize_delegates_through_reborrow() {
4475 let view = OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(3, "js")).unwrap();
4476 let json = ::serde_json::to_string(&view).unwrap();
4477 assert_eq!(json, ::serde_json::to_string(view.reborrow()).unwrap());
4478 assert_eq!(json, r#"{"id":3,"name":"js"}"#);
4479 }
4480
4481 #[test]
4482 fn owned_view_debug_delegates_to_view() {
4483 let bytes = encode_simple(1, "test");
4484 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4485 let debug = alloc::format!("{:?}", view);
4486 assert!(debug.contains("test"));
4487 assert!(debug.contains("1"));
4488 }
4489
4490 #[test]
4491 fn owned_view_bytes_accessor() {
4492 let bytes = encode_simple(5, "data");
4493 let original_len = bytes.len();
4494 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4495
4496 assert_eq!(view.bytes().len(), original_len);
4497 }
4498
4499 #[test]
4500 fn owned_view_into_bytes_recovers_buffer() {
4501 let bytes = encode_simple(99, "recover");
4502 let expected = bytes.clone();
4503 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4504 let recovered = view.into_bytes();
4505
4506 assert_eq!(recovered, expected);
4507 }
4508
4509 #[test]
4510 fn owned_view_decode_invalid_data_returns_error() {
4511 // Truncated varint
4512 let bad = Bytes::from_static(&[0x08, 0x80]);
4513 let result = OwnedView::<SimpleMessageView<'static>>::decode(bad);
4514 assert!(result.is_err());
4515 }
4516
4517 #[test]
4518 fn owned_view_empty_message() {
4519 let bytes = Bytes::from_static(&[]);
4520 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4521 assert_eq!(view.reborrow().id, 0);
4522 assert_eq!(view.reborrow().name, "");
4523 }
4524
4525 #[test]
4526 fn owned_view_is_send_and_sync() {
4527 fn assert_send_sync<T: Send + Sync>() {}
4528 assert_send_sync::<OwnedView<SimpleMessageView<'static>>>();
4529 }
4530
4531 #[test]
4532 fn owned_view_from_owned_roundtrips() {
4533 let msg = SimpleMessage {
4534 id: 99,
4535 name: "roundtrip".into(),
4536 };
4537 let view = OwnedView::<SimpleMessageView<'static>>::from_owned(&msg).expect("from_owned");
4538 assert_eq!(view.reborrow().id, 99);
4539 assert_eq!(view.reborrow().name, "roundtrip");
4540
4541 let back = view.to_owned_message();
4542 assert_eq!(back, msg);
4543 }
4544
4545 #[test]
4546 fn owned_view_decode_with_options() {
4547 let bytes = encode_simple(42, "opts");
4548 let opts = crate::DecodeOptions::new().with_max_message_size(1024);
4549 let view =
4550 OwnedView::<SimpleMessageView<'static>>::decode_with_options(bytes, &opts).unwrap();
4551 assert_eq!(view.reborrow().id, 42);
4552 assert_eq!(view.reborrow().name, "opts");
4553 }
4554
4555 #[test]
4556 fn owned_view_decode_with_options_rejects_oversized() {
4557 let bytes = encode_simple(42, "too large");
4558 let opts = crate::DecodeOptions::new().with_max_message_size(2);
4559 let result = OwnedView::<SimpleMessageView<'static>>::decode_with_options(bytes, &opts);
4560 assert!(result.is_err());
4561 }
4562
4563 #[test]
4564 fn owned_view_clone_survives_original_drop() {
4565 let bytes = encode_simple(42, "cloned");
4566 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4567 let cloned = view.clone();
4568 drop(view); // drop original — clone must still be valid
4569 assert_eq!(cloned.reborrow().id, 42);
4570 assert_eq!(cloned.reborrow().name, "cloned");
4571 }
4572
4573 #[test]
4574 fn owned_view_clone_equality() {
4575 let bytes = encode_simple(42, "eq");
4576 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4577 let cloned = view.clone();
4578 assert_eq!(view, cloned);
4579 }
4580
4581 #[test]
4582 fn owned_view_eq_same_data() {
4583 let a = OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(1, "x")).unwrap();
4584 let b = OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(1, "x")).unwrap();
4585 assert_eq!(a, b);
4586 }
4587
4588 #[test]
4589 fn owned_view_ne_different_data() {
4590 let a = OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(1, "x")).unwrap();
4591 let b = OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(2, "y")).unwrap();
4592 assert_ne!(a, b);
4593 }
4594
4595 #[test]
4596 fn owned_view_into_bytes_after_clone() {
4597 let bytes = encode_simple(42, "test");
4598 let expected = bytes.clone();
4599 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4600 let cloned = view.clone();
4601 drop(view); // drop original first
4602 let recovered = cloned.into_bytes();
4603 assert_eq!(recovered, expected);
4604 }
4605
4606 // The `owned_view_drop*` and `owned_view_into_bytes*` names below are
4607 // the filter for the `Miri (OwnedView soundness)` CI step; a renamed or
4608 // differently named test silently leaves that gate.
4609 #[test]
4610 fn owned_view_drop_count() {
4611 use core::sync::atomic::{AtomicUsize, Ordering};
4612
4613 static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4614
4615 /// A wrapper view that counts drops.
4616 #[derive(Debug)]
4617 struct DropCountingView<'a> {
4618 inner: SimpleMessageView<'a>,
4619 }
4620
4621 impl Drop for DropCountingView<'_> {
4622 fn drop(&mut self) {
4623 DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4624 }
4625 }
4626
4627 crate::impl_view_reborrow!(DropCountingView);
4628
4629 // SAFETY: wraps `SimpleMessageView<'a>` (itself `ViewLifetimeParametric`);
4630 // the `Drop` impl only touches a counter, and every impl other than
4631 // the canonical `impl_view_reborrow!` is parametric in `'a`.
4632 unsafe impl ViewLifetimeParametric for DropCountingView<'static> {}
4633
4634 impl<'a> MessageView<'a> for DropCountingView<'a> {
4635 type Owned = SimpleMessage;
4636 fn merge_view_field(
4637 &mut self,
4638 _tag: crate::encoding::Tag,
4639 cur: &'a [u8],
4640 _before_tag: &'a [u8],
4641 _ctx: crate::DecodeContext<'_>,
4642 ) -> Result<&'a [u8], DecodeError> {
4643 Ok(cur)
4644 }
4645
4646 fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError> {
4647 Ok(DropCountingView {
4648 inner: SimpleMessageView::decode_view(buf)?,
4649 })
4650 }
4651
4652 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
4653 self.inner.to_owned_message()
4654 }
4655 }
4656
4657 // Test normal drop: view drops exactly once.
4658 DROP_COUNT.store(0, Ordering::SeqCst);
4659 {
4660 let bytes = encode_simple(1, "drop");
4661 let _view = OwnedView::<DropCountingView<'static>>::decode(bytes).unwrap();
4662 }
4663 assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1, "normal drop");
4664
4665 // Test into_bytes: view drops exactly once.
4666 DROP_COUNT.store(0, Ordering::SeqCst);
4667 {
4668 let bytes = encode_simple(2, "into");
4669 let view = OwnedView::<DropCountingView<'static>>::decode(bytes).unwrap();
4670 let _bytes = view.into_bytes();
4671 }
4672 assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1, "into_bytes drop");
4673 }
4674
4675 /// Dropping an `OwnedView` that arrived as a by-value argument frees the
4676 /// buffer inside a call that still holds the view's forged `'static`
4677 /// borrows. Under Miri's field retagging that is UB unless the view is
4678 /// behind `MaybeDangling`, so this is a Miri regression test (it cannot
4679 /// fail under plain `cargo test`).
4680 #[test]
4681 fn owned_view_drop_by_value_argument() {
4682 fn consume<V>(v: OwnedView<V>) {
4683 drop(v);
4684 }
4685 let view =
4686 OwnedView::<SimpleMessageView<'static>>::decode(encode_simple(4, "arg")).unwrap();
4687 consume(view);
4688 }
4689
4690 /// A `V::drop` that panics during `into_bytes` must not drop the view a
4691 /// second time on the way out.
4692 #[cfg(feature = "std")]
4693 #[test]
4694 fn owned_view_into_bytes_unwinding_view_drop_runs_once() {
4695 use core::sync::atomic::{AtomicUsize, Ordering};
4696
4697 static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4698
4699 /// Panics on its first drop only: a re-entrant second drop must not
4700 /// panic again, or the unwind would abort the process instead of
4701 /// reaching the assertion below.
4702 #[derive(Debug)]
4703 struct PanicOnFirstDropView<'a> {
4704 inner: SimpleMessageView<'a>,
4705 /// A heap allocation, so that a regression to dropping the view
4706 /// twice is a real double free (which Miri flags), not just a
4707 /// count of two.
4708 _owned: alloc::string::String,
4709 }
4710
4711 impl Drop for PanicOnFirstDropView<'_> {
4712 fn drop(&mut self) {
4713 if DROP_COUNT.fetch_add(1, Ordering::SeqCst) == 0 {
4714 panic!("first drop");
4715 }
4716 }
4717 }
4718
4719 crate::impl_view_reborrow!(PanicOnFirstDropView);
4720
4721 // SAFETY: wraps `SimpleMessageView<'a>` plus an owned `String`; the
4722 // `Drop` impl touches only a counter, and every impl other than the
4723 // canonical `impl_view_reborrow!` is parametric in `'a`.
4724 unsafe impl ViewLifetimeParametric for PanicOnFirstDropView<'static> {}
4725
4726 impl<'a> MessageView<'a> for PanicOnFirstDropView<'a> {
4727 type Owned = SimpleMessage;
4728 fn merge_view_field(
4729 &mut self,
4730 _tag: crate::encoding::Tag,
4731 cur: &'a [u8],
4732 _before_tag: &'a [u8],
4733 _ctx: crate::DecodeContext<'_>,
4734 ) -> Result<&'a [u8], DecodeError> {
4735 Ok(cur)
4736 }
4737
4738 fn decode_view(buf: &'a [u8]) -> Result<Self, DecodeError> {
4739 Ok(PanicOnFirstDropView {
4740 inner: SimpleMessageView::decode_view(buf)?,
4741 _owned: alloc::string::String::from("owned"),
4742 })
4743 }
4744
4745 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
4746 self.inner.to_owned_message()
4747 }
4748 }
4749
4750 DROP_COUNT.store(0, Ordering::SeqCst);
4751 let bytes = encode_simple(3, "unwind");
4752 let view = OwnedView::<PanicOnFirstDropView<'static>>::decode(bytes).unwrap();
4753 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| view.into_bytes()));
4754 assert!(result.is_err(), "the view's panic must propagate");
4755 assert_eq!(
4756 DROP_COUNT.load(Ordering::SeqCst),
4757 1,
4758 "view dropped exactly once"
4759 );
4760 }
4761
4762 #[test]
4763 fn owned_view_name_borrows_from_bytes_buffer() {
4764 let bytes = encode_simple(42, "borrowed");
4765 let view = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4766 let buf = view.bytes();
4767 let buf_start = buf.as_ptr() as usize;
4768 let buf_end = buf_start + buf.len();
4769 let name_ptr = view.reborrow().name.as_ptr() as usize;
4770 assert!(
4771 (buf_start..buf_end).contains(&name_ptr),
4772 "view name should point into the Bytes buffer"
4773 );
4774 }
4775
4776 #[test]
4777 fn owned_view_concurrent_read() {
4778 use alloc::sync::Arc;
4779
4780 let bytes = encode_simple(42, "concurrent");
4781 let view = Arc::new(OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap());
4782 let handles: alloc::vec::Vec<_> = (0..4)
4783 .map(|_| {
4784 let v = Arc::clone(&view);
4785 std::thread::spawn(move || {
4786 assert_eq!(v.reborrow().id, 42);
4787 assert_eq!(v.reborrow().name, "concurrent");
4788 })
4789 })
4790 .collect();
4791 for h in handles {
4792 h.join().unwrap();
4793 }
4794 }
4795
4796 #[test]
4797 fn owned_view_from_parts_roundtrip() {
4798 let bytes = encode_simple(42, "parts");
4799 // Decode a view from the bytes, then wrap via from_parts.
4800 // SAFETY: `view` was decoded from `bytes`.
4801 let view = unsafe {
4802 let slice: &'static [u8] = core::mem::transmute::<&[u8], &'static [u8]>(&bytes);
4803 let decoded = SimpleMessageView::decode_view(slice).unwrap();
4804 OwnedView::<SimpleMessageView<'static>>::from_parts(bytes, decoded)
4805 };
4806 assert_eq!(view.reborrow().id, 42);
4807 assert_eq!(view.reborrow().name, "parts");
4808 }
4809
4810 // ── ViewReborrow / OwnedView::reborrow ───────────────────────────────
4811
4812 #[test]
4813 fn reborrow_fields_match_original() {
4814 let bytes = encode_simple(7, "hello");
4815 let owned = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4816 let reborrowed: &SimpleMessageView<'_> = owned.reborrow();
4817 assert_eq!(reborrowed.id, 7);
4818 assert_eq!(reborrowed.name, "hello");
4819 // The reborrowed &str must point into the Bytes buffer, not a copy.
4820 let buf_start = owned.bytes().as_ptr() as usize;
4821 let buf_end = buf_start + owned.bytes().len();
4822 assert!((buf_start..buf_end).contains(&(reborrowed.name.as_ptr() as usize)));
4823 }
4824
4825 #[test]
4826 fn reborrow_does_not_consume_owned_view() {
4827 let bytes = encode_simple(1, "world");
4828 let owned = OwnedView::<SimpleMessageView<'static>>::decode(bytes).unwrap();
4829 let r1: &SimpleMessageView<'_> = owned.reborrow();
4830 let r2: &SimpleMessageView<'_> = owned.reborrow();
4831 assert_eq!(r1.name, r2.name);
4832 // `owned` still usable here
4833 assert_eq!(owned.reborrow().name, "world");
4834 }
4835 // ── Lazy views ───────────────────────────────────────────────────────
4836
4837 /// Hand-written lazy view of `SimpleMessage`, shaped like generated
4838 /// `FooLazyView` code: scalars borrowed, one flat scan, fragment merge.
4839 #[derive(Clone, Debug, Default, PartialEq)]
4840 struct SimpleLazyView<'a> {
4841 pub id: i32,
4842 pub name: &'a str,
4843 }
4844
4845 impl<'a> LazyMessageView<'a> for SimpleLazyView<'a> {
4846 type Owned = SimpleMessage;
4847
4848 fn decode_lazy(buf: &'a [u8]) -> Result<Self, DecodeError> {
4849 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
4850 Self::decode_lazy_with_ctx(
4851 buf,
4852 crate::DecodeContext::new(crate::RECURSION_LIMIT, &limit),
4853 )
4854 }
4855
4856 fn decode_lazy_with_ctx(
4857 buf: &'a [u8],
4858 ctx: crate::DecodeContext<'_>,
4859 ) -> Result<Self, DecodeError> {
4860 let mut view = SimpleLazyView::default();
4861 view.merge_lazy(buf, ctx)?;
4862 Ok(view)
4863 }
4864
4865 fn merge_lazy(
4866 &mut self,
4867 buf: &'a [u8],
4868 ctx: crate::DecodeContext<'_>,
4869 ) -> Result<(), DecodeError> {
4870 let mut cursor: &'a [u8] = buf;
4871 while !cursor.is_empty() {
4872 let tag = crate::encoding::Tag::decode(&mut cursor)?;
4873 match tag.field_number() {
4874 1 => self.id = crate::types::decode_int32(&mut cursor)?,
4875 2 => self.name = crate::types::borrow_str(&mut cursor)?,
4876 _ => crate::encoding::skip_unknown_field(tag, &mut cursor, ctx)?,
4877 }
4878 }
4879 Ok(())
4880 }
4881
4882 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
4883 Ok(SimpleMessage {
4884 id: self.id,
4885 name: self.name.into(),
4886 })
4887 }
4888 }
4889
4890 #[test]
4891 fn deferred_children_preserve_rejection_separately_from_storage_exhaustion() {
4892 let allowance = core::cell::Cell::new(1);
4893 let ctx = crate::DecodeContext::new(8, &allowance);
4894 ctx.register_unknown_field().unwrap();
4895 assert_eq!(ctx.remaining_unknown_fields(), 0);
4896 assert!(!ctx.rejects_unknown_fields());
4897 let wire = &[0x18, 1][..]; // Unknown to SimpleLazyView.
4898 let mut singular = LazyMessageFieldView::<SimpleLazyView<'_>>::unset();
4899 singular.push_fragment(wire, ctx);
4900 assert!(singular.get().is_ok());
4901 assert!(singular.clone().get().is_ok());
4902 let mut repeated = LazyRepeatedView::<SimpleLazyView<'_>>::new();
4903 repeated.push_bytes(wire, ctx);
4904 assert!(repeated.get(0).unwrap().is_ok());
4905 assert!(repeated.clone().iter().next().unwrap().is_ok());
4906
4907 let allowance = core::cell::Cell::new(0);
4908 let strict = crate::DecodeContext::new(8, &allowance);
4909 let mut singular = LazyMessageFieldView::<SimpleLazyView<'_>>::unset();
4910 singular.push_fragment(wire, strict);
4911 assert_eq!(singular.get(), Err(DecodeError::UnknownFieldLimitExceeded));
4912 let mut repeated = LazyRepeatedView::<SimpleLazyView<'_>>::new();
4913 repeated.push_bytes(wire, strict);
4914 assert_eq!(
4915 repeated.get(0).unwrap(),
4916 Err(DecodeError::UnknownFieldLimitExceeded)
4917 );
4918 }
4919
4920 fn full_budget_ctx(cell: &core::cell::Cell<usize>) -> crate::DecodeContext<'_> {
4921 crate::DecodeContext::new(crate::RECURSION_LIMIT, cell)
4922 }
4923
4924 #[test]
4925 fn lazy_message_field_view_decodes_on_access() {
4926 let bytes = encode_simple(42, "lazy");
4927 let unset = LazyMessageFieldView::<SimpleLazyView<'_>>::unset();
4928 assert!(unset.is_unset());
4929 assert!(unset.fragments().is_empty());
4930 assert!(unset.get().unwrap().is_none());
4931 assert_eq!(unset.get_or_default().unwrap(), SimpleLazyView::default());
4932
4933 let lazy = LazyMessageFieldView::<SimpleLazyView<'_>>::from_bytes(&bytes);
4934 assert!(lazy.is_set());
4935 assert_eq!(lazy.fragments(), &[&bytes[..]]);
4936 let v = lazy.get().unwrap().expect("set");
4937 assert_eq!((v.id, v.name), (42, "lazy"));
4938 // Re-decodes each call (no cache).
4939 assert_eq!(lazy.get().unwrap().unwrap().id, 42);
4940 assert_eq!(v.to_owned_message().unwrap().name, "lazy");
4941 }
4942
4943 #[test]
4944 fn lazy_message_field_view_merges_fragments() {
4945 // A singular message field split across wire occurrences must merge:
4946 // fragment 1 sets `name`, fragment 2 sets `id`; the merged view has
4947 // both, matching the eager/owned decoders.
4948 let frag1 = encode_simple(0, "from-frag-1");
4949 let frag2 = encode_simple(7, "");
4950 let cell = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
4951
4952 let mut lazy = LazyMessageFieldView::<SimpleLazyView<'_>>::unset();
4953 lazy.push_fragment(&frag1, full_budget_ctx(&cell));
4954 assert_eq!(lazy.fragments().len(), 1);
4955 lazy.push_fragment(&frag2, full_budget_ctx(&cell));
4956 assert_eq!(lazy.fragments(), &[&frag1[..], &frag2[..]]);
4957
4958 let v = lazy.get().unwrap().expect("set");
4959 assert_eq!((v.id, v.name), (7, "from-frag-1"));
4960
4961 // Later fragments overwrite singular scalars (last-wins).
4962 let frag3 = encode_simple(9, "final");
4963 lazy.push_fragment(&frag3, full_budget_ctx(&cell));
4964 assert_eq!(lazy.fragments().len(), 3);
4965 let v = lazy.get().unwrap().expect("set");
4966 assert_eq!((v.id, v.name), (9, "final"));
4967 }
4968
4969 #[test]
4970 fn lazy_message_field_view_records_smallest_budgets() {
4971 // Budgets recorded across pushes are min-combined, and the recorded
4972 // allowance replays per access (capture-then-replay).
4973 let bytes = encode_simple(1, "x");
4974 let cell_big = core::cell::Cell::new(500);
4975 let cell_small = core::cell::Cell::new(3);
4976
4977 let mut lazy = LazyMessageFieldView::<SimpleLazyView<'_>>::unset();
4978 lazy.push_fragment(&bytes, crate::DecodeContext::new(80, &cell_big));
4979 lazy.push_fragment(&bytes, crate::DecodeContext::new(50, &cell_small));
4980 // Decoding succeeds — SimpleLazyView has no unknowns or nesting here;
4981 // the recorded budgets only bound what access may consume.
4982 assert!(lazy.get().unwrap().is_some());
4983 }
4984
4985 #[test]
4986 fn lazy_message_field_view_clone_default_debug() {
4987 let bytes = encode_simple(1, "x");
4988 let cell = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
4989 let mut lazy = LazyMessageFieldView::<SimpleLazyView<'_>>::default();
4990 assert!(lazy.is_unset());
4991 lazy.push_fragment(&bytes, full_budget_ctx(&cell));
4992 lazy.push_fragment(&bytes, full_budget_ctx(&cell));
4993 let cloned = lazy.clone();
4994 assert_eq!(cloned.fragments(), lazy.fragments());
4995 let dbg = alloc::format!("{lazy:?}");
4996 assert!(dbg.contains("is_set: true"), "{dbg}");
4997 assert!(dbg.contains("fragments: 2"), "{dbg}");
4998 }
4999
5000 #[test]
5001 fn lazy_message_field_view_malformed_errors_on_access() {
5002 // 0xFF starts a tag whose varint never terminates — invalid.
5003 let malformed = [0xFFu8; 3];
5004 let lazy = LazyMessageFieldView::<SimpleLazyView<'_>>::from_bytes(&malformed);
5005 // Deferred validation: construction succeeds, access fails.
5006 assert!(lazy.is_set());
5007 assert!(lazy.get().is_err());
5008 }
5009
5010 #[test]
5011 fn lazy_repeated_view_decodes_per_element() {
5012 let b0 = encode_simple(1, "a");
5013 let b1 = encode_simple(2, "b");
5014 let cell = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
5015 let mut rep = LazyRepeatedView::<SimpleLazyView<'_>>::new();
5016 assert!(rep.is_empty());
5017 rep.push_bytes(&b0, full_budget_ctx(&cell));
5018 rep.push_bytes(&b1, full_budget_ctx(&cell));
5019 assert_eq!(rep.len(), 2);
5020 assert_eq!(rep.raw_elements(), &[&b0[..], &b1[..]]);
5021 assert_eq!(rep.get(0).unwrap().unwrap().name, "a");
5022 assert_eq!(rep.get(1).unwrap().unwrap().id, 2);
5023 assert!(rep.get(2).is_none());
5024 }
5025
5026 #[test]
5027 fn lazy_repeated_view_iter() {
5028 let bufs: alloc::vec::Vec<Bytes> = (1..=3)
5029 .map(|i| encode_simple(i, core::str::from_utf8(&[b'a' + i as u8]).unwrap()))
5030 .collect();
5031 let cell = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
5032 let mut rep = LazyRepeatedView::<SimpleLazyView<'_>>::new();
5033 for b in &bufs {
5034 rep.push_bytes(b, full_budget_ctx(&cell));
5035 }
5036
5037 let iter = rep.iter();
5038 assert_eq!(iter.len(), 3);
5039 let ids: alloc::vec::Vec<i32> = iter.map(|r| r.unwrap().id).collect();
5040 assert_eq!(ids, [1, 2, 3]);
5041
5042 // IntoIterator for &LazyRepeatedView.
5043 let names: alloc::vec::Vec<&str> = (&rep).into_iter().map(|r| r.unwrap().name).collect();
5044 assert_eq!(names, ["b", "c", "d"]);
5045
5046 // DoubleEndedIterator.
5047 let rev_ids: alloc::vec::Vec<i32> = rep.iter().rev().map(|r| r.unwrap().id).collect();
5048 assert_eq!(rev_ids, [3, 2, 1]);
5049 }
5050
5051 #[test]
5052 fn lazy_repeated_view_iter_surfaces_element_errors() {
5053 let good = encode_simple(1, "ok");
5054 let malformed = [0xFFu8; 3];
5055 let cell = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
5056 let mut rep = LazyRepeatedView::<SimpleLazyView<'_>>::new();
5057 rep.push_bytes(&good, full_budget_ctx(&cell));
5058 rep.push_bytes(&malformed, full_budget_ctx(&cell));
5059 let results: alloc::vec::Vec<_> = rep.iter().collect();
5060 assert!(results[0].is_ok());
5061 assert!(results[1].is_err());
5062 let cloned = rep.clone();
5063 assert_eq!(cloned.len(), 2);
5064 }
5065
5066 #[cfg(feature = "std")]
5067 mod lazy_repeated_iter_tests {
5068 use super::*;
5069 use core::cell::Cell;
5070
5071 std::thread_local! {
5072 static DECODE_CALLS: Cell<usize> = const { Cell::new(0) };
5073 }
5074
5075 #[derive(Clone, Debug)]
5076 struct CountingLazyView<'a>(SimpleLazyView<'a>);
5077
5078 impl<'a> LazyMessageView<'a> for CountingLazyView<'a> {
5079 type Owned = SimpleMessage;
5080
5081 fn decode_lazy(buf: &'a [u8]) -> Result<Self, DecodeError> {
5082 DECODE_CALLS.with(|calls| calls.set(calls.get() + 1));
5083 SimpleLazyView::decode_lazy(buf).map(Self)
5084 }
5085
5086 fn decode_lazy_with_ctx(
5087 buf: &'a [u8],
5088 ctx: crate::DecodeContext<'_>,
5089 ) -> Result<Self, DecodeError> {
5090 DECODE_CALLS.with(|calls| calls.set(calls.get() + 1));
5091 SimpleLazyView::decode_lazy_with_ctx(buf, ctx).map(Self)
5092 }
5093
5094 fn merge_lazy(
5095 &mut self,
5096 buf: &'a [u8],
5097 ctx: crate::DecodeContext<'_>,
5098 ) -> Result<(), DecodeError> {
5099 self.0.merge_lazy(buf, ctx)
5100 }
5101
5102 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
5103 self.0.to_owned_message()
5104 }
5105 }
5106
5107 fn repeated(
5108 elements: &[&'static [u8]],
5109 ) -> LazyRepeatedView<'static, CountingLazyView<'static>> {
5110 DECODE_CALLS.with(|calls| calls.set(0));
5111 let cell = Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
5112 let mut rep = LazyRepeatedView::new();
5113 for &element in elements {
5114 rep.push_bytes(element, full_budget_ctx(&cell));
5115 }
5116 rep
5117 }
5118
5119 fn decode_calls() -> usize {
5120 DECODE_CALLS.with(Cell::get)
5121 }
5122
5123 #[test]
5124 fn nth_decodes_only_selected_elements() {
5125 let rep = repeated(&[b"\x08\x01", b"\x08\x02", b"\x08\x03", b"\x08\x04"]);
5126 let mut iter = rep.iter();
5127 assert_eq!(iter.nth(2).unwrap().unwrap().0.id, 3);
5128 assert_eq!(decode_calls(), 1);
5129 assert_eq!(iter.len(), 1);
5130 assert_eq!(iter.next().unwrap().unwrap().0.id, 4);
5131 assert_eq!(decode_calls(), 2);
5132 assert!(iter.next().is_none());
5133 assert_eq!(decode_calls(), 2);
5134 }
5135
5136 #[test]
5137 fn count_and_last_decode_at_most_one_element() {
5138 let rep = repeated(&[b"\x08\x01", b"\x08\x02", b"\x08\x03"]);
5139 assert_eq!(rep.iter().count(), 3);
5140 assert_eq!(decode_calls(), 0);
5141 assert_eq!(rep.iter().last().unwrap().unwrap().0.id, 3);
5142 assert_eq!(decode_calls(), 1);
5143 assert!(repeated(&[]).iter().last().is_none());
5144 assert_eq!(decode_calls(), 0);
5145 }
5146
5147 #[test]
5148 fn count_and_last_do_not_validate_skipped_elements() {
5149 let rep = repeated(&[b"\xff", b"\x08\x02"]);
5150 assert_eq!(rep.iter().count(), 2);
5151 assert_eq!(rep.iter().last().unwrap().unwrap().0.id, 2);
5152 assert_eq!(decode_calls(), 1);
5153 }
5154
5155 #[test]
5156 fn nth_back_decodes_only_selected_elements() {
5157 let rep = repeated(&[b"\x08\x01", b"\x08\x02", b"\x08\x03", b"\x08\x04"]);
5158 let mut iter = rep.iter();
5159 assert_eq!(iter.nth_back(2).unwrap().unwrap().0.id, 2);
5160 assert_eq!(decode_calls(), 1);
5161 assert_eq!(iter.len(), 1);
5162 assert_eq!(iter.next_back().unwrap().unwrap().0.id, 1);
5163 assert_eq!(decode_calls(), 2);
5164 assert!(iter.next_back().is_none());
5165 assert_eq!(decode_calls(), 2);
5166 }
5167
5168 #[test]
5169 fn out_of_range_skips_exhaust_without_decoding() {
5170 for elements in [
5171 &[][..],
5172 &[&b"\x08\x01"[..]][..],
5173 &[&b"\x08\x01"[..], &b"\x08\x02"[..]][..],
5174 ] {
5175 for n in [elements.len(), elements.len() + 1, usize::MAX] {
5176 for from_back in [false, true] {
5177 let rep = repeated(elements);
5178 let mut iter = rep.iter();
5179 let result = if from_back {
5180 iter.nth_back(n)
5181 } else {
5182 iter.nth(n)
5183 };
5184 assert!(result.is_none());
5185 assert_eq!(iter.len(), 0);
5186 assert_eq!(iter.size_hint(), (0, Some(0)));
5187 assert!(iter.next().is_none());
5188 assert!(iter.next_back().is_none());
5189 assert_eq!(decode_calls(), 0, "n={n}, from_back={from_back}");
5190 }
5191 }
5192 }
5193 }
5194
5195 #[test]
5196 fn skips_preserve_element_errors_and_remaining_items() {
5197 for from_back in [false, true] {
5198 let rep = repeated(&[b"\x08\x01", b"\xff", b"\x08\x03"]);
5199 let mut iter = rep.iter();
5200 let result = if from_back {
5201 iter.nth_back(1)
5202 } else {
5203 iter.nth(1)
5204 };
5205 assert_eq!(result.unwrap().unwrap_err(), DecodeError::UnexpectedEof);
5206 assert_eq!(decode_calls(), 1);
5207 assert_eq!(iter.len(), 1);
5208 let remaining = if from_back {
5209 iter.next_back()
5210 } else {
5211 iter.next()
5212 };
5213 assert_eq!(
5214 remaining.unwrap().unwrap().0.id,
5215 if from_back { 1 } else { 3 }
5216 );
5217 assert_eq!(decode_calls(), 2);
5218 }
5219
5220 let rep = repeated(&[b"\xff", b"\x08\x02", b"\xff"]);
5221 assert_eq!(rep.iter().nth(1).unwrap().unwrap().0.id, 2);
5222 assert_eq!(rep.iter().nth_back(1).unwrap().unwrap().0.id, 2);
5223 assert_eq!(decode_calls(), 2);
5224 }
5225
5226 #[test]
5227 #[allow(clippy::iter_nth_zero)]
5228 fn skips_mix_with_both_ends_and_clone() {
5229 let rep = repeated(&[
5230 b"\x08\x01",
5231 b"\x08\x02",
5232 b"\x08\x03",
5233 b"\x08\x04",
5234 b"\x08\x05",
5235 b"\x08\x06",
5236 ]);
5237 let mut iter = rep.iter();
5238 assert_eq!(iter.nth(1).unwrap().unwrap().0.id, 2);
5239 assert_eq!(iter.nth_back(1).unwrap().unwrap().0.id, 5);
5240 assert_eq!(iter.size_hint(), (2, Some(2)));
5241 assert_eq!(decode_calls(), 2);
5242 let mut cloned = iter.clone();
5243 assert_eq!(iter.nth(0).unwrap().unwrap().0.id, 3);
5244 assert_eq!(iter.nth_back(0).unwrap().unwrap().0.id, 4);
5245 assert!(iter.nth(0).is_none());
5246 assert_eq!(cloned.nth_back(0).unwrap().unwrap().0.id, 4);
5247 assert_eq!(cloned.nth(0).unwrap().unwrap().0.id, 3);
5248 assert!(cloned.nth_back(0).is_none());
5249 assert_eq!(decode_calls(), 6);
5250 }
5251
5252 #[test]
5253 fn skip_adapter_next_decodes_only_yielded_elements() {
5254 let rep = repeated(&[b"\xff", b"\xff", b"\x08\x03", b"\x08\x04"]);
5255 let mut iter = rep.iter().skip(2);
5256 assert_eq!(iter.next().unwrap().unwrap().0.id, 3);
5257 assert_eq!(iter.next().unwrap().unwrap().0.id, 4);
5258 assert!(iter.next().is_none());
5259 assert_eq!(decode_calls(), 2);
5260
5261 let rep = repeated(&[b"\x08\x01", b"\x08\x02", b"\xff", b"\xff"]);
5262 let mut iter = rep.iter().rev().skip(2);
5263 assert_eq!(iter.next().unwrap().unwrap().0.id, 2);
5264 assert_eq!(iter.next().unwrap().unwrap().0.id, 1);
5265 assert!(iter.next().is_none());
5266 assert_eq!(decode_calls(), 2);
5267 }
5268 }
5269
5270 // ── Encode-side 2 GiB guard tests ──────────────────────────────────
5271
5272 /// Test double whose `compute_size` reports a caller-chosen value and
5273 /// whose `write_to` writes nothing — exercises the over-limit paths
5274 /// without materializing gigabytes.
5275 #[derive(Clone, Debug, Default, PartialEq)]
5276 struct SizedView {
5277 reported_size: u32,
5278 }
5279
5280 impl<'a> MessageView<'a> for SizedView {
5281 type Owned = SimpleMessage;
5282 fn merge_view_field(
5283 &mut self,
5284 _tag: crate::encoding::Tag,
5285 cur: &'a [u8],
5286 _before_tag: &'a [u8],
5287 _ctx: crate::DecodeContext<'_>,
5288 ) -> Result<&'a [u8], DecodeError> {
5289 Ok(cur)
5290 }
5291 fn decode_view(_buf: &'a [u8]) -> Result<Self, DecodeError> {
5292 Ok(Self::default())
5293 }
5294 fn to_owned_message(&self) -> Result<SimpleMessage, DecodeError> {
5295 Ok(SimpleMessage::default())
5296 }
5297 }
5298
5299 impl<'a> ViewEncode<'a> for SizedView {
5300 fn compute_size(&self, _cache: &mut crate::SizeCache) -> u32 {
5301 self.reported_size
5302 }
5303 fn write_to(&self, _cache: &mut crate::SizeCache, _buf: &mut impl EncodeSink) {}
5304 }
5305
5306 const OVER_LIMIT: u32 = crate::MAX_MESSAGE_BYTES + 1;
5307
5308 /// View double over the shared [`SizedMsg`](crate::test_doubles::SizedMsg)
5309 /// owned double, so `OwnedView::from_owned` can hit the over-limit
5310 /// encode path without materializing gigabytes.
5311 #[derive(Clone, Debug, Default, PartialEq)]
5312 struct SizedOwnedView;
5313
5314 impl ViewReborrow for SizedOwnedView {
5315 type Reborrowed<'b> = Self;
5316 fn reborrow(this: &Self) -> &Self {
5317 this
5318 }
5319 }
5320
5321 // SAFETY: a unit struct — it holds no borrows from the buffer at all.
5322 unsafe impl ViewLifetimeParametric for SizedOwnedView {}
5323
5324 impl<'a> MessageView<'a> for SizedOwnedView {
5325 type Owned = crate::test_doubles::SizedMsg;
5326 fn merge_view_field(
5327 &mut self,
5328 _tag: crate::encoding::Tag,
5329 cur: &'a [u8],
5330 _before_tag: &'a [u8],
5331 _ctx: crate::DecodeContext<'_>,
5332 ) -> Result<&'a [u8], DecodeError> {
5333 Ok(cur)
5334 }
5335 fn decode_view(_buf: &'a [u8]) -> Result<Self, DecodeError> {
5336 Ok(Self)
5337 }
5338 fn to_owned_message(&self) -> Result<crate::test_doubles::SizedMsg, DecodeError> {
5339 Ok(crate::test_doubles::SizedMsg::default())
5340 }
5341 }
5342
5343 #[test]
5344 fn owned_view_from_owned_over_limit_errs_not_panics() {
5345 // from_owned is a Result-returning API: an over-limit message must
5346 // surface as Err(MessageTooLarge), never a panic from the interior
5347 // encode.
5348 let msg = crate::test_doubles::SizedMsg {
5349 reported_size: OVER_LIMIT,
5350 };
5351 let res = OwnedView::<SizedOwnedView>::from_owned(&msg);
5352 assert!(matches!(res, Err(DecodeError::MessageTooLarge)));
5353 }
5354
5355 #[test]
5356 #[should_panic(expected = "2 GiB protobuf limit")]
5357 fn view_encode_over_limit_panics() {
5358 let view = SizedView {
5359 reported_size: OVER_LIMIT,
5360 };
5361 let mut buf = alloc::vec::Vec::new();
5362 view.encode(&mut buf);
5363 }
5364
5365 #[test]
5366 #[should_panic(expected = "2 GiB protobuf limit")]
5367 fn view_encoded_len_over_limit_panics() {
5368 let view = SizedView {
5369 reported_size: OVER_LIMIT,
5370 };
5371 let _ = view.encoded_len();
5372 }
5373
5374 #[test]
5375 #[should_panic(expected = "2 GiB protobuf limit")]
5376 fn view_encode_length_delimited_over_limit_panics() {
5377 let view = SizedView {
5378 reported_size: OVER_LIMIT,
5379 };
5380 let mut buf = alloc::vec::Vec::new();
5381 view.encode_length_delimited(&mut buf);
5382 }
5383
5384 #[test]
5385 #[should_panic(expected = "2 GiB protobuf limit")]
5386 fn view_encode_to_vec_over_limit_panics() {
5387 let view = SizedView {
5388 reported_size: OVER_LIMIT,
5389 };
5390 let _ = view.encode_to_vec();
5391 }
5392
5393 #[test]
5394 #[should_panic(expected = "2 GiB protobuf limit")]
5395 fn view_encode_to_bytes_over_limit_panics() {
5396 let view = SizedView {
5397 reported_size: OVER_LIMIT,
5398 };
5399 let _ = view.encode_to_bytes();
5400 }
5401
5402 #[test]
5403 #[should_panic(expected = "2 GiB protobuf limit")]
5404 fn view_encode_with_cache_over_limit_panics() {
5405 let view = SizedView {
5406 reported_size: OVER_LIMIT,
5407 };
5408 let mut cache = crate::SizeCache::new();
5409 let mut buf = alloc::vec::Vec::new();
5410 view.encode_with_cache(&mut cache, &mut buf);
5411 }
5412
5413 #[cfg(debug_assertions)]
5414 #[test]
5415 #[should_panic(expected = "two-pass traversal mismatch")]
5416 fn view_encode_to_vec_ledger_catches_size_write_disagreement() {
5417 // An under-limit reported size with a no-op write_to: the guard
5418 // passes, then the debug ledger flags the two-pass divergence.
5419 let view = SizedView { reported_size: 3 };
5420 let _ = view.encode_to_vec();
5421 }
5422
5423 #[test]
5424 fn view_try_encode_over_limit_errors_and_writes_nothing() {
5425 let view = SizedView {
5426 reported_size: OVER_LIMIT,
5427 };
5428 let mut buf = alloc::vec::Vec::new();
5429 assert_eq!(
5430 view.try_encode(&mut buf),
5431 Err(crate::EncodeError::MessageTooLarge)
5432 );
5433 assert!(buf.is_empty(), "no bytes may reach the buffer on Err");
5434 let mut cache = crate::SizeCache::new();
5435 assert_eq!(
5436 view.try_encode_with_cache(&mut cache, &mut buf),
5437 Err(crate::EncodeError::MessageTooLarge)
5438 );
5439 assert!(buf.is_empty(), "no bytes may reach the buffer on Err");
5440 assert_eq!(
5441 view.try_encode_length_delimited(&mut buf),
5442 Err(crate::EncodeError::MessageTooLarge)
5443 );
5444 assert!(buf.is_empty(), "not even the length prefix");
5445 assert_eq!(
5446 view.try_encode_to_vec(),
5447 Err(crate::EncodeError::MessageTooLarge)
5448 );
5449 assert_eq!(
5450 view.try_encode_to_bytes(),
5451 Err(crate::EncodeError::MessageTooLarge)
5452 );
5453 assert_eq!(
5454 view.try_encoded_len(),
5455 Err(crate::EncodeError::MessageTooLarge)
5456 );
5457 }
5458
5459 #[test]
5460 fn view_try_encode_matches_encode_for_normal_views() {
5461 let view = SimpleMessageView {
5462 id: 42,
5463 name: "hello",
5464 };
5465 let mut expected = alloc::vec::Vec::new();
5466 view.encode(&mut expected);
5467 let mut actual = alloc::vec::Vec::new();
5468 view.try_encode(&mut actual).unwrap();
5469 assert_eq!(actual, expected);
5470 assert_eq!(view.try_encode_to_vec().unwrap(), expected);
5471 assert_eq!(view.try_encode_to_bytes().unwrap(), expected);
5472 assert_eq!(view.try_encoded_len().unwrap(), expected.len() as u32);
5473 }
5474
5475 #[test]
5476 fn view_try_encode_bounded_within_budget_encodes_and_returns_len() {
5477 let view = SimpleMessageView {
5478 id: 42,
5479 name: "hello",
5480 };
5481 let mut expected = alloc::vec::Vec::new();
5482 view.encode(&mut expected);
5483 let budget = expected.len() as u32;
5484
5485 let mut buf = alloc::vec::Vec::new();
5486 let len = view.try_encode_bounded(budget, &mut buf).unwrap();
5487 assert_eq!(buf, expected);
5488 assert_eq!(len, budget);
5489
5490 // with_cache variant agrees
5491 let mut cache = crate::SizeCache::new();
5492 let mut buf2 = alloc::vec::Vec::new();
5493 let len2 = view
5494 .try_encode_bounded_with_cache(budget, &mut cache, &mut buf2)
5495 .unwrap();
5496 assert_eq!(buf2, expected);
5497 assert_eq!(len2, budget);
5498 }
5499
5500 #[test]
5501 fn view_try_encode_bounded_over_budget_errors_and_writes_nothing() {
5502 let view = SimpleMessageView {
5503 id: 42,
5504 name: "hello",
5505 };
5506 let len = view.encoded_len();
5507 let budget = len - 1;
5508
5509 let mut buf = alloc::vec::Vec::new();
5510 assert_eq!(
5511 view.try_encode_bounded(budget, &mut buf),
5512 Err(crate::EncodeError::ExceedsBudget {
5513 len,
5514 max_bytes: budget
5515 })
5516 );
5517 assert!(buf.is_empty(), "nothing written on budget exceeded");
5518 }
5519
5520 #[test]
5521 fn view_try_encode_bounded_over_protobuf_limit_errors_as_too_large() {
5522 let view = SizedView {
5523 reported_size: OVER_LIMIT,
5524 };
5525 let mut buf = alloc::vec::Vec::new();
5526 assert_eq!(
5527 view.try_encode_bounded(u32::MAX, &mut buf),
5528 Err(crate::EncodeError::MessageTooLarge)
5529 );
5530 assert!(buf.is_empty());
5531 }
5532
5533 #[test]
5534 fn pool_try_encode_view_bounded_within_budget_encodes_and_returns_len() {
5535 let view = SimpleMessageView {
5536 id: 7,
5537 name: "pooled",
5538 };
5539 let mut expected = alloc::vec::Vec::new();
5540 view.encode(&mut expected);
5541 let budget = expected.len() as u32;
5542
5543 let mut pool = crate::SizeCachePool::sequential(64);
5544 let mut buf = alloc::vec::Vec::new();
5545 let len = pool
5546 .try_encode_view_bounded(&view, budget, &mut buf)
5547 .unwrap();
5548 assert_eq!(buf, expected);
5549 assert_eq!(len, budget);
5550 }
5551
5552 #[test]
5553 fn pool_try_encode_view_bounded_over_budget_errors_and_buffer_returned() {
5554 let view = SimpleMessageView {
5555 id: 7,
5556 name: "pooled",
5557 };
5558 let len = view.encoded_len();
5559 let budget = len - 1;
5560
5561 let mut pool = crate::SizeCachePool::sequential(64);
5562 let mut buf = alloc::vec::Vec::new();
5563 assert_eq!(
5564 pool.try_encode_view_bounded(&view, budget, &mut buf),
5565 Err(crate::EncodeError::ExceedsBudget {
5566 len,
5567 max_bytes: budget
5568 })
5569 );
5570 assert!(buf.is_empty());
5571 // Pool buffer must be returned on Err — a subsequent call must succeed.
5572 assert_eq!(
5573 pool.try_encode_view_bounded(&view, len, &mut buf).unwrap(),
5574 len
5575 );
5576 }
5577}
5578
5579#[cfg(test)]
5580mod unknown_fields_view_repr {
5581 use super::UnknownFieldsView;
5582
5583 // Every generated view embeds this by value, so it must stay pointer-sized
5584 // and hold no inline heap owner; otherwise views regress to being moved by
5585 // out-of-line `memcpy` rather than inline vector stores.
5586 #[test]
5587 fn handle_is_pointer_sized() {
5588 assert_eq!(
5589 core::mem::size_of::<UnknownFieldsView<'_>>(),
5590 core::mem::size_of::<usize>()
5591 );
5592 }
5593
5594 // `UnknownFieldsView` is reachable from every generated view, so it is part
5595 // of the public surface downstream code puts in its own types.
5596 #[test]
5597 fn is_send_and_sync() {
5598 fn assert_send<T: Send>() {}
5599 fn assert_sync<T: Sync>() {}
5600 assert_send::<UnknownFieldsView<'_>>();
5601 assert_sync::<UnknownFieldsView<'_>>();
5602 }
5603
5604 // The manual `Debug` impl exists to keep `last_tail` — which runs to the end
5605 // of the input buffer — out of the output, while still showing the records.
5606 #[test]
5607 fn debug_shows_records_and_hides_the_coalescing_cursor() {
5608 let mut ufv = UnknownFieldsView::new();
5609 assert!(format!("{ufv:?}").contains("records: []"));
5610
5611 ufv.push_raw(&[0x08, 0x2a]);
5612 let rendered = format!("{ufv:?}");
5613 assert!(rendered.contains("records: [Borrowed("), "{rendered}");
5614 assert!(!rendered.contains("last_tail"), "{rendered}");
5615 }
5616}
5617
5618#[cfg(feature = "zeroize")]
5619pub(crate) mod guarded;