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