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