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