Skip to main content

rustbinary/
archive_codec.rs

1//! In-tree zero-copy archive codec (replaces the `rkyv` dependency).
2//!
3//! # Layout
4//!
5//! The archive payload is a flat byte buffer with a **root-first, positive
6//! relative-offset** layout — an original design distinct from rkyv's
7//! root-at-end placement:
8//!
9//! ```text
10//! payload:
11//!   [ root skeleton (fixed-size fields)  ]  <- root lives at offset 0
12//!   [ data region: string / vec bodies   ]
13//! ```
14//!
15//! Every variable-width field in a struct is a
16//! [`crate::archive_codec::RelPtr`]: a signed 32-bit
17//! byte offset **from the field's own address** to its data. Because the data
18//! region always follows the struct that references it, offsets are positive
19//! and the pointer math is monotonic.
20//!
21//! - A `String` body is `u32 byte_len` followed by UTF-8 bytes.
22//! - A `Vec<T>` body is `u32 count`, padding to `align_of::<T>()`, then
23//!   `count` `T` elements. The padding keeps the element array aligned so
24//!   [`crate::archive_codec::ArchivedVec::as_slice`] can build a `&[T]` without an unaligned
25//!   read.
26//! - Archived structs are fixed-size mirrors of their source (primitives
27//!   inline, strings and vecs as [`crate::archive_codec::RelPtr`]), so a `Vec<Reading>` is a
28//!   contiguous array of fixed-size [`crate::archive_codec::ArchivedVec`] elements.
29//!
30//! # Two-phase serialization
31//!
32//! A struct is written in two phases so that `Vec<T>` elements stay
33//! contiguous: the **skeleton** phase writes the fixed-size fields (inline
34//! primitives plus `RelPtr` placeholders for every variable-width field) and
35//! records the placeholder positions; the **bodies** phase writes the actual
36//! string/vec data and patches each placeholder. Nested structs recurse into
37//! the same two phases through a shared position queue.
38//!
39//! # Safety model
40//!
41//! The only `unsafe` is `from_raw_parts` for slices of archived primitives
42//! and `from_utf8_unchecked` for validated strings, both reached only after
43//! [`crate::archive_codec::CheckBytes`] has proven every offset, length, and range in-bounds. The
44//! backing buffer is `ALIGN`-aligned (see the archive envelope), so the root
45//! and every element array start on an alignment boundary.
46//!
47//! Archived mirrors stay borrowed in place; copying a relative-pointer field
48//! to another address would invalidate its targets.
49//!
50//! ```compile_fail
51//! use rustbinary::archive::Archive;
52//! #[derive(Archive)]
53//! struct Record { text: String }
54//! fn require_copy<T: Copy>() {}
55//! require_copy::<ArchivedRecord>();
56//! ```
57//!
58//! ```compile_fail
59//! use rustbinary::archive::Archive;
60//! #[derive(Archive)]
61//! struct Record { text: String }
62//! fn require_clone<T: Clone>() {}
63//! require_clone::<ArchivedRecord>();
64//! ```
65
66use alloc::collections::VecDeque;
67use alloc::string::String;
68use alloc::vec;
69use alloc::vec::Vec;
70use core::marker::PhantomData;
71
72/// A signed 32-bit byte offset from a field's own address to its data.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74#[repr(transparent)]
75pub struct RelPtr(i32);
76
77impl RelPtr {
78    /// Resolves the target address from the field's own address.
79    pub(crate) fn resolve(&self, field: *const u8) -> Option<*const u8> {
80        if self.0 < 0 {
81            return None;
82        }
83        Some(field.wrapping_add(self.0 as usize))
84    }
85
86    /// Reads the offset from a 4-byte little-endian slice.
87    pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
88        let value = i32::from_le_bytes(bytes.try_into().ok()?);
89        if value < 0 {
90            return None;
91        }
92        Some(Self(value))
93    }
94
95    /// The raw offset value.
96    pub(crate) fn raw(&self) -> i32 {
97        self.0
98    }
99}
100
101/// The archived form of a UTF-8 string.
102///
103/// Body layout: `u32 byte_len` followed by UTF-8 bytes.
104/// Relative pointers are tied to their address and must not be copied out.
105///
106/// ```compile_fail
107/// use rustbinary::archive_codec::ArchivedString;
108/// fn relocate(value: &ArchivedString) -> ArchivedString { *value }
109/// ```
110#[repr(transparent)]
111pub struct ArchivedString {
112    ptr: RelPtr,
113}
114
115impl ArchivedString {
116    /// Resolves the string from the field's own address.
117    ///
118    /// # Safety
119    ///
120    /// The archive must have been validated with [`CheckBytes`] and the
121    /// backing buffer must be immutable for the returned borrow.
122    pub unsafe fn as_str_unchecked(&self) -> &str {
123        let field = self as *const ArchivedString as *const u8;
124        let data = unsafe { self.ptr.resolve(field).unwrap_unchecked() };
125        let len = u32::from_le(unsafe { (data as *const u32).read_unaligned() }) as usize;
126        unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(data.add(4), len)) }
127    }
128
129    /// Returns the string (requires prior [`CheckBytes`]).
130    pub fn as_str(&self) -> &str {
131        unsafe { self.as_str_unchecked() }
132    }
133
134    /// Returns the raw UTF-8 bytes (requires prior [`CheckBytes`]).
135    pub fn as_bytes(&self) -> &[u8] {
136        self.as_str().as_bytes()
137    }
138
139    /// Returns the byte length (requires prior [`CheckBytes`]).
140    pub fn len(&self) -> usize {
141        self.as_str().len()
142    }
143
144    /// Whether the string is empty (requires prior [`CheckBytes`]).
145    pub fn is_empty(&self) -> bool {
146        self.len() == 0
147    }
148}
149
150/// The archived form of a `Vec<T>`.
151///
152/// Body layout: `u32 count` followed by `count` elements.
153///
154/// ```compile_fail
155/// use rustbinary::archive_codec::ArchivedVec;
156/// fn relocate(value: &ArchivedVec<u64>) -> ArchivedVec<u64> { *value }
157/// ```
158#[repr(transparent)]
159pub struct ArchivedVec<T> {
160    ptr: RelPtr,
161    marker: PhantomData<T>,
162}
163
164impl<T: ArchivedValue> ArchivedVec<T> {
165    /// Resolves the elements from the field's own address.
166    ///
167    /// # Safety
168    ///
169    /// The archive must have been validated with [`CheckBytes`] and the
170    /// backing buffer must be immutable for the returned borrow.
171    pub unsafe fn as_slice_unchecked(&self) -> &[T] {
172        let field = self as *const ArchivedVec<T> as *const u8;
173        let data = unsafe { self.ptr.resolve(field).unwrap_unchecked() };
174        let count = u32::from_le(unsafe { (data as *const u32).read_unaligned() }) as usize;
175        let padding = (core::mem::align_of::<T>()
176            - (data.wrapping_add(4) as usize % core::mem::align_of::<T>()))
177            % core::mem::align_of::<T>();
178        let elements = unsafe { data.add(4 + padding).cast::<T>() };
179        unsafe { core::slice::from_raw_parts(elements, count) }
180    }
181
182    /// Returns the elements as a slice (requires prior [`CheckBytes`]).
183    pub fn as_slice(&self) -> &[T] {
184        // SAFETY: contract of the archive API: validate before access.
185        unsafe { self.as_slice_unchecked() }
186    }
187
188    /// Returns a pointer to the first element (requires prior [`CheckBytes`]).
189    pub fn as_ptr(&self) -> *const T {
190        self.as_slice().as_ptr()
191    }
192
193    /// Returns an iterator over the elements (requires prior [`CheckBytes`]).
194    pub fn iter(&self) -> core::slice::Iter<'_, T> {
195        self.as_slice().iter()
196    }
197
198    /// Returns the element count (requires prior [`CheckBytes`]).
199    pub fn len(&self) -> usize {
200        self.as_slice().len()
201    }
202
203    /// Whether the vector is empty (requires prior [`CheckBytes`]).
204    pub fn is_empty(&self) -> bool {
205        self.len() == 0
206    }
207}
208
209impl<T: ArchivedValue> core::ops::Index<usize> for ArchivedVec<T> {
210    type Output = T;
211
212    fn index(&self, index: usize) -> &T {
213        &self.as_slice()[index]
214    }
215}
216
217/// Marker for archived values whose in-memory representation is their wire
218/// layout and which can therefore be read as a contiguous slice.
219///
220/// Implemented for archived primitives (`u64`, `i32`, ...) and for archived
221/// structs whose fields are all [`ArchivedValue`] (generated by the derive).
222/// Relative-pointer values must stay borrowed at their validated address.
223///
224/// # Safety
225///
226/// Implementing types must have `align_of::<Self>() <= 8`, and
227/// their bytes must be a valid in-memory value for every possible byte
228/// pattern. Safe accessors may rely only on invariants established by
229/// `CheckBytes`; types with relative pointers must not permit safe relocation
230/// (including through `Copy` or `Clone`) or mutation of the backing bytes.
231pub unsafe trait ArchivedValue: 'static {}
232
233macro_rules! archived_primitive {
234    ($($t:ty),* $(,)?) => {$(
235        unsafe impl ArchivedValue for $t {}
236    )*};
237}
238
239archived_primitive!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
240
241// `ArchivedString` is a single `RelPtr` (an `i32`): `'static`,
242// 4-aligned, and every byte pattern is a valid offset value.
243unsafe impl ArchivedValue for ArchivedString {}
244// `ArchivedVec<T>` is a `RelPtr` plus a zero-sized marker:
245// `'static` (via the `T: 'static` supertrait of `ArchivedValue`), 4-aligned,
246// and every byte pattern is a valid offset value.
247unsafe impl<T: ArchivedValue> ArchivedValue for ArchivedVec<T> {}
248
249/// The archive schema contract: the archived mirror type.
250pub trait Archive {
251    /// The archived mirror type.
252    type Archived;
253}
254
255/// The archival serialization contract.
256///
257/// A type that can be archived writes its fixed-size **skeleton** (inline
258/// primitives plus `RelPtr` placeholders) in the skeleton phase, then its
259/// variable-width **bodies** in the bodies phase. The two phases are separated
260/// so that `Vec<T>` element arrays stay contiguous in memory.
261pub trait ArchiveWrite {
262    /// Writes the skeleton fields and records every placeholder position.
263    fn write_skeleton(&self, serializer: &mut ArchiveSerializer, positions: &mut VecDeque<usize>);
264
265    /// Writes the variable-width bodies and patches placeholders.
266    fn write_bodies(
267        &self,
268        serializer: &mut ArchiveSerializer,
269        positions: &mut VecDeque<usize>,
270    ) -> Result<(), String>;
271}
272
273/// Serializer that produces the flat archive payload.
274pub struct ArchiveSerializer {
275    bytes: Vec<u8>,
276}
277
278impl Default for ArchiveSerializer {
279    fn default() -> Self {
280        Self::new()
281    }
282}
283
284impl ArchiveSerializer {
285    /// Creates an empty serializer.
286    pub fn new() -> Self {
287        Self { bytes: Vec::new() }
288    }
289
290    /// The current length of the output buffer.
291    pub fn len(&self) -> usize {
292        self.bytes.len()
293    }
294
295    /// Whether the output buffer is empty.
296    pub fn is_empty(&self) -> bool {
297        self.bytes.is_empty()
298    }
299
300    /// Starts a fresh payload (root at offset 0).
301    pub fn begin(&mut self) -> usize {
302        self.bytes.clear();
303        0
304    }
305
306    /// Writes a fixed-width `u8`.
307    pub fn write_u8(&mut self, value: u8) {
308        self.bytes.push(value);
309    }
310
311    /// Writes a fixed-width `u16`.
312    pub fn write_u16(&mut self, value: u16) {
313        self.bytes.extend_from_slice(&value.to_le_bytes());
314    }
315
316    /// Writes a fixed-width `u32`.
317    pub fn write_u32(&mut self, value: u32) {
318        self.bytes.extend_from_slice(&value.to_le_bytes());
319    }
320
321    /// Writes a fixed-width `u64`.
322    pub fn write_u64(&mut self, value: u64) {
323        self.bytes.extend_from_slice(&value.to_le_bytes());
324    }
325
326    /// Writes a fixed-width `i8`.
327    pub fn write_i8(&mut self, value: i8) {
328        self.bytes.push(value as u8);
329    }
330
331    /// Writes a fixed-width `i16`.
332    pub fn write_i16(&mut self, value: i16) {
333        self.bytes.extend_from_slice(&value.to_le_bytes());
334    }
335
336    /// Writes a fixed-width `i32`.
337    pub fn write_i32(&mut self, value: i32) {
338        self.bytes.extend_from_slice(&value.to_le_bytes());
339    }
340
341    /// Writes a fixed-width `i64`.
342    pub fn write_i64(&mut self, value: i64) {
343        self.bytes.extend_from_slice(&value.to_le_bytes());
344    }
345
346    /// Writes a fixed-width `f32`.
347    pub fn write_f32(&mut self, value: f32) {
348        self.bytes.extend_from_slice(&value.to_le_bytes());
349    }
350
351    /// Writes a fixed-width `f64`.
352    pub fn write_f64(&mut self, value: f64) {
353        self.bytes.extend_from_slice(&value.to_le_bytes());
354    }
355
356    /// Writes a fixed-width `bool`.
357    pub fn write_bool(&mut self, value: bool) {
358        self.bytes.push(value as u8);
359    }
360
361    /// Reserves a 4-byte placeholder for a [`RelPtr`] and returns the absolute
362    /// position of the placeholder.
363    pub fn reserve_ptr(&mut self) -> usize {
364        let pos = self.bytes.len();
365        self.bytes.extend_from_slice(&0i32.to_le_bytes());
366        pos
367    }
368
369    /// Pads the output with zero bytes until the length is a multiple of
370    /// `align`.
371    ///
372    /// The archived mirrors are `#[repr(C)]` structs, so the writer inserts
373    /// the same padding between fields (and before `Vec<T>` element arrays)
374    /// that the C ABI does. A zero `align` would divide by zero; the derive
375    /// only ever passes real type alignments (1, 2, 4, or 8).
376    pub fn align_to(&mut self, align: usize) {
377        debug_assert!(align != 0 && align.is_power_of_two());
378        let remainder = self.bytes.len() % align;
379        if remainder != 0 {
380            let pad = align - remainder;
381            self.bytes.resize(self.bytes.len() + pad, 0);
382        }
383    }
384
385    /// Appends a `String` body and patches the placeholder at `field_pos`.
386    pub fn write_string_at(&mut self, field_pos: usize, value: &str) -> Result<(), String> {
387        let data_pos = self.bytes.len();
388        let len = u32::try_from(value.len()).map_err(|_| "archive string exceeds u32 length")?;
389        self.patch_ptr(field_pos, data_pos)?;
390        self.bytes.extend_from_slice(&len.to_le_bytes());
391        self.bytes.extend_from_slice(value.as_bytes());
392        Ok(())
393    }
394
395    /// Appends a `Vec<T>` body (count + alignment padding + elements) and
396    /// patches the placeholder.
397    pub fn write_vec_at<T: Pod>(&mut self, field_pos: usize, values: &[T]) -> Result<(), String> {
398        let data_pos = self.bytes.len();
399        let count = u32::try_from(values.len()).map_err(|_| "archive vec exceeds u32 count")?;
400        let elements_pos = checked_vec_elements_offset(data_pos, core::mem::align_of::<T>())?;
401        self.patch_ptr(field_pos, data_pos)?;
402        self.bytes.extend_from_slice(&count.to_le_bytes());
403        while self.bytes.len() < elements_pos {
404            self.bytes.push(0);
405        }
406        for value in values {
407            self.bytes.extend_from_slice(&value.to_le_bytes());
408        }
409        Ok(())
410    }
411
412    /// Patches the placeholder at `field_pos` with the offset from
413    /// `field_pos` to `data_pos`.
414    pub fn patch_ptr(&mut self, field_pos: usize, data_pos: usize) -> Result<(), String> {
415        let delta = data_pos
416            .checked_sub(field_pos)
417            .and_then(|delta| i32::try_from(delta).ok())
418            .ok_or("archive relative offset is outside the positive i32 range")?;
419        if data_pos > self.bytes.len() {
420            return Err("archive pointer target out of bounds".into());
421        }
422        let end = field_pos
423            .checked_add(4)
424            .ok_or("archive pointer position overflow")?;
425        self.bytes
426            .get_mut(field_pos..end)
427            .ok_or("archive pointer placeholder out of bounds")?
428            .copy_from_slice(&delta.to_le_bytes());
429        Ok(())
430    }
431
432    /// Returns the complete payload.
433    pub fn finish(self) -> Vec<u8> {
434        self.bytes
435    }
436}
437
438/// Plain-data value serialized by its little-endian byte representation.
439pub trait Pod: Sized {
440    /// The little-endian byte representation.
441    fn to_le_bytes(&self) -> Vec<u8>;
442}
443
444macro_rules! pod_impl {
445    ($($t:ty),* $(,)?) => {$(
446        impl Pod for $t {
447            fn to_le_bytes(&self) -> Vec<u8> {
448                <$t>::to_le_bytes(*self).to_vec()
449            }
450        }
451    )*};
452}
453
454pod_impl!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
455
456impl Pod for bool {
457    fn to_le_bytes(&self) -> Vec<u8> {
458        vec![*self as u8]
459    }
460}
461
462/// Validates an archived value.
463///
464/// This is the in-tree replacement for rkyv's `check_archived_root`. It walks
465/// the whole graph once, proving every offset, length, and range in-bounds,
466/// and must run before the first access.
467///
468/// # Safety
469///
470/// Returning success must prove that `bytes` at `base` holds a fully valid,
471/// aligned `Self`, including its complete skeleton and every reachable value.
472/// All references exposed by safe accessors must remain inside `bytes`, with
473/// valid alignment and representation, for the lifetime of that immutable
474/// buffer. Implementations must not allow safe relocation of relative pointers
475/// or interior mutation that invalidates these guarantees.
476///
477/// ```compile_fail
478/// use rustbinary::archive_codec::CheckBytes;
479/// struct Unchecked(bool);
480/// impl CheckBytes for Unchecked {
481///     fn check_at(_: &[u8], _: usize) -> Result<(), String> { Ok(()) }
482/// }
483/// ```
484pub unsafe trait CheckBytes {
485    /// Validates the archived value at `base` inside `bytes`.
486    fn check_at(bytes: &[u8], base: usize) -> Result<(), String>;
487}
488
489std::thread_local! {
490    // Shared by recursive generated validators on this thread. The outermost
491    // guard resets the work counter, including when validation unwinds.
492    static VALIDATION_STATE: core::cell::Cell<(usize, u64)> = const {
493        core::cell::Cell::new((0, 0))
494    };
495}
496
497/// Recursion and total-visit guard used by generated archive validators.
498#[doc(hidden)]
499pub struct ValidationGuard(PhantomData<*mut ()>);
500
501impl ValidationGuard {
502    /// Starts one validation step, capped at 128 active steps and one million
503    /// visits per outermost call. The guard must live until child checks finish.
504    pub fn enter() -> Result<Self, String> {
505        VALIDATION_STATE.with(|state| {
506            let (depth, visits) = state.get();
507            if depth >= crate::tags::MAX_DEPTH {
508                return Err("archive validation depth limit exceeded".into());
509            }
510            if visits >= crate::config::DEFAULT_COLLECTION_LIMIT {
511                return Err("archive validation visit limit exceeded".into());
512            }
513            state.set((depth + 1, visits + 1));
514            Ok(Self(PhantomData))
515        })
516    }
517}
518
519impl Drop for ValidationGuard {
520    fn drop(&mut self) {
521        VALIDATION_STATE.with(|state| {
522            let (depth, visits) = state.get();
523            state.set(if depth == 1 {
524                (0, 0)
525            } else {
526                (depth - 1, visits)
527            });
528        });
529    }
530}
531
532unsafe impl CheckBytes for ArchivedString {
533    fn check_at(bytes: &[u8], base: usize) -> Result<(), String> {
534        check_skeleton::<Self>(bytes, base)?;
535        check_string_field(bytes, base)
536    }
537}
538
539/// Reads the `RelPtr` at `field_pos` and bounds-checks its target plus
540/// `header` bytes (the `u32` length) inside `bytes`.
541pub(crate) fn checked_field(bytes: &[u8], field_pos: usize) -> Option<usize> {
542    let ptr = RelPtr::from_bytes(bytes.get(field_pos..field_pos.checked_add(4)?)?)?;
543    let target = field_pos.checked_add(ptr.raw() as usize)?;
544    let end = target.checked_add(4)?;
545    if end > bytes.len() {
546        return None;
547    }
548    Some(target)
549}
550
551/// Checks the entire fixed-size representation, including trailing padding,
552/// before a validator walks fields or constructs a typed reference.
553pub fn check_skeleton<T>(bytes: &[u8], base: usize) -> Result<(), String> {
554    if cfg!(target_endian = "big") {
555        return Err("zero-copy archive access requires a little-endian target".into());
556    }
557    let end = base
558        .checked_add(core::mem::size_of::<T>())
559        .ok_or("archive skeleton size overflow")?;
560    if end > bytes.len() {
561        return Err("archive skeleton out of bounds".into());
562    }
563    let alignment = core::mem::align_of::<T>();
564    if base % alignment != 0 || bytes.as_ptr() as usize % alignment != 0 {
565        return Err("archive skeleton is misaligned".into());
566    }
567    Ok(())
568}
569
570fn checked_vec_elements_offset(body_base: usize, align: usize) -> Result<usize, String> {
571    if !align.is_power_of_two() {
572        return Err("invalid vec element alignment".into());
573    }
574    let after_count = body_base.checked_add(4).ok_or("vec header overflow")?;
575    after_count
576        .checked_add((align - after_count % align) % align)
577        .ok_or_else(|| "vec alignment overflow".into())
578}
579
580/// Byte offset of the element array inside a `Vec<T>` body, given the body's
581/// base address (the position of the `u32` count). The writer inserts the
582/// same padding, so reader and writer always agree.
583pub(crate) fn vec_elements_offset(body_base: usize, align: usize) -> usize {
584    let after_count = body_base + 4;
585    let pad = (align - (after_count % align)) % align;
586    after_count + pad
587}
588
589/// The alignment helper for a concrete element type, mirroring the private
590/// `vec_elements_offset` used by the writer and validators (crate-private, so
591/// not linkable from public docs).
592pub fn vec_elements_offset_of<T>(body_base: usize) -> usize {
593    vec_elements_offset(body_base, core::mem::align_of::<T>())
594}
595
596/// Checks a `String` field: reads `u32 len` at the target and verifies the
597/// UTF-8 bytes fit.
598pub fn check_string_field(bytes: &[u8], field_pos: usize) -> Result<(), String> {
599    let target = checked_field(bytes, field_pos).ok_or("string offset out of bounds")?;
600    let len = u32::from_le_bytes(
601        bytes
602            .get(target..target + 4)
603            .ok_or("string length out of bounds")?
604            .try_into()
605            .map_err(|_| "string length read failed")?,
606    ) as usize;
607    let body = target + 4;
608    let end = body.checked_add(len).ok_or("string body length overflow")?;
609    if end > bytes.len() {
610        return Err("string body out of bounds".into());
611    }
612    core::str::from_utf8(&bytes[body..end])
613        .map(|_| ())
614        .map_err(|_| "invalid UTF-8 in archived string".into())
615}
616
617/// Checks a `Vec<T>` field of fixed-size elements: reads `u32 count` at the
618/// target, skips the alignment padding, and verifies the element slice fits.
619pub fn check_vec_field(
620    bytes: &[u8],
621    field_pos: usize,
622    element_size: usize,
623    element_align: usize,
624) -> Result<(), String> {
625    if cfg!(target_endian = "big")
626        || !element_align.is_power_of_two()
627        || bytes.as_ptr() as usize % element_align != 0
628        || element_size % element_align != 0
629    {
630        return Err("invalid or misaligned vec element layout".into());
631    }
632    let target = checked_field(bytes, field_pos).ok_or("vec offset out of bounds")?;
633    let count = u32::from_le_bytes(
634        bytes
635            .get(target..target + 4)
636            .ok_or("vec count out of bounds")?
637            .try_into()
638            .map_err(|_| "vec count read failed")?,
639    ) as usize;
640    let size = count
641        .checked_mul(element_size)
642        .ok_or("vec body size overflow")?;
643    let body = checked_vec_elements_offset(target, element_align)?;
644    let end = body.checked_add(size).ok_or("vec body overflow")?;
645    if end > bytes.len() {
646        return Err("vec body out of bounds".into());
647    }
648    Ok(())
649}
650
651/// Checks a `Vec<T>` field of nested archived structs: verifies the element
652/// slice fits (including alignment padding) and recursively validates each
653/// element.
654pub fn check_vec_nested<T: CheckBytes>(
655    bytes: &[u8],
656    field_pos: usize,
657    element_size: usize,
658    element_align: usize,
659) -> Result<(), String> {
660    let _validation = ValidationGuard::enter()?;
661    if element_size != core::mem::size_of::<T>() || element_align != core::mem::align_of::<T>() {
662        return Err("nested vec element layout does not match its type".into());
663    }
664    check_vec_field(bytes, field_pos, element_size, element_align)?;
665    let target = checked_field(bytes, field_pos).ok_or("vec offset out of bounds")?;
666    let count = u32::from_le_bytes(
667        bytes
668            .get(target..target + 4)
669            .ok_or("vec count out of bounds")?
670            .try_into()
671            .map_err(|_| "vec count read failed")?,
672    ) as usize;
673    let size = count
674        .checked_mul(element_size)
675        .ok_or("vec body size overflow")?;
676    let body = checked_vec_elements_offset(target, element_align)?;
677    let end = body.checked_add(size).ok_or("vec body overflow")?;
678    if end > bytes.len() {
679        return Err("vec body out of bounds".into());
680    }
681    for i in 0..count {
682        let element_base = body
683            .checked_add(
684                i.checked_mul(element_size)
685                    .ok_or("vec element offset overflow")?,
686            )
687            .ok_or("vec element offset overflow")?;
688        T::check_at(bytes, element_base)?;
689    }
690    Ok(())
691}
692
693/// Convenience: serializes a root value into a fresh payload.
694pub fn to_archive<T: ArchiveWrite>(value: &T) -> Result<Vec<u8>, String> {
695    let mut serializer = ArchiveSerializer::new();
696    serializer.begin();
697    let mut positions = VecDeque::new();
698    value.write_skeleton(&mut serializer, &mut positions);
699    value.write_bodies(&mut serializer, &mut positions)?;
700    Ok(serializer.finish())
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    /// Reads the `u32` at a validated body position via pure slice indexing.
708    ///
709    /// Every caller runs the matching `check_*_field` validator first, so the
710    /// range is already known in-bounds; indexing here can never go out of
711    /// bounds and needs no raw pointers.
712    fn read_u32(bytes: &[u8], pos: usize) -> u32 {
713        u32::from_le_bytes(bytes[pos..pos + 4].try_into().expect("validated u32 range"))
714    }
715
716    #[test]
717    fn string_roundtrip() {
718        let mut serializer = ArchiveSerializer::new();
719        serializer.begin();
720        let field = serializer.reserve_ptr();
721        serializer.write_string_at(field, "hello archive").unwrap();
722        let payload = serializer.finish();
723        check_string_field(&payload, field).unwrap();
724
725        let target = checked_field(&payload, field).expect("validated string offset");
726        let len = read_u32(&payload, target) as usize;
727        let body = &payload[target + 4..target + 4 + len];
728        assert_eq!(
729            core::str::from_utf8(body).expect("validated UTF-8"),
730            "hello archive"
731        );
732    }
733
734    #[test]
735    fn vec_roundtrip() {
736        let mut serializer = ArchiveSerializer::new();
737        serializer.begin();
738        let field = serializer.reserve_ptr();
739        serializer
740            .write_vec_at(field, &[1i32, 2, 3, 65_536])
741            .unwrap();
742        let payload = serializer.finish();
743        check_vec_field(&payload, field, 4, 4).unwrap();
744        let target = checked_field(&payload, field).expect("validated vec offset");
745        assert_eq!(read_u32(&payload, target), 4);
746        let elements = vec_elements_offset(target, 4);
747        let expected = [1i32, 2, 3, 65_536];
748        for (i, &value) in expected.iter().enumerate() {
749            let start = elements + i * 4;
750            let word: [u8; 4] = payload[start..start + 4]
751                .try_into()
752                .expect("validated element");
753            assert_eq!(i32::from_le_bytes(word), value);
754        }
755    }
756
757    #[test]
758    fn vec_elements_are_aligned() {
759        let mut serializer = ArchiveSerializer::new();
760        serializer.begin();
761        let string_field = serializer.reserve_ptr();
762        serializer.write_string_at(string_field, "abc").unwrap();
763        serializer.align_to(4);
764        let vec_field = serializer.reserve_ptr();
765        serializer.write_vec_at(vec_field, &[7i32, 8, 9]).unwrap();
766        let payload = serializer.finish();
767        check_vec_field(&payload, vec_field, 4, 4).unwrap();
768
769        let target = checked_field(&payload, vec_field).expect("validated vec offset");
770        assert_eq!(read_u32(&payload, target), 3);
771        let elements = vec_elements_offset(target, 4);
772        assert_eq!(elements % 4, 0, "element array must be 4-aligned");
773        let expected = [7i32, 8, 9];
774        for (i, &value) in expected.iter().enumerate() {
775            let start = elements + i * 4;
776            let word: [u8; 4] = payload[start..start + 4]
777                .try_into()
778                .expect("validated element");
779            assert_eq!(i32::from_le_bytes(word), value);
780        }
781    }
782
783    #[test]
784    fn negative_offsets_are_rejected() {
785        let mut serializer = ArchiveSerializer::new();
786        serializer.begin();
787        let field = serializer.reserve_ptr();
788        serializer.bytes[field..field + 4].copy_from_slice(&(-8i32).to_le_bytes());
789        let payload = serializer.finish();
790        assert!(check_string_field(&payload, field).is_err());
791    }
792
793    #[test]
794    fn corrupted_length_is_rejected() {
795        let mut serializer = ArchiveSerializer::new();
796        serializer.begin();
797        let field = serializer.reserve_ptr();
798        serializer.write_string_at(field, "x").unwrap();
799        let mut payload = serializer.finish();
800
801        let target = RelPtr::from_bytes(&payload[field..field + 4])
802            .unwrap()
803            .raw() as usize;
804        payload[target..target + 4].copy_from_slice(&1_000_000u32.to_le_bytes());
805        assert!(check_string_field(&payload, field).is_err());
806    }
807
808    #[test]
809    fn nested_vec_elements_are_checked() {
810        let mut serializer = ArchiveSerializer::new();
811        serializer.begin();
812        let field = serializer.reserve_ptr();
813        serializer.write_u32(2); // count
814        serializer.write_u64(10);
815        serializer.write_u32(100);
816        serializer.write_u64(20);
817        serializer.write_u32(200);
818        serializer.patch_ptr(field, 0).unwrap();
819        let payload = serializer.finish();
820
821        check_vec_field(&payload, field, 12, 1).unwrap();
822    }
823}