Skip to main content

nros_serdes/
size.rs

1//! A message's serialized size, computed instead of guessed.
2//!
3//! `NROS_EXECUTOR_SUBSCRIPTION_BUFFER_BYTES` defaults to 1024 bytes and is a GUESS.
4//! Nothing checks it against the messages an image actually subscribes to, so a
5//! sample that does not fit is dropped AFTER the transport ACKed it, and
6//! `report_dropped_take` can only say "raise the knob" because the runtime does
7//! not know what value would have worked. On a target that knob is static RAM
8//! nobody can spare. This module is the calculator.
9//!
10//! # Why this is not a vtable slot
11//!
12//! Nothing about a size bound varies by backend, and
13//! upstream proves it by not varying at all — both `librmw_cyclonedds_cpp.so`
14//! and `librmw_fastrtps_cpp.so` answer `rmw_get_serialized_message_size` with
15//! `RMW_RET_UNSUPPORTED`, and nothing in a Humble install calls it. Upstream can
16//! afford that because its serialized buffer RESIZES; the bound is a hint that
17//! saves a realloc. Ours cannot resize, so the same number is load-bearing here.
18//!
19//! # Thread the offset — do not sum the maxima
20//!
21//! Padding is a function of WHERE a field starts, so a calculation that sums
22//! per-field maxima is wrong the moment a variable-length field shifts what
23//! follows. [`size_bound`] therefore takes `current_alignment` in and returns
24//! the size from there, which is also what makes nested structs compose with no
25//! special case — the same signature rosidl's generated Fast-RTPS support uses
26//! (`max_serialized_size_T(full_bounded, is_plain, current_alignment)`).
27//!
28//! # Agreement with the writer is the only thing that matters
29//!
30//! Every rule below was read out of `CdrWriter`, not out of the CDR spec:
31//! `align()` caps alignment at 4 under XCDR2 and honours 8 under XCDR1;
32//! `begin_dheader()` aligns to 4 and reserves 4 bytes for EVERY struct under
33//! XCDR2 (a generated `serialize` opens with it, so nested structs get one too);
34//! `write_string` writes `len + 1` and then the NUL. A bound that merely looks
35//! right is worthless — see `size_tests.rs`, which checks it against the bytes
36//! the writer actually produced.
37
38use core::ops::ControlFlow;
39
40use crate::{
41    cdr::EncodingVersion,
42    schema::{Field, FieldType},
43};
44
45/// What one walk of a schema can say about size.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct SizeBound {
48    /// Bytes, given the starting offset the walk was handed.
49    pub bytes: usize,
50    /// False once an unbounded `String` / `WString` / `Sequence` is reached —
51    /// `bytes` is then a FLOOR, not a bound, and callers must not size a buffer
52    /// from it.
53    pub bounded: bool,
54    /// No variable-length member anywhere, so the WIRE length is fixed: `bytes`
55    /// is EXACT rather than an upper bound.
56    ///
57    /// **Nothing dispatches on this, by decision**. It is
58    /// the walk's exactness property, asserted as such by
59    /// `plain_struct_bound_is_exact` here and by
60    /// `bound_holds_against_the_writer_for_every_generated_type` over the whole
61    /// generated corpus, and it is surfaced as
62    /// [`crate::schema::Message::IS_PLAIN`] / [`is_loan_eligible`] so there is
63    /// ONE definition of "fixed layout" for whoever finally needs one.
64    ///
65    /// The earlier text here said this "wires to
66    /// `borrow_loaned_message` / `subscription_supports_in_place`". It does not:
67    /// the definition shipped and the wiring was left to whoever owns those
68    /// slots, and **the wiring waits** — deliberately, since the loan surface
69    /// measures as a cost on three of four backends and
70    /// the natural consumer of this predicate is Cyclone-with-iceoryx, which no
71    /// target we ship can reach. Do not gate the in-place path on it: that path
72    /// hands the callback raw CDR to deserialize, which needs no fixed layout, so
73    /// the flag would only take it away from every type with a `String`.
74    ///
75    /// It is NOT "POD-blit eligible", and a second flag under that name in the
76    /// codegen IR was deleted for disagreeing with this one on
77    /// `bool`, on nested all-`float64` structs and on mixed alignment. Nor does
78    /// it make the bound version-INDEPENDENT: XCDR2's DHEADER is fixed-width, so
79    /// a plain type stays plain while its bound still differs per encoding
80    /// (`Time` measures 12 under XCDR1 and 16 under XCDR2).
81    pub plain: bool,
82}
83
84/// The encapsulation header the payload crossing our vtable carries: 2 bytes of
85/// representation id + 2 of options.
86///
87/// TOP LEVEL ONLY, not per nested struct — which is why the Cyclone backend
88/// computes `total = paylen + 4`. [`size_bound`] deliberately does not include
89/// it; [`max_serialized_size`] does.
90pub const ENCAPSULATION_HEADER_BYTES: usize = 4;
91
92/// Padding needed to reach `alignment` from `offset`, under `version`.
93///
94/// Mirrors `CdrWriter::align` exactly, including the XCDR2 cap at 4 — a message
95/// containing an `int64` therefore has TWO different bounds, and a single
96/// constant would be silently wrong for one encoding.
97const fn pad_to(offset: usize, alignment: usize, version: EncodingVersion) -> usize {
98    let alignment = match version {
99        EncodingVersion::Xcdr2 => {
100            if alignment > 4 {
101                4
102            } else {
103                alignment
104            }
105        }
106        EncodingVersion::Xcdr1 => alignment,
107    };
108    if alignment == 0 {
109        return 0;
110    }
111    (alignment - (offset % alignment)) % alignment
112}
113
114/// Size of one field, starting at `offset`. Returns the new offset plus the two
115/// flags, folded by the caller.
116const fn field_bound(
117    ty: &FieldType,
118    version: EncodingVersion,
119    offset: usize,
120) -> (usize, bool, bool) {
121    match ty {
122        FieldType::Bool | FieldType::Uint8 | FieldType::Int8 => (offset + 1, true, true),
123        FieldType::Uint16 | FieldType::Int16 => {
124            let o = offset + pad_to(offset, 2, version);
125            (o + 2, true, true)
126        }
127        FieldType::Uint32 | FieldType::Int32 | FieldType::Float32 => {
128            let o = offset + pad_to(offset, 4, version);
129            (o + 4, true, true)
130        }
131        FieldType::Uint64 | FieldType::Int64 | FieldType::Float64 => {
132            let o = offset + pad_to(offset, 8, version);
133            (o + 8, true, true)
134        }
135        // `write_string` writes `len + 1` as the u32 prefix and then the NUL,
136        // so a bound of `n` payload bytes costs `4 + n + 1`.
137        FieldType::BoundedString(n) => {
138            let o = offset + pad_to(offset, 4, version);
139            (o + 4 + *n + 1, true, false)
140        }
141        FieldType::BoundedWString(n) => {
142            let o = offset + pad_to(offset, 4, version);
143            (o + 4 + 2 * *n, true, false)
144        }
145        // No bound exists. Account the length prefix so `bytes` is an honest
146        // floor, and clear `bounded` so nobody sizes a buffer from it.
147        FieldType::String | FieldType::WString | FieldType::Sequence(_) => {
148            let o = offset + pad_to(offset, 4, version);
149            (o + 4, false, false)
150        }
151        FieldType::Array(n, inner) => {
152            let mut o = offset;
153            let mut bounded = true;
154            let mut plain = true;
155            let mut i = 0;
156            while i < *n {
157                let (next, b, p) = field_bound(inner, version, o);
158                o = next;
159                bounded &= b;
160                plain &= p;
161                i += 1;
162            }
163            // A fixed array of plain elements is itself plain; of anything else,
164            // not — the element count is fixed but each element's size is not.
165            (o, bounded, plain)
166        }
167        FieldType::BoundedSequence(n, inner) => {
168            let mut o = offset + pad_to(offset, 4, version);
169            o += 4;
170            let mut bounded = true;
171            let mut i = 0;
172            while i < *n {
173                let (next, b, _) = field_bound(inner, version, o);
174                o = next;
175                bounded &= b;
176                i += 1;
177            }
178            // Never plain: the wire length varies with the actual element count
179            // even though its maximum is known.
180            (o, bounded, false)
181        }
182        FieldType::Nested(nested) => {
183            let inner = size_bound(nested.fields, version, offset);
184            (inner.bytes, inner.bounded, inner.plain)
185        }
186    }
187}
188
189/// Walk `fields` from `current_alignment`, returning the size bound of the
190/// struct they describe.
191///
192/// The returned `bytes` is an ABSOLUTE offset — the position after the last
193/// field, measured from the same origin `current_alignment` was measured from —
194/// so a nested struct composes by being handed the parent's current offset.
195/// Subtract the starting offset if a length is what you want.
196///
197/// Excludes the encapsulation header; see [`max_serialized_size`].
198pub const fn size_bound(
199    fields: &'static [Field],
200    version: EncodingVersion,
201    current_alignment: usize,
202) -> SizeBound {
203    let mut offset = current_alignment;
204    let mut bounded = true;
205    let mut plain = true;
206
207    // XCDR2 delimits EVERY appendable struct, nested ones included: a generated
208    // `serialize` opens with `begin_dheader()`, which aligns to 4 and reserves
209    // 4. Under XCDR1 the call is a no-op. Missing this UNDER-reports, which is
210    // the dangerous direction — an under-reported bound sizes a buffer too
211    // small and reintroduces the very drop this exists to stop.
212    if matches!(version, EncodingVersion::Xcdr2) {
213        offset += pad_to(offset, 4, version);
214        offset += 4;
215        // A DHEADER does not make a struct non-plain: its width is fixed.
216    }
217
218    let mut i = 0;
219    while i < fields.len() {
220        let (next, b, p) = field_bound(&fields[i].ty, version, offset);
221        offset = next;
222        bounded &= b;
223        plain &= p;
224        i += 1;
225    }
226
227    SizeBound {
228        bytes: offset,
229        bounded,
230        plain,
231    }
232}
233
234/// How deep a field path [`first_unbounded`] will name before it stops.
235///
236/// ROS message nesting is shallow in practice (`PoseStamped.header.stamp.sec`
237/// is three), and this walk runs on `no_std` with no allocator, so the path is
238/// a fixed array rather than a `Vec`. A deeper type still reports — the path is
239/// simply truncated, and [`UnboundedField::truncated`] says so, because a path
240/// that silently stops short would point at the wrong member.
241pub const MAX_FIELD_PATH_DEPTH: usize = 8;
242
243/// Which unbounded member kind was reached.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum UnboundedKind {
246    /// `string` with no IDL bound.
247    String,
248    /// `wstring` with no IDL bound.
249    WString,
250    /// `sequence<T>` with no IDL bound.
251    Sequence,
252}
253
254impl UnboundedKind {
255    /// The IDL spelling, for a diagnostic.
256    pub const fn as_str(self) -> &'static str {
257        match self {
258            UnboundedKind::String => "string",
259            UnboundedKind::WString => "wstring",
260            UnboundedKind::Sequence => "sequence<T>",
261        }
262    }
263}
264
265/// The first member that makes a type unbounded, named.
266///
267/// [`max_serialized_size`] answers `None`, which is honest and useless on its
268/// own: a user told their type has no bound cannot act without knowing WHICH
269/// member costs it, and the offender is routinely three structs down in a type
270/// they did not write. This is that answer.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub struct UnboundedField {
273    /// Field names from the root outward; only `depth` entries are meaningful.
274    pub path: [&'static str; MAX_FIELD_PATH_DEPTH],
275    /// How many entries of `path` are set.
276    pub depth: usize,
277    /// True when nesting exceeded [`MAX_FIELD_PATH_DEPTH`] and `path` names a
278    /// prefix rather than the whole route.
279    pub truncated: bool,
280    /// What kind of member it is.
281    pub kind: UnboundedKind,
282}
283
284impl core::fmt::Display for UnboundedField {
285    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
286        for (i, seg) in self.path.iter().take(self.depth).enumerate() {
287            if i > 0 {
288                f.write_str(".")?;
289            }
290            f.write_str(seg)?;
291        }
292        if self.truncated {
293            f.write_str(".…")?;
294        }
295        write!(f, " ({})", self.kind.as_str())
296    }
297}
298
299/// Report EVERY member that makes `fields` unbounded, in declaration order.
300///
301/// [`first_unbounded`] answers "which member costs the bound" one member at a
302/// time, and that is the wrong shape for the caller that actually asks.
303/// An unbounded type is a BUILD ERROR, and a stock ROS type is
304/// routinely unbounded in several places at once — `nav_msgs/Odometry` has
305/// `header.frame_id` and `child_frame_id`, and `sensor_msgs/PointCloud2` has
306/// four. Naming only the first turns "bound your types" into cap, rebuild,
307/// discover the next one, repeat, once per member, with a whole codegen run
308/// between each step. One build should name everything that needs a bound.
309///
310/// THE walk. [`first_unbounded`] is expressed on top of this rather than beside
311/// it: two walks of one schema is the shape the sizes-header mirror defect keeps
312/// taking, and "the first thing this reports" is exactly
313/// what "the first unbounded member" means, so there is nothing left for a
314/// second implementation to say.
315///
316/// `visit` returns [`ControlFlow`] so a caller that wants only the first can
317/// stop the walk rather than let it enumerate a whole type and discard all but
318/// one answer. The return value is `Break` iff the visitor broke.
319///
320/// `&mut dyn FnMut` rather than `impl FnMut`: the walk recurses, and a recursive
321/// generic function cannot name the closure type it would instantiate itself
322/// with. `no_std` and allocation-free either way — nothing is collected here,
323/// which is what lets an all-members form exist at all on a target with no
324/// allocator. The COLLECTING is the caller's, and only codegen (`std`) does it.
325pub fn visit_unbounded(
326    fields: &'static [Field],
327    visit: &mut dyn FnMut(UnboundedField) -> ControlFlow<()>,
328) -> ControlFlow<()> {
329    fn walk(
330        fields: &'static [Field],
331        prefix: &mut [&'static str; MAX_FIELD_PATH_DEPTH],
332        depth: usize,
333        visit: &mut dyn FnMut(UnboundedField) -> ControlFlow<()>,
334    ) -> ControlFlow<()> {
335        for field in fields {
336            let truncated = depth >= MAX_FIELD_PATH_DEPTH;
337            if !truncated {
338                prefix[depth] = field.name;
339            }
340            let here = |kind: UnboundedKind| UnboundedField {
341                path: *prefix,
342                depth: if truncated {
343                    MAX_FIELD_PATH_DEPTH
344                } else {
345                    depth + 1
346                },
347                truncated,
348                kind,
349            };
350            match &field.ty {
351                FieldType::String => visit(here(UnboundedKind::String))?,
352                FieldType::WString => visit(here(UnboundedKind::WString))?,
353                FieldType::Sequence(_) => visit(here(UnboundedKind::Sequence))?,
354                // A fixed array or a bounded sequence is bounded only if its
355                // ELEMENT is, and the element can itself be an unbounded
356                // string — `string[4]` has no bound. The element carries no
357                // name of its own, so it reports at the field's own path, and
358                // ONCE: several offenders inside one unnamed element would all
359                // print the same path, which reads as a repeated line rather
360                // than as more information.
361                FieldType::Array(_, inner) | FieldType::BoundedSequence(_, inner) => {
362                    if let Some(kind) = element_unbounded(inner) {
363                        visit(here(kind))?;
364                    }
365                }
366                FieldType::Nested(nested) => {
367                    if truncated {
368                        // Cannot record another segment; report the deepest
369                        // path we can name rather than descending silently.
370                        walk(nested.fields, prefix, depth, &mut |mut u| {
371                            u.truncated = true;
372                            visit(u)
373                        })?;
374                    } else {
375                        walk(nested.fields, prefix, depth + 1, visit)?;
376                    }
377                }
378                _ => {}
379            }
380        }
381        ControlFlow::Continue(())
382    }
383
384    /// An element type is not a field, so it has no name — report only its kind.
385    fn element_unbounded(ty: &'static FieldType) -> Option<UnboundedKind> {
386        match ty {
387            FieldType::String => Some(UnboundedKind::String),
388            FieldType::WString => Some(UnboundedKind::WString),
389            FieldType::Sequence(_) => Some(UnboundedKind::Sequence),
390            FieldType::Array(_, inner) | FieldType::BoundedSequence(_, inner) => {
391                element_unbounded(inner)
392            }
393            FieldType::Nested(nested) => {
394                // A nested struct inside an array: any unbounded member counts.
395                first_unbounded(nested.fields).map(|u| u.kind)
396            }
397            _ => None,
398        }
399    }
400
401    let mut prefix = [""; MAX_FIELD_PATH_DEPTH];
402    walk(fields, &mut prefix, 0, visit)
403}
404
405/// Find the first member that makes `fields` unbounded, if any.
406///
407/// Returns `None` exactly when [`size_bound`] reports `bounded` — the two walk
408/// the same schema by the same rules, so a type that has a bound has no
409/// offender to name and vice versa. That agreement is asserted by test, not
410/// assumed: two walks of one schema is the shape the sizes-header mirror defect
411/// keeps taking, so the second one exists only because it
412/// answers a question the first cannot (WHICH member) and must be checked
413/// against it.
414///
415/// The walk is [`visit_unbounded`]; this is its "stop at the first one" caller.
416/// Reach for [`visit_unbounded`] when the diagnostic should name every member a
417/// user has to fix, which is what codegen wants now that an unbounded type is a
418/// build error.
419///
420/// Not `const`: it recurses through `&'static NestedType`, and the array
421/// bookkeeping is not worth expressing in a const walk when every caller is a
422/// diagnostic path.
423pub fn first_unbounded(fields: &'static [Field]) -> Option<UnboundedField> {
424    let mut found = None;
425    let _ = visit_unbounded(fields, &mut |u| {
426        found = Some(u);
427        ControlFlow::Break(())
428    });
429    found
430}
431
432/// The whole payload a publisher hands the transport: encapsulation header plus
433/// the struct's body, starting from offset 0.
434///
435/// `None` when the type is unbounded — the honest answer, and the one that keeps
436/// a caller from sizing a buffer off a floor. Reach for `serialized_size(&self)`
437/// when an unbounded type still needs a number for THIS message.
438pub const fn max_serialized_size(
439    fields: &'static [Field],
440    version: EncodingVersion,
441) -> Option<usize> {
442    // The body's offsets are measured from after the encapsulation header —
443    // that is where `CdrWriter`'s `origin` sits — so the walk starts at 0 and
444    // the header is added once, at the top.
445    let bound = size_bound(fields, version, 0);
446    if bound.bounded {
447        Some(ENCAPSULATION_HEADER_BYTES + bound.bytes)
448    } else {
449        None
450    }
451}
452
453/// The EXACT serialized size of THIS message.
454///
455/// Two questions get asked about size and they are not the same one:
456///
457/// | question | asked by | this module |
458/// | --- | --- | --- |
459/// | how large can this TYPE ever be? | build-time buffer sizing | [`max_serialized_size`] |
460/// | how large is THIS message? | a publisher before publishing; a drop report | `serialized_size` |
461///
462/// The second is the only honest answer for an unbounded type, where the first
463/// is `None` — a `String` field has no maximum, but the string in hand has a
464/// length. It is what lets a drop report name the number that would have worked
465/// instead of saying "raise the knob".
466///
467/// Exact by construction: it runs the REAL writer with its stores disabled
468/// (`CdrWriter::measuring`), so the count comes from the same code that emits
469/// the bytes. A second walk of the schema could not see the actual string
470/// lengths and sequence counts, and would be a second implementation to keep in
471/// step besides.
472///
473/// Includes the encapsulation header, matching [`max_serialized_size`], so the
474/// two are directly comparable — which is the whole point at a call site
475/// deciding whether a message fits.
476pub fn serialized_size<T: crate::traits::Serialize>(
477    value: &T,
478    version: EncodingVersion,
479) -> Result<usize, crate::error::SerError> {
480    let mut w = crate::cdr::CdrWriter::measuring(&mut [], version);
481    value.serialize(&mut w)?;
482    Ok(ENCAPSULATION_HEADER_BYTES + w.position())
483}
484
485/// Does a receive buffer of `rx_buf` bytes fit every message of
486/// this type?
487///
488/// `true` when the type is bounded and the bound fits. **`false` when the type
489/// is UNBOUNDED**, deliberately: no finite buffer fits a `String`, so the
490/// honest answer to "is this guaranteed to fit" is no. A caller that wants
491/// "fits unless proven otherwise" is asking a different question and should
492/// look at [`serialized_size`] per message.
493///
494/// Const, so a call site can put it in a `const { assert!(...) }` and turn a
495/// runtime drop into a build error:
496///
497/// ```ignore
498/// const { assert!(buffer_fits::<Odometry>(RX_BUF, EncodingVersion::Xcdr1)) };
499/// ```
500///
501/// # Why this is not simply a bound on `Subscription`
502///
503/// `Subscription<M, RX_BUF>` bounds `M: RosMessage`, which is a DIFFERENT trait
504/// from [`crate::schema::Message`] — and measured 2026-08-26, hand-written
505/// `RosMessage` types with no schema DO exist (`nros-core/src/service.rs`, the
506/// component-runtime tests). Tightening that bound would break them, so the
507/// assertion is opt-in at sites where the schema is known rather than universal
508/// at a site where it is not. See the phase doc for what closing that gap needs.
509pub const fn buffer_fits<M: crate::schema::Message>(
510    rx_buf: usize,
511    version: EncodingVersion,
512) -> bool {
513    let bound = match version {
514        EncodingVersion::Xcdr1 => M::MAX_SERIALIZED_SIZE_XCDR1,
515        EncodingVersion::Xcdr2 => M::MAX_SERIALIZED_SIZE_XCDR2,
516    };
517    match bound {
518        Some(n) => rx_buf >= n,
519        None => false,
520    }
521}
522
523/// The type's own receive-buffer bound, or `None` when it has
524/// none.
525///
526/// The VALUE behind [`bound_fits`]'s predicate. A subscription that knows its
527/// type's bound can be routed to a size class instead of forcing the GLOBAL
528/// buffer knob up: `NROS_SUBSCRIBER_BUFFER_BYTES` multiplies across
529/// `MAX_SUBSCRIBERS x RING_DEPTH`, so raising it from 1024 to 4096 for one
530/// 4 KiB topic costs 98,304 bytes, while the large class that topic belongs in
531/// is already reserved and empty.
532///
533/// Takes the larger of the two encodings, for the same reason `bound_fits`
534/// does: the peer picks the encoding at runtime, so sizing from XCDR1 alone is
535/// a trap.
536///
537/// `None` means "no bound EXISTS", never "unknown" — a buffer must not be
538/// sized from a fallback. A caller routing by size class
539/// must treat `None` as "keep the default", not as "assume small".
540pub const fn max_serialized_bound<M: crate::schema::Message>() -> Option<usize> {
541    match (M::MAX_SERIALIZED_SIZE_XCDR1, M::MAX_SERIALIZED_SIZE_XCDR2) {
542        (Some(x1), Some(x2)) => Some(if x1 > x2 { x1 } else { x2 }),
543        // One encoding unbounded makes the type unbounded on the wire, because
544        // the peer chooses. Not `Some(the_other)`.
545        _ => None,
546    }
547}
548
549/// The BUILD-ASSERTION predicate: `false` only when the type is
550/// provably too large for `rx_buf`.
551///
552/// Distinct from [`buffer_fits`], and the difference is the whole reason both
553/// exist:
554///
555/// * `buffer_fits` answers "is this GUARANTEED to fit", so an unbounded type is
556///   `false` — no finite buffer fits a `String`.
557/// * this answers "can we PROVE it will not fit", so an unbounded type is
558///   `true` — there is nothing to check, and failing the build for every
559///   `std_msgs/String` subscription would be absurd.
560///
561/// Asserting `buffer_fits` at a subscription site was my first attempt and
562/// would have refused the most common message in ROS. Kept as two named
563/// functions rather than one with a flag, because the wrong one is silently
564/// plausible at either call site.
565///
566/// Checks BOTH encodings and takes the larger: the encoding is a runtime
567/// property of the peer, so a buffer sized from XCDR1 alone is a trap — XCDR2
568/// adds a DHEADER per struct and is the bigger of the two for nested types.
569pub const fn bound_fits<M: crate::schema::Message>(rx_buf: usize) -> bool {
570    let x1 = match M::MAX_SERIALIZED_SIZE_XCDR1 {
571        Some(n) => n,
572        None => return true, // unbounded: nothing to prove
573    };
574    let x2 = match M::MAX_SERIALIZED_SIZE_XCDR2 {
575        Some(n) => n,
576        None => return true,
577    };
578    let largest = if x1 > x2 { x1 } else { x2 };
579    rx_buf >= largest
580}
581
582/// Is this type loan-eligible?
583///
584/// A loan hands out a pointer into the transport's own memory, which is sound
585/// only when the layout is fixed: no length prefix to chase, no variable
586/// member. That is exactly [`SizeBound::plain`], so the answer falls out of W1
587/// rather than becoming a second notion of "fixed layout" maintained by hand —
588/// which is the drift `borrow_loaned_message` and
589/// `subscription_supports_in_place` would otherwise each grow their own version
590/// of.
591///
592/// **It has no non-test caller, and that is the decision rather than an
593/// oversight**. Its natural consumer is a TYPED loan, and the recommendation
594/// is not to build one now:
595/// the byte-span loan surface it would sit beside is measured as strictly worse
596/// than `publish_raw` on three of four backends, and the one place `IS_PLAIN`
597/// matches a real gate is Cyclone's own `fixed_size` check, which loans only
598/// under iceoryx. **0814 step 5 is the consumer**, if and when it exists. The
599/// function is kept — not inlined into that future caller — because its whole
600/// job is to be the one place the predicate is spelled; two spellings is the
601/// defect already deleted from the codegen IR.
602pub const fn is_loan_eligible<M: crate::schema::Message>() -> bool {
603    M::IS_PLAIN
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::{
610        cdr::CdrWriter,
611        schema::{Field, NestedType},
612    };
613
614    const fn f(name: &'static str, ty: FieldType) -> Field {
615        Field {
616            name,
617            ty,
618            offset: 0,
619        }
620    }
621
622    // ========================================================================
623    // issue 0896 layer 0 — naming the member that costs the bound
624    // ========================================================================
625
626    /// The two walks must agree. `first_unbounded` is a SECOND walk of the same
627    /// schema, which is the shape the sizes-header mirror defect keeps taking
628    /// (0088 -> 0268), so it earns its existence only by answering a question
629    /// `size_bound` cannot — and only while it never disagrees about the
630    /// question they share.
631    fn agree(fields: &'static [Field]) {
632        for version in [EncodingVersion::Xcdr1, EncodingVersion::Xcdr2] {
633            let bounded = size_bound(fields, version, 0).bounded;
634            let named = first_unbounded(fields);
635            assert_eq!(
636                bounded,
637                named.is_none(),
638                "size_bound says bounded={bounded} but first_unbounded says \
639                 {named:?} ({version:?})"
640            );
641        }
642    }
643
644    #[test]
645    fn a_bounded_type_has_no_offender_to_name() {
646        static FIELDS: &[Field] = &[
647            f("x", FieldType::Uint32),
648            f("s", FieldType::BoundedString(8)),
649        ];
650        agree(FIELDS);
651    }
652
653    #[test]
654    fn an_unbounded_string_is_named() {
655        static FIELDS: &[Field] = &[f("flag", FieldType::Bool), f("label", FieldType::String)];
656        agree(FIELDS);
657        let u = first_unbounded(FIELDS).unwrap();
658        assert_eq!(u.kind, UnboundedKind::String);
659        assert_eq!(&u.path[..u.depth], &["label"]);
660    }
661
662    /// The offender is usually not at the top level — this is the whole reason
663    /// the path exists rather than a bare field name.
664    #[test]
665    fn a_nested_offender_reports_its_full_path() {
666        static INNER: &[Field] = &[f("sec", FieldType::Int32), f("frame_id", FieldType::String)];
667        static INNER_TY: NestedType = NestedType {
668            type_name: "std_msgs/msg/Header",
669            fields: INNER,
670        };
671        static FIELDS: &[Field] = &[f("header", FieldType::Nested(&INNER_TY))];
672        agree(FIELDS);
673        let u = first_unbounded(FIELDS).unwrap();
674        assert_eq!(&u.path[..u.depth], &["header", "frame_id"]);
675    }
676
677    /// `string[4]` is a FIXED array of an UNBOUNDED element: the count is
678    /// known and the bound is not. Reported at the field's own path, because
679    /// an element has no name of its own.
680    #[test]
681    fn a_fixed_array_of_unbounded_elements_is_unbounded() {
682        static ELEM: FieldType = FieldType::String;
683        static FIELDS: &[Field] = &[f("names", FieldType::Array(4, &ELEM))];
684        agree(FIELDS);
685        let u = first_unbounded(FIELDS).unwrap();
686        assert_eq!(&u.path[..u.depth], &["names"]);
687        assert_eq!(u.kind, UnboundedKind::String);
688    }
689
690    /// A bounded sequence of bounded elements IS bounded — the easy way to get
691    /// this wrong is to treat any sequence as unbounded.
692    #[test]
693    fn a_bounded_sequence_of_bounded_elements_is_bounded() {
694        static ELEM: FieldType = FieldType::Uint16;
695        static FIELDS: &[Field] = &[f("ranges", FieldType::BoundedSequence(16, &ELEM))];
696        agree(FIELDS);
697        assert!(first_unbounded(FIELDS).is_none());
698    }
699
700    #[test]
701    fn the_first_offender_wins_so_the_message_names_one_thing() {
702        static FIELDS: &[Field] = &[
703            f("a", FieldType::String),
704            f("b", FieldType::Sequence(&FieldType::Uint8)),
705        ];
706        let u = first_unbounded(FIELDS).unwrap();
707        assert_eq!(&u.path[..u.depth], &["a"]);
708    }
709
710    /// A stack-only `core::fmt::Write` sink.
711    ///
712    /// `alloc::format!` would be shorter and would test the wrong build:
713    /// `Display` here exists FOR the `no_std` diagnostic path, so the test runs
714    /// where that path runs. Silently drops overflow — the assertion below
715    /// catches a truncated result either way.
716    struct Buf {
717        bytes: [u8; 128],
718        len: usize,
719    }
720
721    impl core::fmt::Write for Buf {
722        fn write_str(&mut self, s: &str) -> core::fmt::Result {
723            for b in s.as_bytes() {
724                if self.len < self.bytes.len() {
725                    self.bytes[self.len] = *b;
726                    self.len += 1;
727                }
728            }
729            Ok(())
730        }
731    }
732
733    #[test]
734    fn the_display_form_reads_as_a_path_and_a_kind() {
735        use core::fmt::Write;
736        static INNER: &[Field] = &[f("frame_id", FieldType::String)];
737        static INNER_TY: NestedType = NestedType {
738            type_name: "std_msgs/msg/Header",
739            fields: INNER,
740        };
741        static FIELDS: &[Field] = &[f("header", FieldType::Nested(&INNER_TY))];
742        let u = first_unbounded(FIELDS).unwrap();
743
744        let mut buf = Buf {
745            bytes: [0; 128],
746            len: 0,
747        };
748        write!(buf, "{u}").unwrap();
749        assert_eq!(
750            core::str::from_utf8(&buf.bytes[..buf.len]).unwrap(),
751            "header.frame_id (string)"
752        );
753    }
754
755    // ========================================================================
756    // phase-403 W0 — naming EVERY member, not the first
757    // ========================================================================
758
759    /// Collect a whole type's offenders. `heapless` rather than `Vec` because
760    /// this crate is `no_std`; that is also the point of the visitor shape.
761    fn all(fields: &'static [Field]) -> heapless::Vec<UnboundedField, 16> {
762        let mut out = heapless::Vec::new();
763        let _ = visit_unbounded(fields, &mut |u| {
764            let _ = out.push(u);
765            ControlFlow::Continue(())
766        });
767        out
768    }
769
770    fn names(fields: &'static [Field]) -> heapless::Vec<&'static str, 16> {
771        let mut out = heapless::Vec::new();
772        for u in all(fields) {
773            let _ = out.push(u.path[u.depth - 1]);
774        }
775        out
776    }
777
778    /// An unbounded type is a build error now, and a stock ROS type is unbounded
779    /// in several places at once, so one build has to name all of them —
780    /// otherwise bounding a package is one cap and one full codegen run per
781    /// member.
782    #[test]
783    fn every_unbounded_member_is_visited_in_declaration_order() {
784        static FIELDS: &[Field] = &[
785            f("a", FieldType::String),
786            f("keep", FieldType::Int32),
787            f("b", FieldType::Sequence(&FieldType::Int64)),
788            f("c", FieldType::WString),
789        ];
790        assert_eq!(names(FIELDS).as_slice(), &["a", "b", "c"]);
791    }
792
793    /// Nested members are visited too, and a bounded sibling does not stop the
794    /// walk from continuing past the struct that contained one.
795    #[test]
796    fn the_walk_continues_past_a_nested_offender_to_its_siblings() {
797        static INNER: &[Field] = &[f("frame_id", FieldType::String)];
798        static INNER_TY: NestedType = NestedType {
799            type_name: "std_msgs/msg/Header",
800            fields: INNER,
801        };
802        static FIELDS: &[Field] = &[
803            f("header", FieldType::Nested(&INNER_TY)),
804            f("child_frame_id", FieldType::String),
805        ];
806        assert_eq!(names(FIELDS).as_slice(), &["frame_id", "child_frame_id"]);
807        // The path, not just the leaf name, so a diagnostic can be acted on.
808        assert_eq!(all(FIELDS)[0].path[0], "header");
809        assert_eq!(all(FIELDS)[0].depth, 2);
810    }
811
812    /// `first_unbounded` is now expressed on top of this walk, so it must still
813    /// answer exactly what the walk reports first — and must still stop, rather
814    /// than enumerating a type and discarding all but one answer.
815    #[test]
816    fn the_first_offender_is_the_first_one_visited() {
817        static INNER: &[Field] = &[f("frame_id", FieldType::String)];
818        static INNER_TY: NestedType = NestedType {
819            type_name: "std_msgs/msg/Header",
820            fields: INNER,
821        };
822        static FLAT: &[Field] = &[f("a", FieldType::String), f("b", FieldType::String)];
823        static NESTED: &[Field] = &[
824            f("header", FieldType::Nested(&INNER_TY)),
825            f("tail", FieldType::String),
826        ];
827        static CLEAN: &[Field] = &[f("only", FieldType::Int32)];
828        for fields in [FLAT, NESTED, CLEAN] {
829            assert_eq!(first_unbounded(fields), all(fields).first().copied());
830        }
831    }
832
833    /// A visitor that breaks stops the walk where it broke — which is the
834    /// mechanism `first_unbounded` uses, asserted rather than assumed.
835    #[test]
836    fn a_visitor_that_breaks_stops_the_walk() {
837        static FIELDS: &[Field] = &[
838            f("a", FieldType::String),
839            f("b", FieldType::String),
840            f("c", FieldType::String),
841        ];
842        let mut seen = 0usize;
843        let flow = visit_unbounded(FIELDS, &mut |_| {
844            seen += 1;
845            if seen == 2 {
846                ControlFlow::Break(())
847            } else {
848                ControlFlow::Continue(())
849            }
850        });
851        assert_eq!(seen, 2);
852        assert_eq!(flow, ControlFlow::Break(()));
853    }
854
855    /// A bounded type has nothing to report, from either form.
856    #[test]
857    fn a_bounded_type_visits_nothing() {
858        static FIELDS: &[Field] = &[
859            f("a", FieldType::BoundedString(8)),
860            f("b", FieldType::Int32),
861        ];
862        assert!(all(FIELDS).is_empty());
863        assert!(first_unbounded(FIELDS).is_none());
864    }
865
866    /// Serialize a MAXIMAL instance of a schema with the real `CdrWriter`, and
867    /// return the byte length the writer produced (header included).
868    ///
869    /// This is the whole point of the test module: a bound that is merely
870    /// self-consistent proves nothing. Every assertion below compares
871    /// [`max_serialized_size`] against bytes this function actually wrote.
872    fn write_maximal(fields: &[Field], version: EncodingVersion, buf: &mut [u8]) -> usize {
873        let mut w = match version {
874            EncodingVersion::Xcdr1 => CdrWriter::new_with_header(buf).unwrap(),
875            EncodingVersion::Xcdr2 => CdrWriter::new_with_header_xcdr2(buf).unwrap(),
876        };
877        let dh = w.begin_dheader().unwrap();
878        write_fields(&mut w, fields);
879        w.end_dheader(dh).unwrap();
880        w.position()
881    }
882
883    /// Phase 392 W3a — `max_serialized_bound` is what routes a subscription to a
884    /// size class, so the two ways it can be wrong both cost real RAM or real
885    /// truncation: reporting the smaller encoding under-sizes the block the peer
886    /// may actually fill, and inventing a number for an unbounded type sizes a
887    /// buffer from a fallback, which phase 380 forbids in as many words.
888    struct BoundedMsg;
889    impl crate::schema::Message for BoundedMsg {
890        const TYPE_NAME: &'static str = "test/msg/BoundedMsg";
891        const FIELDS: &'static [Field] = &[
892            f("a", FieldType::Uint8),
893            f("b", FieldType::Uint64),
894            f("c", FieldType::Uint8),
895        ];
896    }
897
898    struct UnboundedMsg;
899    impl crate::schema::Message for UnboundedMsg {
900        const TYPE_NAME: &'static str = "test/msg/UnboundedMsg";
901        const FIELDS: &'static [Field] = &[f("s", FieldType::String)];
902    }
903
904    #[test]
905    fn max_serialized_bound_takes_the_larger_encoding() {
906        let x1 = <BoundedMsg as crate::schema::Message>::MAX_SERIALIZED_SIZE_XCDR1
907            .expect("bounded in xcdr1");
908        let x2 = <BoundedMsg as crate::schema::Message>::MAX_SERIALIZED_SIZE_XCDR2
909            .expect("bounded in xcdr2");
910        let got = max_serialized_bound::<BoundedMsg>().expect("bounded type has a bound");
911        assert_eq!(
912            got,
913            x1.max(x2),
914            "must take the LARGER encoding — the peer picks it at runtime, so \
915             sizing from one alone is the trap phase 380 documents"
916        );
917        assert!(
918            bound_fits::<BoundedMsg>(got),
919            "the value must satisfy the predicate it is derived from"
920        );
921        assert!(
922            !bound_fits::<BoundedMsg>(got - 1),
923            "one byte under the bound must NOT fit, or the value is not tight"
924        );
925    }
926
927    #[test]
928    fn max_serialized_bound_is_none_for_an_unbounded_type() {
929        assert_eq!(
930            max_serialized_bound::<UnboundedMsg>(),
931            None,
932            "an unbounded type has NO bound; returning a number here would let a \
933             caller size a buffer from a fallback"
934        );
935        assert!(
936            bound_fits::<UnboundedMsg>(1),
937            "unbounded still passes the BUILD assertion — nothing is provable"
938        );
939    }
940
941    fn write_fields(w: &mut CdrWriter<'_>, fields: &[Field]) {
942        for field in fields {
943            write_one(w, &field.ty);
944        }
945    }
946
947    fn write_one(w: &mut CdrWriter<'_>, ty: &FieldType) {
948        match ty {
949            FieldType::Bool => w.write_bool(true).unwrap(),
950            FieldType::Uint8 => w.write_u8(0xAB).unwrap(),
951            FieldType::Int8 => w.write_i8(-1).unwrap(),
952            FieldType::Uint16 => w.write_u16(0xBEEF).unwrap(),
953            FieldType::Int16 => w.write_i16(-2).unwrap(),
954            FieldType::Uint32 => w.write_u32(0xDEADBEEF).unwrap(),
955            FieldType::Int32 => w.write_i32(-3).unwrap(),
956            FieldType::Float32 => w.write_f32(1.5).unwrap(),
957            FieldType::Uint64 => w.write_u64(u64::MAX).unwrap(),
958            FieldType::Int64 => w.write_i64(-4).unwrap(),
959            FieldType::Float64 => w.write_f64(2.5).unwrap(),
960            // Maximal = exactly `n` payload bytes, which is what the bound
961            // claims room for.
962            FieldType::BoundedString(n) => {
963                let s = "x".repeat(*n);
964                w.write_string(&s).unwrap()
965            }
966            FieldType::String => w.write_string("").unwrap(),
967            FieldType::Array(n, inner) => {
968                for _ in 0..*n {
969                    write_one(w, inner);
970                }
971            }
972            FieldType::BoundedSequence(n, inner) => {
973                w.write_u32(*n as u32).unwrap();
974                for _ in 0..*n {
975                    write_one(w, inner);
976                }
977            }
978            FieldType::Nested(nested) => {
979                let dh = w.begin_dheader().unwrap();
980                write_fields(w, nested.fields);
981                w.end_dheader(dh).unwrap();
982            }
983            other => panic!("test writer has no maximal value for {other:?}"),
984        }
985    }
986
987    /// The core property, in both encodings: the computed bound is an upper
988    /// bound on what the writer produces, and an EXACT one when `plain`.
989    fn assert_agrees(fields: &'static [Field], version: EncodingVersion) {
990        let mut buf = [0u8; 4096];
991        let actual = write_maximal(fields, version, &mut buf);
992        let bound = max_serialized_size(fields, version).expect("these fixtures are all bounded");
993        assert!(
994            actual <= bound,
995            "{version:?}: writer produced {actual} bytes, bound claimed {bound} — \
996             an UNDER-reported bound sizes a buffer too small, which is the drop \
997             this module exists to stop"
998        );
999        if size_bound(fields, version, 0).plain {
1000            assert_eq!(
1001                actual, bound,
1002                "{version:?}: a plain type's bound must be EXACT, not merely an \
1003                 upper bound"
1004            );
1005        }
1006    }
1007
1008    fn both(fields: &'static [Field]) {
1009        assert_agrees(fields, EncodingVersion::Xcdr1);
1010        assert_agrees(fields, EncodingVersion::Xcdr2);
1011    }
1012
1013    // `builtin_interfaces/Time` — the plain case, and the one whose bound must
1014    // be exact.
1015    static TIME: &[Field] = &[f("sec", FieldType::Int32), f("nanosec", FieldType::Uint32)];
1016
1017    #[test]
1018    fn plain_struct_bound_is_exact() {
1019        both(TIME);
1020        assert!(size_bound(TIME, EncodingVersion::Xcdr1, 0).plain);
1021    }
1022
1023    /// Issue 1422 — the FLAG is version-independent; the bound it qualifies is
1024    /// NOT, and conflating the two is how "plain" gets read as "one number
1025    /// serves both encodings".
1026    ///
1027    /// `plain` answers "is there a variable-length member", which no encoding
1028    /// changes, so [`crate::schema::Message::IS_PLAIN`] is one const rather than
1029    /// two. XCDR2 still adds a fixed-width DHEADER per struct, so the exact size
1030    /// differs — and both of those facts have to hold for `plain` to mean
1031    /// "`bytes` is exact" rather than "`bytes` is the same everywhere". Written
1032    /// as a test because the issue that asked for a consumer for this flag
1033    /// described its one pinning assertion as version-INDEPENDENCE of the bound,
1034    /// which is not a property this walk has.
1035    #[test]
1036    fn plainness_is_version_independent_and_the_exact_size_is_not() {
1037        let x1 = size_bound(TIME, EncodingVersion::Xcdr1, 0);
1038        let x2 = size_bound(TIME, EncodingVersion::Xcdr2, 0);
1039        assert_eq!(
1040            x1.plain, x2.plain,
1041            "plainness cannot depend on the encoding"
1042        );
1043        assert!(x1.plain);
1044        assert_eq!(x1.bytes, 8, "two 4-byte scalars");
1045        assert_eq!(x2.bytes, 12, "same, plus the 4-byte DHEADER");
1046        assert_ne!(
1047            x1.bytes, x2.bytes,
1048            "a plain type still has two bounds — one constant would be wrong \
1049             for one encoding (issue 0776)"
1050        );
1051    }
1052
1053    /// The defect issue 0776 calls out first: a message containing an `int64`
1054    /// has TWO different bounds, because `CdrWriter::align` honours 8 under
1055    /// XCDR1 and caps at 4 under XCDR2. A single constant is silently wrong for
1056    /// one of them.
1057    #[test]
1058    fn eight_byte_alignment_differs_by_encoding() {
1059        // Two `int64`s, deliberately: with only ONE the two encodings come out
1060        // EQUAL, and that is a coincidence rather than a missing cap. For
1061        // `[u8, i64]` XCDR1 pads 7 before the i64 while XCDR2 caps alignment at
1062        // 4 and pads 3 — saving exactly the 4 bytes its DHEADER costs, so both
1063        // totals are 20. A test built on that single field would have "passed"
1064        // while asserting nothing, and would keep passing if the cap were
1065        // deleted. Repeating the pattern breaks the tie: the padding saving
1066        // scales with the number of 8-byte members, the DHEADER does not.
1067        static S: &[Field] = &[
1068            f("flag", FieldType::Uint8),
1069            f("big", FieldType::Int64),
1070            f("flag2", FieldType::Uint8),
1071            f("big2", FieldType::Int64),
1072        ];
1073        both(S);
1074        let x1 = max_serialized_size(S, EncodingVersion::Xcdr1).unwrap();
1075        let x2 = max_serialized_size(S, EncodingVersion::Xcdr2).unwrap();
1076        assert_ne!(
1077            x1, x2,
1078            "8-byte primitives must pad differently under the two encodings; if \
1079             these agree the alignment cap is not being applied"
1080        );
1081        assert!(
1082            x1 > x2,
1083            "XCDR1 aligns 8-byte primitives to 8 and so must be the larger of \
1084             the two here ({x1} vs {x2})"
1085        );
1086    }
1087
1088    /// The coincidence above, pinned so nobody "simplifies" the test back into
1089    /// it: for this one layout the encodings genuinely agree, and a bound that
1090    /// reported one number for both would look correct here and nowhere else.
1091    #[test]
1092    fn a_single_int64_makes_the_two_encodings_agree_by_coincidence() {
1093        static S: &[Field] = &[f("flag", FieldType::Uint8), f("big", FieldType::Int64)];
1094        both(S);
1095        assert_eq!(
1096            max_serialized_size(S, EncodingVersion::Xcdr1),
1097            max_serialized_size(S, EncodingVersion::Xcdr2),
1098            "XCDR2's DHEADER (+4) exactly offsets the padding its alignment cap \
1099             saves (-4) for this shape"
1100        );
1101    }
1102
1103    /// Padding depends on WHERE a field starts, so summing per-field maxima is
1104    /// wrong. Same fields, different order, different size.
1105    #[test]
1106    fn offset_is_threaded_not_summed() {
1107        static A: &[Field] = &[f("a", FieldType::Uint8), f("b", FieldType::Uint32)];
1108        static B: &[Field] = &[f("b", FieldType::Uint32), f("a", FieldType::Uint8)];
1109        both(A);
1110        both(B);
1111        assert_ne!(
1112            max_serialized_size(A, EncodingVersion::Xcdr1),
1113            max_serialized_size(B, EncodingVersion::Xcdr1),
1114            "u8,u32 pads and u32,u8 does not — a sum of maxima cannot tell them apart"
1115        );
1116    }
1117
1118    #[test]
1119    fn bounded_string_and_sequence_are_bounded_but_not_plain() {
1120        static S: &[Field] = &[
1121            f("name", FieldType::BoundedString(8)),
1122            f("vals", FieldType::BoundedSequence(3, &FieldType::Uint32)),
1123        ];
1124        both(S);
1125        let b = size_bound(S, EncodingVersion::Xcdr1, 0);
1126        assert!(b.bounded);
1127        assert!(!b.plain, "variable-length members are not loan-eligible");
1128    }
1129
1130    #[test]
1131    fn nested_struct_composes_at_the_parent_offset() {
1132        static NESTED: NestedType = NestedType {
1133            type_name: "builtin_interfaces/msg/Time",
1134            fields: TIME,
1135        };
1136        static S: &[Field] = &[
1137            f("flag", FieldType::Uint8),
1138            f("stamp", FieldType::Nested(&NESTED)),
1139        ];
1140        both(S);
1141    }
1142
1143    /// An unbounded member makes the type unbounded, and `max_serialized_size`
1144    /// must answer `None` rather than a floor someone could size a buffer from.
1145    #[test]
1146    fn unbounded_member_yields_none() {
1147        static S: &[Field] = &[
1148            f(
1149                "stamp",
1150                FieldType::Nested(&NestedType {
1151                    type_name: "builtin_interfaces/msg/Time",
1152                    fields: TIME,
1153                }),
1154            ),
1155            f("frame_id", FieldType::String),
1156        ];
1157        assert_eq!(max_serialized_size(S, EncodingVersion::Xcdr1), None);
1158        assert!(!size_bound(S, EncodingVersion::Xcdr1, 0).bounded);
1159        assert!(!size_bound(S, EncodingVersion::Xcdr1, 0).plain);
1160    }
1161
1162    /// XCDR2 delimits every struct, nested ones included. Missing the nested
1163    /// DHEADER under-reports — the dangerous direction.
1164    #[test]
1165    fn xcdr2_counts_a_dheader_per_struct() {
1166        static INNER: NestedType = NestedType {
1167            type_name: "t/Inner",
1168            fields: TIME,
1169        };
1170        static FLAT: &[Field] = &[f("sec", FieldType::Int32), f("nanosec", FieldType::Uint32)];
1171        static WRAPPED: &[Field] = &[f("inner", FieldType::Nested(&INNER))];
1172        both(WRAPPED);
1173        let flat = max_serialized_size(FLAT, EncodingVersion::Xcdr2).unwrap();
1174        let wrapped = max_serialized_size(WRAPPED, EncodingVersion::Xcdr2).unwrap();
1175        assert_eq!(
1176            wrapped,
1177            flat + 4,
1178            "the nested struct's own DHEADER must be counted under XCDR2"
1179        );
1180        // ...and must NOT be under XCDR1, where begin_dheader is a no-op.
1181        assert_eq!(
1182            max_serialized_size(WRAPPED, EncodingVersion::Xcdr1).unwrap(),
1183            max_serialized_size(FLAT, EncodingVersion::Xcdr1).unwrap(),
1184            "XCDR1 has no DHEADER; wrapping must cost nothing"
1185        );
1186    }
1187}