Skip to main content

bincode_next/features/
relative_ptr.rs

1#![allow(unsafe_code)]
2
3use core::marker::PhantomData;
4
5#[cfg(feature = "alloc")]
6use alloc::string::String;
7#[cfg(feature = "alloc")]
8use alloc::vec::Vec;
9
10/// Indicates that a type has a fixed size known at compile time.
11/// This allows us to perform bounds checking efficiently.
12pub trait StaticSize {
13    /// The size of the type in bytes.
14    const SIZE: usize;
15}
16
17macro_rules! impl_static_size {
18    ($($t:ty),*) => {
19        $(
20            impl StaticSize for $t {
21                const SIZE: usize = core::mem::size_of::<$t>();
22            }
23            // Every bit pattern is a valid value for these types.
24            unsafe impl ZeroCopy for $t {
25                const ALIGN: usize = core::mem::align_of::<$t>();
26            }
27        )*
28    };
29}
30
31impl_static_size!(
32    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
33);
34
35impl StaticSize for bool {
36    const SIZE: usize = core::mem::size_of::<Self>();
37}
38// `bool` has invalid bit patterns, so `is_valid_repr` must be checked before a reference is formed.
39unsafe impl ZeroCopy for bool {
40    const ALIGN: usize = core::mem::align_of::<Self>();
41
42    #[inline]
43    fn is_valid_repr(bytes: &[u8]) -> bool {
44        bytes.len() == Self::SIZE && bytes[0] <= 1
45    }
46}
47
48impl StaticSize for char {
49    const SIZE: usize = core::mem::size_of::<Self>();
50}
51// `char` has invalid bit patterns (surrogates, > 0x10FFFF).
52unsafe impl ZeroCopy for char {
53    const ALIGN: usize = core::mem::align_of::<Self>();
54
55    #[inline]
56    fn is_valid_repr(bytes: &[u8]) -> bool {
57        match <[u8; 4]>::try_from(bytes) {
58            | Ok(raw) => Self::from_u32(u32::from_ne_bytes(raw)).is_some(),
59            | Err(_) => false,
60        }
61    }
62}
63
64impl<T: StaticSize, const N: usize> StaticSize for [T; N] {
65    const SIZE: usize = T::SIZE * N;
66}
67
68/// A marker trait indicating that a type has a fixed, predictable layout (e.g., `#[repr(C)]`)
69/// and contains no padding bytes or invalid bit patterns allowing safe zero-copy casting.
70///
71/// # Safety
72///
73/// The type must have a fixed, predictable layout (e.g., `#[repr(C)]`) and contain no padding bytes or invalid bit patterns allowing safe zero-copy casting.
74pub unsafe trait ZeroCopy: StaticSize {
75    /// The required alignment for this type.
76    const ALIGN: usize;
77
78    /// Writes the object representation of `self` into `dst` (exactly `Self::SIZE` bytes,
79    /// already zero-initialized by the caller).
80    ///
81    /// The default implementation copies the whole representation, which is only sound for types
82    /// without padding. Types that may contain padding (such as `#[derive(ZeroCopy)]` types) must
83    /// override this to copy field by field so that padding bytes are never read.
84    #[inline]
85    fn write_repr(
86        &self,
87        dst: &mut [u8],
88    ) where
89        Self: Sized,
90    {
91        assert_eq!(dst.len(), Self::SIZE);
92        let bytes = unsafe {
93            core::slice::from_raw_parts(core::ptr::from_ref(self).cast::<u8>(), Self::SIZE)
94        };
95        dst.copy_from_slice(bytes);
96    }
97
98    /// Returns `true` if `bytes` (exactly `Self::SIZE` bytes, in native representation) form a
99    /// valid value of `Self`. Types with invalid bit patterns (e.g. `bool`, `char`) must override
100    /// this; it is checked before any reference to `Self` is created from untrusted bytes.
101    #[inline]
102    #[must_use]
103    fn is_valid_repr(bytes: &[u8]) -> bool {
104        let _ = bytes;
105        true
106    }
107}
108
109unsafe impl<T: ZeroCopy, const N: usize> ZeroCopy for [T; N] {
110    const ALIGN: usize = T::ALIGN;
111
112    #[inline]
113    fn write_repr(
114        &self,
115        dst: &mut [u8],
116    ) {
117        assert_eq!(dst.len(), Self::SIZE);
118        if T::SIZE == 0 {
119            return;
120        }
121        for (item, chunk) in self.iter().zip(dst.chunks_exact_mut(T::SIZE)) {
122            item.write_repr(chunk);
123        }
124    }
125
126    #[inline]
127    fn is_valid_repr(bytes: &[u8]) -> bool {
128        bytes.len() == T::SIZE * N && bytes.chunks_exact(T::SIZE.max(1)).all(T::is_valid_repr)
129    }
130}
131
132/// Trait for handling endianness in zero-copy types.
133#[doc(hidden)]
134pub trait Endian {
135    /// Converts a u16 from native endianness to the relative pointer's endianness.
136    fn from_native_u16(v: u16) -> u16;
137    /// Converts a u16 from the relative pointer's endianness to native endianness.
138    fn to_native_u16(v: u16) -> u16;
139    /// Converts a u32 from native endianness to the relative pointer's endianness.
140    fn from_native_u32(v: u32) -> u32;
141    /// Converts a u32 from the relative pointer's endianness to native endianness.
142    fn to_native_u32(v: u32) -> u32;
143    /// Converts a u64 from native endianness to the relative pointer's endianness.
144    fn from_native_u64(v: u64) -> u64;
145    /// Converts a u64 from the relative pointer's endianness to native endianness.
146    fn to_native_u64(v: u64) -> u64;
147    /// Converts a u128 from native endianness to the relative pointer's endianness.
148    fn from_native_u128(v: u128) -> u128;
149    /// Converts a u128 from the relative pointer's endianness to native endianness.
150    fn to_native_u128(v: u128) -> u128;
151
152    /// Converts a i16 from native endianness to the relative pointer's endianness.
153    fn from_native_i16(v: i16) -> i16;
154    /// Converts a i16 from the relative pointer's endianness to native endianness.
155    fn to_native_i16(v: i16) -> i16;
156    /// Converts a i32 from native endianness to the relative pointer's endianness.
157    fn from_native_i32(v: i32) -> i32;
158    /// Converts a i32 from the relative pointer's endianness to native endianness.
159    fn to_native_i32(v: i32) -> i32;
160    /// Converts a i64 from native endianness to the relative pointer's endianness.
161    fn from_native_i64(v: i64) -> i64;
162    /// Converts a i64 from the relative pointer's endianness to native endianness.
163    fn to_native_i64(v: i64) -> i64;
164    /// Converts a i128 from native endianness to the relative pointer's endianness.
165    fn from_native_i128(v: i128) -> i128;
166    /// Converts a i128 from the relative pointer's endianness to native endianness.
167    fn to_native_i128(v: i128) -> i128;
168
169    #[inline(always)]
170    /// Converts a f32 from native endianness to the relative pointer's endianness.
171    #[must_use]
172    fn from_native_f32(v: f32) -> f32 {
173        f32::from_bits(Self::from_native_u32(v.to_bits()))
174    }
175    #[inline(always)]
176    /// Converts a f32 from the relative pointer's endianness to native endianness.
177    #[must_use]
178    fn to_native_f32(v: f32) -> f32 {
179        f32::from_bits(Self::to_native_u32(v.to_bits()))
180    }
181    #[inline(always)]
182    /// Converts a f64 from native endianness to the relative pointer's endianness.
183    #[must_use]
184    fn from_native_f64(v: f64) -> f64 {
185        f64::from_bits(Self::from_native_u64(v.to_bits()))
186    }
187    #[inline(always)]
188    /// Converts a f64 from the relative pointer's endianness to native endianness.
189    #[must_use]
190    fn to_native_f64(v: f64) -> f64 {
191        f64::from_bits(Self::to_native_u64(v.to_bits()))
192    }
193}
194
195/// Little-endian marker.
196#[doc(hidden)]
197#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
198pub struct LittleEndian;
199impl Endian for LittleEndian {
200    #[inline(always)]
201    fn from_native_u16(v: u16) -> u16 {
202        v.to_le()
203    }
204
205    #[inline(always)]
206    fn to_native_u16(v: u16) -> u16 {
207        u16::from_le(v)
208    }
209
210    #[inline(always)]
211    fn from_native_u32(v: u32) -> u32 {
212        v.to_le()
213    }
214
215    #[inline(always)]
216    fn to_native_u32(v: u32) -> u32 {
217        u32::from_le(v)
218    }
219
220    #[inline(always)]
221    fn from_native_u64(v: u64) -> u64 {
222        v.to_le()
223    }
224
225    #[inline(always)]
226    fn to_native_u64(v: u64) -> u64 {
227        u64::from_le(v)
228    }
229
230    #[inline(always)]
231    fn from_native_u128(v: u128) -> u128 {
232        v.to_le()
233    }
234
235    #[inline(always)]
236    fn to_native_u128(v: u128) -> u128 {
237        u128::from_le(v)
238    }
239
240    #[inline(always)]
241    fn from_native_i16(v: i16) -> i16 {
242        v.to_le()
243    }
244
245    #[inline(always)]
246    fn to_native_i16(v: i16) -> i16 {
247        i16::from_le(v)
248    }
249
250    #[inline(always)]
251    fn from_native_i32(v: i32) -> i32 {
252        v.to_le()
253    }
254
255    #[inline(always)]
256    fn to_native_i32(v: i32) -> i32 {
257        i32::from_le(v)
258    }
259
260    #[inline(always)]
261    fn from_native_i64(v: i64) -> i64 {
262        v.to_le()
263    }
264
265    #[inline(always)]
266    fn to_native_i64(v: i64) -> i64 {
267        i64::from_le(v)
268    }
269
270    #[inline(always)]
271    fn from_native_i128(v: i128) -> i128 {
272        v.to_le()
273    }
274
275    #[inline(always)]
276    fn to_native_i128(v: i128) -> i128 {
277        i128::from_le(v)
278    }
279}
280
281/// Big-endian marker.
282#[doc(hidden)]
283#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
284pub struct BigEndian;
285impl Endian for BigEndian {
286    #[inline(always)]
287    fn from_native_u16(v: u16) -> u16 {
288        v.to_be()
289    }
290
291    #[inline(always)]
292    fn to_native_u16(v: u16) -> u16 {
293        u16::from_be(v)
294    }
295
296    #[inline(always)]
297    fn from_native_u32(v: u32) -> u32 {
298        v.to_be()
299    }
300
301    #[inline(always)]
302    fn to_native_u32(v: u32) -> u32 {
303        u32::from_be(v)
304    }
305
306    #[inline(always)]
307    fn from_native_u64(v: u64) -> u64 {
308        v.to_be()
309    }
310
311    #[inline(always)]
312    fn to_native_u64(v: u64) -> u64 {
313        u64::from_be(v)
314    }
315
316    #[inline(always)]
317    fn from_native_u128(v: u128) -> u128 {
318        v.to_be()
319    }
320
321    #[inline(always)]
322    fn to_native_u128(v: u128) -> u128 {
323        u128::from_be(v)
324    }
325
326    #[inline(always)]
327    fn from_native_i16(v: i16) -> i16 {
328        v.to_be()
329    }
330
331    #[inline(always)]
332    fn to_native_i16(v: i16) -> i16 {
333        i16::from_be(v)
334    }
335
336    #[inline(always)]
337    fn from_native_i32(v: i32) -> i32 {
338        v.to_be()
339    }
340
341    #[inline(always)]
342    fn to_native_i32(v: i32) -> i32 {
343        i32::from_be(v)
344    }
345
346    #[inline(always)]
347    fn from_native_i64(v: i64) -> i64 {
348        v.to_be()
349    }
350
351    #[inline(always)]
352    fn to_native_i64(v: i64) -> i64 {
353        i64::from_be(v)
354    }
355
356    #[inline(always)]
357    fn from_native_i128(v: i128) -> i128 {
358        v.to_be()
359    }
360
361    #[inline(always)]
362    fn to_native_i128(v: i128) -> i128 {
363        i128::from_be(v)
364    }
365}
366
367/// Native-endian marker.
368#[doc(hidden)]
369#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
370pub struct NativeEndian;
371impl Endian for NativeEndian {
372    #[inline(always)]
373    fn from_native_u16(v: u16) -> u16 {
374        v
375    }
376
377    #[inline(always)]
378    fn to_native_u16(v: u16) -> u16 {
379        v
380    }
381
382    #[inline(always)]
383    fn from_native_u32(v: u32) -> u32 {
384        v
385    }
386
387    #[inline(always)]
388    fn to_native_u32(v: u32) -> u32 {
389        v
390    }
391
392    #[inline(always)]
393    fn from_native_u64(v: u64) -> u64 {
394        v
395    }
396
397    #[inline(always)]
398    fn to_native_u64(v: u64) -> u64 {
399        v
400    }
401
402    #[inline(always)]
403    fn from_native_u128(v: u128) -> u128 {
404        v
405    }
406
407    #[inline(always)]
408    fn to_native_u128(v: u128) -> u128 {
409        v
410    }
411
412    #[inline(always)]
413    fn from_native_i16(v: i16) -> i16 {
414        v
415    }
416
417    #[inline(always)]
418    fn to_native_i16(v: i16) -> i16 {
419        v
420    }
421
422    #[inline(always)]
423    fn from_native_i32(v: i32) -> i32 {
424        v
425    }
426
427    #[inline(always)]
428    fn to_native_i32(v: i32) -> i32 {
429        v
430    }
431
432    #[inline(always)]
433    fn from_native_i64(v: i64) -> i64 {
434        v
435    }
436
437    #[inline(always)]
438    fn to_native_i64(v: i64) -> i64 {
439        v
440    }
441
442    #[inline(always)]
443    fn from_native_i128(v: i128) -> i128 {
444        v
445    }
446
447    #[inline(always)]
448    fn to_native_i128(v: i128) -> i128 {
449        v
450    }
451}
452
453/// A relative pointer that stores the offset from its own address to the target data.
454/// This allows zero-copy deserialization without runtime allocations.
455#[repr(transparent)]
456#[derive(Debug, PartialEq, Eq, Clone, Copy)]
457pub struct RelativePtr<T, const ALIGN: usize, E: Endian = NativeEndian> {
458    offset: i32,
459    _marker: PhantomData<(T, E)>,
460}
461
462impl<T, const ALIGN: usize, E: Endian> RelativePtr<T, ALIGN, E> {
463    /// Creates a new `RelativePtr` with the given native offset.
464    #[must_use]
465    pub fn new(offset: i32) -> Self {
466        Self {
467            offset: E::from_native_i32(offset),
468            _marker: PhantomData,
469        }
470    }
471
472    /// Resolves the pointer within the given buffer.
473    /// Returns `Some(&T)` if the computed pointer is within the bounds of `buffer`
474    /// and correctly aligned. Otherwise, returns `None`.
475    #[must_use]
476    pub fn get<'a>(
477        &self,
478        buffer: &'a [u8],
479    ) -> Option<&'a T>
480    where
481        T: ZeroCopy,
482    {
483        // Compile-time check: alignment must be a power of two, and sufficiently large for T
484        const {
485            let effective_align = if ALIGN == 0 {
486                T::ALIGN
487            } else {
488                ALIGN
489            };
490            assert!(
491                effective_align > 0 && effective_align.is_power_of_two(),
492                "Alignment must be a power of two"
493            );
494            assert!(
495                effective_align >= core::mem::align_of::<T>(),
496                "ALIGN must be at least the natural alignment of T"
497            );
498        };
499
500        let self_ptr = core::ptr::from_ref(self) as usize;
501        let buffer_start = buffer.as_ptr() as usize;
502        let buffer_end = buffer_start + buffer.len();
503
504        let self_end = self_ptr + core::mem::size_of::<Self>();
505
506        if self_ptr < buffer_start || self_end > buffer_end {
507            return None;
508        }
509
510        let offset = E::to_native_i32(unsafe { core::ptr::addr_of!(self.offset).read_unaligned() });
511
512        // Here we use wrapping arithmetic because the offset is relative to the pointer's address
513        // and could potentially wrap around the address space. But in the CPU, the address space
514        // is a linear ring, so we can use wrapping arithmetic to avoid overflow.
515        let target_addr = if offset >= 0 {
516            self_ptr.wrapping_add(offset as usize)
517        } else {
518            self_ptr.wrapping_sub(offset.unsigned_abs() as usize)
519        };
520
521        let target_end = target_addr.wrapping_add(T::SIZE);
522
523        if target_addr < buffer_start || target_end > buffer_end {
524            return None;
525        }
526
527        let effective_align = if ALIGN == 0 {
528            T::ALIGN
529        } else {
530            ALIGN
531        };
532        // Runtime alignment check
533        if target_addr % effective_align != 0 {
534            return None;
535        }
536
537        // Derive target_ptr from buffer.as_ptr() to maintain provenance over the whole buffer
538        let target_offset_in_buffer = target_addr - buffer_start;
539        let target_ptr = unsafe { buffer.as_ptr().add(target_offset_in_buffer) };
540
541        // Reject representations that are not a valid `T` (e.g. bool != 0/1, invalid char)
542        // before any reference is formed.
543        let target_bytes = unsafe { core::slice::from_raw_parts(target_ptr, T::SIZE) };
544        if !T::is_valid_repr(target_bytes) {
545            return None;
546        }
547
548        // Safe because we bounds checked against the buffer, alignment checked,
549        // representation validated, and we derive the lifetime from the buffer.
550        Some(unsafe { &*target_ptr.cast::<T>() })
551    }
552}
553
554#[cfg(feature = "fuzzing")]
555impl<'a, T, const ALIGN: usize, E: Endian> arbitrary::Arbitrary<'a> for RelativePtr<T, ALIGN, E> {
556    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
557        Ok(Self::new(i32::arbitrary(u)?))
558    }
559}
560
561impl<T, const ALIGN: usize, E: Endian> StaticSize for RelativePtr<T, ALIGN, E> {
562    const SIZE: usize = core::mem::size_of::<Self>();
563}
564
565unsafe impl<T, const ALIGN: usize, E: Endian> ZeroCopy for RelativePtr<T, ALIGN, E> {
566    const ALIGN: usize = core::mem::align_of::<i32>();
567}
568
569/// A zero-copy array collection equivalent to `[T; N]`.
570#[repr(transparent)]
571#[derive(Debug, PartialEq, Eq, Clone, Copy)]
572pub struct ZeroArray<T, const N: usize, const ALIGN: usize, E: Endian = NativeEndian> {
573    ptr: RelativePtr<[T; N], ALIGN, E>,
574}
575
576impl<T: ZeroCopy, const N: usize, const ALIGN: usize, E: Endian> ZeroArray<T, N, ALIGN, E> {
577    /// Resolves the array within the given buffer.
578    #[must_use]
579    pub fn get<'a>(
580        &self,
581        buffer: &'a [u8],
582    ) -> Option<&'a [T; N]> {
583        self.ptr.get(buffer)
584    }
585}
586
587#[cfg(feature = "fuzzing")]
588impl<'a, T: ZeroCopy, const N: usize, const ALIGN: usize, E: Endian> arbitrary::Arbitrary<'a>
589    for ZeroArray<T, N, ALIGN, E>
590{
591    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
592        Ok(Self {
593            ptr: arbitrary::Arbitrary::arbitrary(u)?,
594        })
595    }
596}
597
598impl<T, const N: usize, const ALIGN: usize, E: Endian> StaticSize for ZeroArray<T, N, ALIGN, E> {
599    const SIZE: usize = core::mem::size_of::<Self>();
600}
601
602// Implement ZeroCopy for zero-copy containers since their layouts are guaranteed
603unsafe impl<T: ZeroCopy, const N: usize, const ALIGN: usize, E: Endian> ZeroCopy
604    for ZeroArray<T, N, ALIGN, E>
605{
606    const ALIGN: usize = core::mem::align_of::<i32>();
607}
608
609/// A zero-copy string type with compile-time known max capacity, stored inline.
610#[repr(C)]
611#[derive(Debug, PartialEq, Eq, Clone, Copy)]
612pub struct ZeroString<const CAP: usize, E: Endian = NativeEndian> {
613    len: u32,
614    data: [u8; CAP],
615    _marker: PhantomData<E>,
616}
617
618impl<const CAP: usize, E: Endian> ZeroString<CAP, E> {
619    /// Resolves the string. Inline strings don't necessarily need the buffer.
620    #[must_use]
621    pub fn get(&self) -> Option<&str> {
622        let len =
623            E::to_native_u32(unsafe { core::ptr::addr_of!(self.len).read_unaligned() }) as usize;
624        let len = len.min(CAP);
625        core::str::from_utf8(&self.data[..len]).ok()
626    }
627}
628
629#[cfg(feature = "fuzzing")]
630impl<'a, const CAP: usize, E: Endian> arbitrary::Arbitrary<'a> for ZeroString<CAP, E> {
631    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
632        let len = u32::arbitrary(u)? % (CAP as u32 + 1);
633        let mut data = [0u8; CAP];
634        u.fill_buffer(&mut data[..len as usize])?;
635        Ok(Self {
636            len: E::from_native_u32(len),
637            data,
638            _marker: PhantomData,
639        })
640    }
641}
642
643impl<const CAP: usize, E: Endian> StaticSize for ZeroString<CAP, E> {
644    const SIZE: usize = core::mem::size_of::<Self>();
645}
646
647unsafe impl<const CAP: usize, E: Endian> ZeroCopy for ZeroString<CAP, E> {
648    const ALIGN: usize = core::mem::align_of::<u32>();
649}
650
651/// A zero-copy slice collection conceptually equivalent to `&[T]` or `Vec<T>`.
652#[repr(C)]
653#[derive(Debug, PartialEq, Eq, Clone, Copy)]
654pub struct ZeroSlice<T, const ALIGN: usize, E: Endian = NativeEndian> {
655    len: u32,
656    ptr: RelativePtr<T, ALIGN, E>,
657}
658
659impl<T: ZeroCopy, const ALIGN: usize, E: Endian> ZeroSlice<T, ALIGN, E> {
660    /// Creates a new `ZeroSlice` with the given native length and relative offset.
661    #[must_use]
662    pub fn new(
663        len: u32,
664        offset: i32,
665    ) -> Self {
666        Self {
667            len: E::from_native_u32(len),
668            ptr: RelativePtr::new(offset),
669        }
670    }
671
672    /// Resolves the slice within the given buffer.
673    #[must_use]
674    pub fn get<'a>(
675        &self,
676        buffer: &'a [u8],
677    ) -> Option<&'a [T]> {
678        let len = E::to_native_u32(unsafe { core::ptr::addr_of!(self.len).read_unaligned() });
679
680        if len == 0 {
681            // For zero-length slices, we can just return an empty slice,
682            // bypassing the pointer lookup (which might be invalid or dummy).
683            return Some(&[]);
684        }
685
686        // Get the first element's reference to validate base bounds, alignment, and offset
687        let first_ref = self.ptr.get(buffer)?;
688
689        let slice_len = len as usize;
690
691        // Calculate the total size required for the full slice.
692        let total_size = T::SIZE.checked_mul(slice_len)?;
693
694        let first_addr = core::ptr::from_ref::<T>(first_ref) as usize;
695        let buffer_start = buffer.as_ptr() as usize;
696        let target_offset = first_addr - buffer_start;
697
698        let target_end = target_offset.checked_add(total_size)?;
699        if target_end > buffer.len() {
700            return None;
701        }
702
703        // Validate every element's representation before forming the slice.
704        let all_bytes = &buffer[target_offset..target_end];
705        if T::SIZE > 0 && !all_bytes.chunks_exact(T::SIZE).all(T::is_valid_repr) {
706            return None;
707        }
708
709        // Derive target_ptr from buffer.as_ptr() to maintain provenance over the whole slice
710        let target_ptr = unsafe { buffer.as_ptr().add(target_offset).cast::<T>() };
711
712        Some(unsafe { core::slice::from_raw_parts(target_ptr, slice_len) })
713    }
714}
715
716#[cfg(feature = "fuzzing")]
717impl<'a, T: ZeroCopy, const ALIGN: usize, E: Endian> arbitrary::Arbitrary<'a>
718    for ZeroSlice<T, ALIGN, E>
719{
720    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
721        Ok(Self::new(u32::arbitrary(u)?, i32::arbitrary(u)?))
722    }
723}
724
725impl<T, const ALIGN: usize, E: Endian> StaticSize for ZeroSlice<T, ALIGN, E> {
726    const SIZE: usize = core::mem::size_of::<Self>();
727}
728
729unsafe impl<T: ZeroCopy, const ALIGN: usize, E: Endian> ZeroCopy for ZeroSlice<T, ALIGN, E> {
730    const ALIGN: usize = core::mem::align_of::<u32>();
731}
732
733/// A dynamically sized zero-copy string conceptually equivalent to `&str` or `String`.
734#[repr(transparent)]
735#[derive(Debug, PartialEq, Eq, Clone, Copy)]
736pub struct ZeroStr<E: Endian = NativeEndian> {
737    slice: ZeroSlice<u8, 0, E>,
738}
739
740impl<E: Endian> ZeroStr<E> {
741    /// Creates a new instance.
742    #[must_use]
743    pub fn new(
744        len: u32,
745        offset: i32,
746    ) -> Self {
747        Self {
748            slice: ZeroSlice::new(len, offset),
749        }
750    }
751
752    /// Returns a reference to the underlying data if valid.
753    #[must_use]
754    pub fn get<'a>(
755        &self,
756        buffer: &'a [u8],
757    ) -> Option<&'a str> {
758        let bytes = self.slice.get(buffer)?;
759        core::str::from_utf8(bytes).ok()
760    }
761}
762
763#[cfg(feature = "fuzzing")]
764impl<'a, E: Endian> arbitrary::Arbitrary<'a> for ZeroStr<E> {
765    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
766        Ok(Self {
767            slice: arbitrary::Arbitrary::arbitrary(u)?,
768        })
769    }
770}
771
772impl<E: Endian> StaticSize for ZeroStr<E> {
773    const SIZE: usize = core::mem::size_of::<Self>();
774}
775
776unsafe impl<E: Endian> ZeroCopy for ZeroStr<E> {
777    const ALIGN: usize = core::mem::align_of::<u32>();
778}
779
780/// A trait for validating zero-copy types.
781pub trait Validator {
782    /// Checks if the relative pointer is valid within the given buffer.
783    fn is_valid(
784        &self,
785        buffer: &[u8],
786    ) -> bool;
787}
788
789impl<T: ZeroCopy, const ALIGN: usize, E: Endian> Validator for RelativePtr<T, ALIGN, E> {
790    /// Checks if the relative pointer is valid within the given buffer.
791    fn is_valid(
792        &self,
793        buffer: &[u8],
794    ) -> bool {
795        self.get(buffer).is_some()
796    }
797}
798
799impl<const CAP: usize, E: Endian> Validator for ZeroString<CAP, E> {
800    /// Checks if the relative pointer is valid within the given buffer.
801    fn is_valid(
802        &self,
803        _buffer: &[u8],
804    ) -> bool {
805        self.get().is_some()
806    }
807}
808
809impl<T: ZeroCopy, const ALIGN: usize, E: Endian> Validator for ZeroSlice<T, ALIGN, E> {
810    /// Checks if the relative pointer is valid within the given buffer.
811    fn is_valid(
812        &self,
813        buffer: &[u8],
814    ) -> bool {
815        self.get(buffer).is_some()
816    }
817}
818
819impl<E: Endian> Validator for ZeroStr<E> {
820    /// Checks if the relative pointer is valid within the given buffer.
821    fn is_valid(
822        &self,
823        buffer: &[u8],
824    ) -> bool {
825        self.get(buffer).is_some()
826    }
827}
828
829macro_rules! impl_validator_primitive {
830    ($($t:ty),*) => {
831        $(
832            impl Validator for $t {
833                /// Checks if the relative pointer is valid within the given buffer.
834                fn is_valid(&self, _buffer: &[u8]) -> bool {
835                    true
836                }
837            }
838        )*
839    };
840}
841
842impl_validator_primitive!(
843    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, char, bool
844);
845
846impl<T: ZeroCopy, const N: usize, const ALIGN: usize, E: Endian> Validator
847    for ZeroArray<T, N, ALIGN, E>
848{
849    /// Checks if the relative pointer is valid within the given buffer.
850    fn is_valid(
851        &self,
852        buffer: &[u8],
853    ) -> bool {
854        self.get(buffer).is_some()
855    }
856}
857
858impl<T: ZeroCopy + Validator, const N: usize> Validator for [T; N] {
859    /// Checks if the relative pointer is valid within the given buffer.
860    fn is_valid(
861        &self,
862        buffer: &[u8],
863    ) -> bool {
864        for item in self {
865            if !item.is_valid(buffer) {
866                return false;
867            }
868        }
869        true
870    }
871}
872
873/// A trait for deep validation of zero-copy structures, recursively checking all pointers.
874pub trait DeepValidator: Validator {
875    /// Performs a deep validation check on the relative pointer.
876    fn is_valid_deep(
877        &self,
878        buffer: &[u8],
879    ) -> bool;
880}
881
882macro_rules! impl_deep_validator_primitive {
883    ($($t:ty),*) => {
884        $(
885            impl DeepValidator for $t {
886                /// Performs a deep validation check on the relative pointer.
887                fn is_valid_deep(&self, _buffer: &[u8]) -> bool {
888                    true
889                }
890            }
891        )*
892    };
893}
894
895impl_deep_validator_primitive!(
896    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, char, bool
897);
898
899impl<T: ZeroCopy + DeepValidator, const N: usize> DeepValidator for [T; N] {
900    /// Performs a deep validation check on the relative pointer.
901    fn is_valid_deep(
902        &self,
903        buffer: &[u8],
904    ) -> bool {
905        for item in self {
906            if !item.is_valid_deep(buffer) {
907                return false;
908            }
909        }
910        true
911    }
912}
913
914impl<T: ZeroCopy + DeepValidator, const ALIGN: usize, E: Endian> DeepValidator
915    for RelativePtr<T, ALIGN, E>
916{
917    /// Performs a deep validation check on the relative pointer.
918    fn is_valid_deep(
919        &self,
920        buffer: &[u8],
921    ) -> bool {
922        self.get(buffer)
923            .is_some_and(|target| target.is_valid_deep(buffer))
924    }
925}
926
927impl<const CAP: usize, E: Endian> DeepValidator for ZeroString<CAP, E> {
928    /// Performs a deep validation check on the relative pointer.
929    fn is_valid_deep(
930        &self,
931        _buffer: &[u8],
932    ) -> bool {
933        self.get().is_some()
934    }
935}
936
937impl<T: ZeroCopy + DeepValidator, const ALIGN: usize, E: Endian> DeepValidator
938    for ZeroSlice<T, ALIGN, E>
939{
940    /// Performs a deep validation check on the relative pointer.
941    fn is_valid_deep(
942        &self,
943        buffer: &[u8],
944    ) -> bool {
945        if let Some(slice) = self.get(buffer) {
946            for item in slice {
947                if !item.is_valid_deep(buffer) {
948                    return false;
949                }
950            }
951            true
952        } else {
953            false
954        }
955    }
956}
957
958impl<E: Endian> DeepValidator for ZeroStr<E> {
959    /// Performs a deep validation check on the relative pointer.
960    fn is_valid_deep(
961        &self,
962        buffer: &[u8],
963    ) -> bool {
964        self.get(buffer).is_some()
965    }
966}
967
968impl<T: ZeroCopy + DeepValidator, const N: usize, const ALIGN: usize, E: Endian> DeepValidator
969    for ZeroArray<T, N, ALIGN, E>
970{
971    /// Performs a deep validation check on the relative pointer.
972    fn is_valid_deep(
973        &self,
974        buffer: &[u8],
975    ) -> bool {
976        if let Some(arr) = self.get(buffer) {
977            for item in arr {
978                if !item.is_valid_deep(buffer) {
979                    return false;
980                }
981            }
982            true
983        } else {
984            false
985        }
986    }
987}
988
989// Bincode integration
990use crate::de::BorrowDecode;
991use crate::de::BorrowDecoder;
992use crate::de::Decode;
993use crate::de::Decoder;
994use crate::enc::Encode;
995use crate::enc::Encoder;
996use crate::error::DecodeError;
997use crate::error::EncodeError;
998
999impl<T: StaticSize, const ALIGN: usize, E: Endian, Context> Decode<Context>
1000    for RelativePtr<T, ALIGN, E>
1001{
1002    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
1003        Ok(Self {
1004            offset: i32::decode(decoder)?,
1005            _marker: PhantomData,
1006        })
1007    }
1008}
1009impl<'de, T: StaticSize, const ALIGN: usize, E: Endian, Context> BorrowDecode<'de, Context>
1010    for RelativePtr<T, ALIGN, E>
1011{
1012    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
1013        decoder: &mut D
1014    ) -> Result<Self, DecodeError> {
1015        Ok(Self {
1016            offset: i32::borrow_decode(decoder)?,
1017            _marker: PhantomData,
1018        })
1019    }
1020}
1021impl<T: StaticSize, const ALIGN: usize, E: Endian> Encode for RelativePtr<T, ALIGN, E> {
1022    fn encode<EN: Encoder>(
1023        &self,
1024        encoder: &mut EN,
1025    ) -> Result<(), EncodeError> {
1026        self.offset.encode(encoder)
1027    }
1028}
1029
1030impl<const CAP: usize, E: Endian, Context> Decode<Context> for ZeroString<CAP, E> {
1031    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
1032        Ok(Self {
1033            len: u32::decode(decoder)?,
1034            data: Decode::decode(decoder)?,
1035            _marker: PhantomData,
1036        })
1037    }
1038}
1039impl<'de, const CAP: usize, E: Endian, Context> BorrowDecode<'de, Context> for ZeroString<CAP, E> {
1040    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
1041        decoder: &mut D
1042    ) -> Result<Self, DecodeError> {
1043        Ok(Self {
1044            len: u32::borrow_decode(decoder)?,
1045            data: BorrowDecode::borrow_decode(decoder)?,
1046            _marker: PhantomData,
1047        })
1048    }
1049}
1050impl<const CAP: usize, E: Endian> Encode for ZeroString<CAP, E> {
1051    fn encode<EN: Encoder>(
1052        &self,
1053        encoder: &mut EN,
1054    ) -> Result<(), EncodeError> {
1055        self.len.encode(encoder)?;
1056        self.data.encode(encoder)
1057    }
1058}
1059
1060impl<T: StaticSize, const ALIGN: usize, E: Endian, Context> Decode<Context>
1061    for ZeroSlice<T, ALIGN, E>
1062{
1063    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
1064        Ok(Self {
1065            len: u32::decode(decoder)?,
1066            ptr: RelativePtr::decode(decoder)?,
1067        })
1068    }
1069}
1070impl<'de, T: StaticSize, const ALIGN: usize, E: Endian, Context> BorrowDecode<'de, Context>
1071    for ZeroSlice<T, ALIGN, E>
1072{
1073    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
1074        decoder: &mut D
1075    ) -> Result<Self, DecodeError> {
1076        Ok(Self {
1077            len: u32::borrow_decode(decoder)?,
1078            ptr: RelativePtr::borrow_decode(decoder)?,
1079        })
1080    }
1081}
1082impl<T: StaticSize, const ALIGN: usize, E: Endian> Encode for ZeroSlice<T, ALIGN, E> {
1083    fn encode<EN: Encoder>(
1084        &self,
1085        encoder: &mut EN,
1086    ) -> Result<(), EncodeError> {
1087        self.len.encode(encoder)?;
1088        self.ptr.encode(encoder)
1089    }
1090}
1091
1092impl<E: Endian, Context> Decode<Context> for ZeroStr<E> {
1093    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
1094        Ok(Self {
1095            slice: ZeroSlice::decode(decoder)?,
1096        })
1097    }
1098}
1099impl<'de, E: Endian, Context> BorrowDecode<'de, Context> for ZeroStr<E> {
1100    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
1101        decoder: &mut D
1102    ) -> Result<Self, DecodeError> {
1103        Ok(Self {
1104            slice: ZeroSlice::borrow_decode(decoder)?,
1105        })
1106    }
1107}
1108impl<E: Endian> Encode for ZeroStr<E> {
1109    fn encode<EN: Encoder>(
1110        &self,
1111        encoder: &mut EN,
1112    ) -> Result<(), EncodeError> {
1113        self.slice.encode(encoder)
1114    }
1115}
1116
1117/// An aligned byte buffer that correctly deallocates with the alignment it was allocated with.
1118///
1119/// This is necessary because `Vec<u8>` always deallocates with alignment 1, which is UB
1120/// if the memory was allocated with a higher alignment.
1121#[cfg(feature = "alloc")]
1122#[doc(hidden)]
1123pub struct AlignedBuffer {
1124    ptr: *mut u8,
1125    len: usize,
1126    align: usize,
1127}
1128
1129#[cfg(feature = "alloc")]
1130impl AlignedBuffer {
1131    fn from_vec(
1132        data: &[u8],
1133        align: usize,
1134    ) -> Self {
1135        let len = data.len();
1136        if len == 0 {
1137            return Self {
1138                ptr: core::ptr::NonNull::dangling().as_ptr(),
1139                len: 0,
1140                align,
1141            };
1142        }
1143        let layout = alloc::alloc::Layout::from_size_align(len, align).expect("Invalid layout");
1144        unsafe {
1145            let ptr = alloc::alloc::alloc(layout);
1146            if ptr.is_null() {
1147                alloc::alloc::handle_alloc_error(layout);
1148            }
1149            core::ptr::copy_nonoverlapping(data.as_ptr(), ptr, len);
1150            Self { ptr, len, align }
1151        }
1152    }
1153}
1154
1155#[cfg(feature = "alloc")]
1156impl core::ops::Deref for AlignedBuffer {
1157    /// The target type that this builds into.
1158    type Target = [u8];
1159
1160    fn deref(&self) -> &[u8] {
1161        if self.len == 0 {
1162            return &[];
1163        }
1164        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
1165    }
1166}
1167
1168#[cfg(feature = "alloc")]
1169impl AsRef<[u8]> for AlignedBuffer {
1170    fn as_ref(&self) -> &[u8] {
1171        self
1172    }
1173}
1174
1175#[cfg(feature = "alloc")]
1176impl Drop for AlignedBuffer {
1177    fn drop(&mut self) {
1178        if self.len > 0 {
1179            let layout = alloc::alloc::Layout::from_size_align(self.len, self.align)
1180                .expect("Invalid layout");
1181            unsafe {
1182                alloc::alloc::dealloc(self.ptr, layout);
1183            }
1184        }
1185    }
1186}
1187
1188/// Computes a relative offset and checks that it fits in an `i32`.
1189/// Panics if the distance between `from` and `to` exceeds the i32 range (~2GB).
1190#[cfg(feature = "alloc")]
1191fn checked_relative_offset(
1192    to: usize,
1193    from: usize,
1194) -> i32 {
1195    let diff = to as isize - from as isize;
1196    i32::try_from(diff).unwrap_or_else(|_| {
1197        panic!(
1198            "Relative offset overflow: distance {diff} between positions {from} and {to} exceeds i32 range"
1199        )
1200    })
1201}
1202
1203/// A builder for zero-copy structures.
1204#[cfg(feature = "alloc")]
1205pub struct ZeroBuilder {
1206    data: Vec<u8>,
1207    max_align: usize,
1208}
1209
1210#[cfg(feature = "alloc")]
1211impl Default for ZeroBuilder {
1212    fn default() -> Self {
1213        Self::new()
1214    }
1215}
1216
1217#[cfg(feature = "alloc")]
1218impl ZeroBuilder {
1219    /// Creates a new instance.
1220    #[must_use]
1221    pub const fn new() -> Self {
1222        Self {
1223            data: Vec::new(),
1224            max_align: 1,
1225        }
1226    }
1227
1228    /// Aligns the builder to the specified boundary.
1229    pub fn align(
1230        &mut self,
1231        align: usize,
1232    ) -> usize {
1233        if align > self.max_align {
1234            self.max_align = align;
1235        }
1236        if align > 1 {
1237            let padding = (align - (self.data.len() % align)) % align;
1238            if padding > 0 {
1239                self.data.resize(self.data.len() + padding, 0);
1240            }
1241        }
1242        self.data.len()
1243    }
1244
1245    /// Reserves space for a value of type T.
1246    pub fn reserve<T: ZeroCopy>(&mut self) -> usize {
1247        let offset = self.align(T::ALIGN);
1248        self.data.resize(offset + T::SIZE, 0);
1249        offset
1250    }
1251
1252    /// Reserves a specific number of bytes with alignment.
1253    pub fn reserve_bytes(
1254        &mut self,
1255        size: usize,
1256        align: usize,
1257    ) -> usize {
1258        let offset = self.align(align);
1259        self.data.resize(offset + size, 0);
1260        offset
1261    }
1262
1263    /// Writes a value to the specified offset.
1264    pub fn write<T: ZeroCopy>(
1265        &mut self,
1266        offset: usize,
1267        val: &T,
1268    ) {
1269        let size = T::SIZE;
1270        let dst = &mut self.data[offset..offset + size];
1271        // Padding bytes are never read from `val`; they are deterministically zeroed.
1272        dst.fill(0);
1273        val.write_repr(dst);
1274    }
1275
1276    /// Pushes a value onto the builder and returns its offset.
1277    pub fn push<T: ZeroCopy>(
1278        &mut self,
1279        val: &T,
1280    ) -> usize {
1281        let offset = self.reserve::<T>();
1282        self.write(offset, val);
1283        offset
1284    }
1285
1286    /// Pushes raw bytes onto the builder.
1287    pub fn push_bytes(
1288        &mut self,
1289        bytes: &[u8],
1290        align: usize,
1291    ) -> usize {
1292        let offset = self.align(align);
1293        self.data.extend_from_slice(bytes);
1294        offset
1295    }
1296
1297    /// Finalizes the builder and returns the `AlignedBuffer`.
1298    #[must_use]
1299    pub fn finish(self) -> AlignedBuffer {
1300        AlignedBuffer::from_vec(&self.data, self.max_align)
1301    }
1302
1303    /// Returns the current length of the buffer.
1304    #[must_use]
1305    pub const fn len(&self) -> usize {
1306        self.data.len()
1307    }
1308
1309    /// Returns true if the buffer is empty.
1310    #[must_use]
1311    pub const fn is_empty(&self) -> bool {
1312        self.data.is_empty()
1313    }
1314}
1315
1316/// A trait for zero-copy types that defines their preferred builder type.
1317pub trait ZeroCopyType<E: Endian = NativeEndian>: ZeroCopy {
1318    /// The builder type associated with this trait.
1319    type Builder;
1320}
1321
1322/// A trait for types that can be built into a zero-copy structure.
1323pub trait ZeroCopyBuilder<E: Endian = NativeEndian, const ALIGN: usize = 0> {
1324    /// The target type that this builds into.
1325    type Target: ZeroCopy;
1326
1327    #[cfg(feature = "alloc")]
1328    /// Build the zero-copy type into the builder.
1329    fn build_to_target(
1330        self,
1331        builder: &mut ZeroBuilder,
1332        offset: usize,
1333    ) -> Self::Target;
1334
1335    #[cfg(feature = "alloc")]
1336    /// Build the zero-copy type into the builder and return its offset.
1337    fn build(
1338        self,
1339        builder: &mut ZeroBuilder,
1340    ) -> usize
1341    where
1342        Self: Sized,
1343    {
1344        // Use the target's natural alignment if ALIGN is 0, otherwise use ALIGN
1345        let alignment = if ALIGN == 0 {
1346            <Self::Target as ZeroCopy>::ALIGN
1347        } else {
1348            ALIGN
1349        };
1350        let offset = builder.align(alignment);
1351        builder
1352            .data
1353            .resize(offset + <Self::Target as StaticSize>::SIZE, 0);
1354        let target = self.build_to_target(builder, offset);
1355        builder.write(offset, &target);
1356        offset
1357    }
1358}
1359
1360/// A wrapper for builders that produce a `RelativePtr`.
1361#[cfg(feature = "alloc")]
1362#[doc(hidden)]
1363pub struct RelativeBuilder<B, const ALIGN: usize>(pub B);
1364
1365#[cfg(feature = "alloc")]
1366impl<E: Endian, T, B, const ALIGN: usize> ZeroCopyBuilder<E, ALIGN> for RelativeBuilder<B, ALIGN>
1367where
1368    B: ZeroCopyBuilder<E, 0, Target = T>,
1369    T: ZeroCopy,
1370{
1371    /// The target type that this builds into.
1372    type Target = RelativePtr<T, ALIGN, E>;
1373
1374    /// Builds the object into the target location.
1375    fn build_to_target(
1376        self,
1377        builder: &mut ZeroBuilder,
1378        offset: usize,
1379    ) -> Self::Target {
1380        let target_offset = self.0.build(builder);
1381        RelativePtr::new(checked_relative_offset(target_offset, offset))
1382    }
1383}
1384
1385/// A wrapper for builders that produce a `ZeroArray`.
1386#[cfg(feature = "alloc")]
1387#[doc(hidden)]
1388pub struct ArrayBuilder<B, const N: usize, const ALIGN: usize>(pub [B; N]);
1389
1390#[cfg(feature = "alloc")]
1391impl<E: Endian, T, B, const N: usize, const ALIGN: usize> ZeroCopyBuilder<E, ALIGN>
1392    for ArrayBuilder<B, N, ALIGN>
1393where
1394    B: ZeroCopyBuilder<E, 0, Target = T>,
1395    T: ZeroCopy,
1396{
1397    /// The target type that this builds into.
1398    type Target = ZeroArray<T, N, ALIGN, E>;
1399
1400    /// Builds the object into the target location.
1401    fn build_to_target(
1402        self,
1403        builder: &mut ZeroBuilder,
1404        offset: usize,
1405    ) -> Self::Target {
1406        let effective_align = if ALIGN == 0 {
1407            T::ALIGN
1408        } else {
1409            ALIGN
1410        };
1411        let data_offset = builder.reserve_bytes(N * T::SIZE, effective_align);
1412        for (i, item) in self.0.into_iter().enumerate() {
1413            let item_offset = data_offset + i * T::SIZE;
1414            let target = item.build_to_target(builder, item_offset);
1415            builder.write(item_offset, &target);
1416        }
1417        ZeroArray {
1418            ptr: RelativePtr::new(checked_relative_offset(data_offset, offset)),
1419        }
1420    }
1421}
1422
1423/// A wrapper for builders that produce a `ZeroSlice`.
1424#[cfg(feature = "alloc")]
1425#[doc(hidden)]
1426pub struct SliceBuilder<B, const ALIGN: usize>(pub Vec<B>);
1427
1428#[cfg(feature = "alloc")]
1429impl<E: Endian, T, B, const ALIGN: usize> ZeroCopyBuilder<E, ALIGN> for SliceBuilder<B, ALIGN>
1430where
1431    B: ZeroCopyBuilder<E, 0, Target = T>,
1432    T: ZeroCopy,
1433{
1434    /// The target type that this builds into.
1435    type Target = ZeroSlice<T, ALIGN, E>;
1436
1437    /// Builds the object into the target location.
1438    fn build_to_target(
1439        self,
1440        builder: &mut ZeroBuilder,
1441        offset: usize,
1442    ) -> Self::Target {
1443        let len = self.0.len() as u32;
1444        let effective_align = if ALIGN == 0 {
1445            T::ALIGN
1446        } else {
1447            ALIGN
1448        };
1449        let data_offset = builder.reserve_bytes(self.0.len() * T::SIZE, effective_align);
1450        for (i, item) in self.0.into_iter().enumerate() {
1451            let item_offset = data_offset + i * T::SIZE;
1452            let target = item.build_to_target(builder, item_offset);
1453            builder.write(item_offset, &target);
1454        }
1455        // RelativePtr is at offset + size_of::<u32>() (after the `len` field)
1456        let ptr_field_offset = offset + core::mem::size_of::<u32>();
1457        ZeroSlice::new(len, checked_relative_offset(data_offset, ptr_field_offset))
1458    }
1459}
1460
1461macro_rules! impl_zerocopy_primitive {
1462    ($($t:ty, $from_native:ident),*) => {
1463        $(
1464            impl<E: Endian> ZeroCopyType<E> for $t {
1465                /// The builder type associated with this trait.
1466                type Builder = $t;
1467            }
1468            impl<E: Endian> ZeroCopyBuilder<E, 0> for $t {
1469                /// The target type that this builds into.
1470                type Target = $t;
1471                #[cfg(feature = "alloc")]
1472                fn build_to_target(self, _builder: &mut ZeroBuilder, _offset: usize) -> Self::Target {
1473                    E::$from_native(self)
1474                }
1475            }
1476        )*
1477    };
1478}
1479
1480impl_zerocopy_primitive!(
1481    u16,
1482    from_native_u16,
1483    u32,
1484    from_native_u32,
1485    u64,
1486    from_native_u64,
1487    u128,
1488    from_native_u128,
1489    i16,
1490    from_native_i16,
1491    i32,
1492    from_native_i32,
1493    i64,
1494    from_native_i64,
1495    i128,
1496    from_native_i128,
1497    f32,
1498    from_native_f32,
1499    f64,
1500    from_native_f64
1501);
1502
1503impl<E: Endian> ZeroCopyType<E> for u8 {
1504    /// The builder type associated with this trait.
1505    type Builder = Self;
1506}
1507impl<E: Endian> ZeroCopyBuilder<E, 0> for u8 {
1508    /// The target type that this builds into.
1509    type Target = Self;
1510
1511    #[cfg(feature = "alloc")]
1512    fn build_to_target(
1513        self,
1514        _builder: &mut ZeroBuilder,
1515        _offset: usize,
1516    ) -> Self::Target {
1517        self
1518    }
1519}
1520impl<E: Endian> ZeroCopyType<E> for i8 {
1521    /// The builder type associated with this trait.
1522    type Builder = Self;
1523}
1524impl<E: Endian> ZeroCopyBuilder<E, 0> for i8 {
1525    /// The target type that this builds into.
1526    type Target = Self;
1527
1528    #[cfg(feature = "alloc")]
1529    fn build_to_target(
1530        self,
1531        _builder: &mut ZeroBuilder,
1532        _offset: usize,
1533    ) -> Self::Target {
1534        self
1535    }
1536}
1537impl<E: Endian> ZeroCopyType<E> for bool {
1538    /// The builder type associated with this trait.
1539    type Builder = Self;
1540}
1541impl<E: Endian> ZeroCopyBuilder<E, 0> for bool {
1542    /// The target type that this builds into.
1543    type Target = Self;
1544
1545    #[cfg(feature = "alloc")]
1546    fn build_to_target(
1547        self,
1548        _builder: &mut ZeroBuilder,
1549        _offset: usize,
1550    ) -> Self::Target {
1551        self
1552    }
1553}
1554impl<E: Endian> ZeroCopyType<E> for char {
1555    /// The builder type associated with this trait.
1556    type Builder = Self;
1557}
1558impl<E: Endian> ZeroCopyBuilder<E, 0> for char {
1559    /// The target type that this builds into.
1560    type Target = Self;
1561
1562    #[cfg(feature = "alloc")]
1563    fn build_to_target(
1564        self,
1565        _builder: &mut ZeroBuilder,
1566        _offset: usize,
1567    ) -> Self::Target {
1568        Self::from_u32(E::from_native_u32(self as u32)).unwrap()
1569    }
1570}
1571
1572#[cfg(feature = "alloc")]
1573impl<E: Endian> ZeroCopyType<E> for ZeroStr<E> {
1574    /// The builder type associated with this trait.
1575    type Builder = String;
1576}
1577#[cfg(feature = "alloc")]
1578impl<E: Endian> ZeroCopyBuilder<E, 0> for String {
1579    /// The target type that this builds into.
1580    type Target = ZeroStr<E>;
1581
1582    /// Builds the object into the target location.
1583    fn build_to_target(
1584        self,
1585        builder: &mut ZeroBuilder,
1586        offset: usize,
1587    ) -> Self::Target {
1588        let alignment = 1;
1589        let data_offset = builder.push_bytes(self.as_bytes(), alignment);
1590        // The RelativePtr inside ZeroStr is at offset + size_of::<u32>() (after the `len` field).
1591        // RelativePtr::get() resolves relative to its own address, so we must adjust.
1592        let ptr_field_offset = offset + core::mem::size_of::<u32>();
1593        ZeroStr::new(
1594            self.len() as u32,
1595            checked_relative_offset(data_offset, ptr_field_offset),
1596        )
1597    }
1598}
1599
1600/// A wrapper for `String` to build into an inline `ZeroString<CAP>`.
1601#[cfg(feature = "alloc")]
1602#[doc(hidden)]
1603pub struct FixedString<const CAP: usize>(pub String);
1604
1605#[cfg(feature = "alloc")]
1606impl<E: Endian, const CAP: usize> ZeroCopyType<E> for ZeroString<CAP, E> {
1607    /// The builder type associated with this trait.
1608    type Builder = FixedString<CAP>;
1609}
1610#[cfg(feature = "alloc")]
1611impl<E: Endian, const CAP: usize> ZeroCopyBuilder<E, 0> for FixedString<CAP> {
1612    /// The target type that this builds into.
1613    type Target = ZeroString<CAP, E>;
1614
1615    /// Builds the object into the target location.
1616    fn build_to_target(
1617        self,
1618        _builder: &mut ZeroBuilder,
1619        _offset: usize,
1620    ) -> Self::Target {
1621        let bytes = self.0.as_bytes();
1622        let mut len = bytes.len().min(CAP);
1623        // Ensure truncation happens at a valid UTF-8 boundary
1624        while len > 0 && !self.0.is_char_boundary(len) {
1625            len -= 1;
1626        }
1627        let mut data = [0u8; CAP];
1628        data[..len].copy_from_slice(&bytes[..len]);
1629        ZeroString {
1630            len: E::from_native_u32(len as u32),
1631            data,
1632            _marker: PhantomData,
1633        }
1634    }
1635}
1636
1637#[cfg(feature = "alloc")]
1638impl<E: Endian, T, const ALIGN: usize> ZeroCopyType<E> for ZeroSlice<T, ALIGN, E>
1639where
1640    T: ZeroCopy + ZeroCopyType<E>,
1641{
1642    /// The builder type associated with this trait.
1643    type Builder = SliceBuilder<T::Builder, ALIGN>;
1644}
1645#[cfg(feature = "alloc")]
1646impl<E: Endian, T, B, const ALIGN: usize> ZeroCopyBuilder<E, ALIGN> for Vec<B>
1647where
1648    B: ZeroCopyBuilder<E, 0, Target = T>,
1649    T: ZeroCopy,
1650{
1651    /// The target type that this builds into.
1652    type Target = ZeroSlice<T, ALIGN, E>;
1653
1654    /// Builds the object into the target location.
1655    fn build_to_target(
1656        self,
1657        builder: &mut ZeroBuilder,
1658        offset: usize,
1659    ) -> Self::Target {
1660        let len = self.len() as u32;
1661        let effective_align = if ALIGN == 0 {
1662            T::ALIGN
1663        } else {
1664            ALIGN
1665        };
1666        let data_offset = builder.reserve_bytes(self.len() * T::SIZE, effective_align);
1667        for (i, item) in self.into_iter().enumerate() {
1668            let item_offset = data_offset + i * T::SIZE;
1669            let target = item.build_to_target(builder, item_offset);
1670            builder.write(item_offset, &target);
1671        }
1672        // RelativePtr is at offset + size_of::<u32>() (after the `len` field)
1673        let ptr_field_offset = offset + core::mem::size_of::<u32>();
1674        ZeroSlice::new(len, checked_relative_offset(data_offset, ptr_field_offset))
1675    }
1676}
1677#[cfg(feature = "alloc")]
1678impl<E: Endian, T, const ALIGN: usize> ZeroCopyType<E> for RelativePtr<T, ALIGN, E>
1679where
1680    T: ZeroCopy + ZeroCopyType<E>,
1681{
1682    /// The builder type associated with this trait.
1683    type Builder = RelativeBuilder<T::Builder, ALIGN>;
1684}
1685
1686#[cfg(feature = "alloc")]
1687impl<E: Endian, T, const N: usize, const ALIGN: usize> ZeroCopyType<E> for ZeroArray<T, N, ALIGN, E>
1688where
1689    T: ZeroCopy + ZeroCopyType<E>,
1690{
1691    /// The builder type associated with this trait.
1692    type Builder = ArrayBuilder<T::Builder, N, ALIGN>;
1693}
1694
1695impl<E: Endian, T, const N: usize> ZeroCopyType<E> for [T; N]
1696where
1697    T: ZeroCopy + ZeroCopyType<E>,
1698{
1699    /// The builder type associated with this trait.
1700    type Builder = [<T as ZeroCopyType<E>>::Builder; N];
1701}
1702impl<E: Endian, T, B, const N: usize> ZeroCopyBuilder<E, 0> for [B; N]
1703where
1704    B: ZeroCopyBuilder<E, 0, Target = T>,
1705    T: ZeroCopy,
1706{
1707    /// The target type that this builds into.
1708    type Target = [T; N];
1709
1710    #[cfg(feature = "alloc")]
1711    fn build_to_target(
1712        self,
1713        builder: &mut ZeroBuilder,
1714        offset: usize,
1715    ) -> Self::Target {
1716        let mut target_array: [core::mem::MaybeUninit<T>; N] =
1717            unsafe { core::mem::MaybeUninit::uninit().assume_init() };
1718        for (i, item) in self.into_iter().enumerate() {
1719            let item_offset = offset + i * T::SIZE;
1720            target_array[i] =
1721                core::mem::MaybeUninit::new(item.build_to_target(builder, item_offset));
1722        }
1723        unsafe { core::mem::transmute_copy(&target_array) }
1724    }
1725}