wincode-arcium-fork 0.2.7

Fast bincode de/serialization with placement initialization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! This module provides specialized implementations of standard library collection types that
//! provide control over the length encoding (see [`SeqLen`](crate::len::SeqLen)), as well
//! as special case opt-in raw-copy overrides (see [`Pod`]).
//!
//! # Examples
//! Raw byte vec with solana short vec length encoding:
//!
//! ```
//! # #[cfg(all(feature = "solana-short-vec", feature = "alloc"))] {
//! # use wincode::{containers::self, len::ShortU16Len};
//! # use wincode_derive::SchemaWrite;
//! # use serde::Serialize;
//! # use solana_short_vec;
//! #[derive(Serialize, SchemaWrite)]
//! struct MyStruct {
//!     #[serde(with = "solana_short_vec")]
//!     #[wincode(with = "containers::Vec<_, ShortU16Len>")]
//!     vec: Vec<u8>,
//! }
//!
//! let my_struct = MyStruct {
//!     vec: vec![1, 2, 3],
//! };
//! let wincode_bytes = wincode::serialize(&my_struct).unwrap();
//! let bincode_bytes = bincode::serialize(&my_struct).unwrap();
//! assert_eq!(wincode_bytes, bincode_bytes);
//! # }
//! ```
//!
//! Vector with struct elements and custom length encoding:
//!
//! ```
//! # #[cfg(all(feature = "solana-short-vec", feature = "alloc", feature = "derive"))] {
//! # use wincode_derive::SchemaWrite;
//! # use wincode::{containers::self, len::ShortU16Len};
//! # use serde::Serialize;
//! # use solana_short_vec;
//! #[derive(Serialize, SchemaWrite)]
//! struct Point {
//!     x: u64,
//!     y: u64,
//! }
//!
//! #[derive(Serialize, SchemaWrite)]
//! struct MyStruct {
//!     #[serde(with = "solana_short_vec")]
//!     #[wincode(with = "containers::Vec<Point, ShortU16Len>")]
//!     vec: Vec<Point>,
//! }
//!
//! let my_struct = MyStruct {
//!     vec: vec![Point { x: 1, y: 2 }, Point { x: 3, y: 4 }],
//! };
//! let wincode_bytes = wincode::serialize(&my_struct).unwrap();
//! let bincode_bytes = bincode::serialize(&my_struct).unwrap();
//! assert_eq!(wincode_bytes, bincode_bytes);
//! # }
//! ```
use {
    crate::{
        error::{ReadResult, WriteResult},
        io::{Reader, Writer},
        schema::{SchemaRead, SchemaWrite},
        TypeMeta, ZeroCopy,
    },
    core::{marker::PhantomData, mem::MaybeUninit, ptr},
};
#[cfg(feature = "alloc")]
use {
    crate::{
        len::{BincodeLen, SeqLen},
        schema::{size_of_elem_iter, size_of_elem_slice, write_elem_iter, write_elem_slice},
    },
    alloc::{boxed::Box as AllocBox, collections, rc::Rc as AllocRc, sync::Arc as AllocArc, vec},
    core::mem::{self, ManuallyDrop},
};

/// A [`Vec`](std::vec::Vec) with a customizable length encoding.
#[cfg(feature = "alloc")]
pub struct Vec<T, Len = BincodeLen>(PhantomData<Len>, PhantomData<T>);

/// A [`VecDeque`](std::collections::VecDeque) with a customizable length encoding.
#[cfg(feature = "alloc")]
pub struct VecDeque<T, Len = BincodeLen>(PhantomData<Len>, PhantomData<T>);

/// A [`Box<[T]>`](std::boxed::Box) with a customizable length encoding.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "alloc", feature = "derive", feature = "solana-short-vec"))] {
/// # use wincode::{containers, len::ShortU16Len};
/// # use wincode_derive::{SchemaWrite, SchemaRead};
/// # use serde::{Serialize, Deserialize};
/// # use std::array;
/// #[derive(Serialize, SchemaWrite, Clone, Copy)]
/// #[repr(transparent)]
/// struct Address([u8; 32]);
///
/// #[derive(Serialize, SchemaWrite)]
/// struct MyStruct {
///     #[serde(with = "solana_short_vec")]
///     #[wincode(with = "containers::Box<[Address], ShortU16Len>")]
///     address: Box<[Address]>
/// }
///
/// let my_struct = MyStruct {
///     address: vec![Address(array::from_fn(|i| i as u8)); 10].into_boxed_slice(),
/// };
/// let wincode_bytes = wincode::serialize(&my_struct).unwrap();
/// let bincode_bytes = bincode::serialize(&my_struct).unwrap();
/// assert_eq!(wincode_bytes, bincode_bytes);
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct Box<T: ?Sized, Len = BincodeLen>(PhantomData<T>, PhantomData<Len>);

#[cfg(feature = "alloc")]
/// Like [`Box`], for [`Rc`].
pub struct Rc<T: ?Sized, Len = BincodeLen>(PhantomData<T>, PhantomData<Len>);

#[cfg(feature = "alloc")]
/// Like [`Box`], for [`Arc`].
pub struct Arc<T: ?Sized, Len = BincodeLen>(PhantomData<T>, PhantomData<Len>);

#[cfg(feature = "bytes")]
/// A [`bytes::Bytes`] with a customizable length encoding.
pub struct Bytes<Len = BincodeLen>(PhantomData<Len>);

#[cfg(feature = "bytes")]
/// A [`bytes::BytesMut`] with a customizable length encoding.
pub struct BytesMut<Len = BincodeLen>(PhantomData<Len>);

/// Indicates that the type is an element of a sequence, composable with [`containers`](self).
///
/// Prefer [`Pod`] for types representable as raw bytes.
#[deprecated(
    since = "0.2.0",
    note = "Elem is no longer needed for container usage. Use `T` directly instead."
)]
pub struct Elem<T>(PhantomData<T>);

/// Indicates that the type is represented by raw bytes and does not have any invalid bit patterns.
///
/// By opting into `Pod`, you are telling wincode that it can serialize and deserialize a type
/// with a single memcpy -- it wont pay attention to things like struct layout, endianness, or anything
/// else that would require validity or bit pattern checks. This is a very strong claim to make,
/// so be sure that your type adheres to those requirements.
///
/// Composable with sequence [`containers`](self) or compound types (structs, tuples) for
/// an optimized read/write implementation.
///
///
/// This can be useful outside of sequences as well, for example on newtype structs
/// containing byte arrays with `#[repr(transparent)]`.
///
/// ---
/// 💡 **Note:** as of `wincode` `0.2.0`, `Pod` is no longer needed for types that wincode can determine
/// are "Pod-safe".
///
/// This includes:
/// - [`u8`]
/// - [`[u8; N]`](prim@array)
/// - structs comprised of the above, and;
///     - annotated with `#[derive(SchemaWrite)]` or `#[derive(SchemaRead)]`, and;
///     - annotated with `#[repr(transparent)]` or `#[repr(C)]`.
///
/// Similarly, using built-in std collections like `Vec<T>` or `Box<[T]>` where `T` is one of the
/// above will also be automatically optimized.
///
/// You'll really only need to reach for [`Pod`] when dealing with foreign types for which you cannot
/// derive `SchemaWrite` or `SchemaRead`. Or you're in a controlled scenario where you explicitly
/// want to avoid endianness or layout checks.
///
/// # Safety
///
/// - The type must allow any bit pattern (e.g., no `bool`s, no `char`s, etc.)
/// - If used on a compound type like a struct, all fields must be also be `Pod`, its
///   layout must be guaranteed (via `#[repr(transparent)]` or `#[repr(C)]`), and the struct
///   must not have any padding.
/// - Must not contain references or pointers (includes types like `Vec` or `Box`).
///     - Note, you may use `Pod` *inside* types like `Vec` or `Box`, e.g., `Vec<Pod<T>>` or `Box<[Pod<T>]>`,
///       but specifying `Pod` on the outer type is invalid.
///
/// # Examples
///
/// A repr-transparent newtype struct containing a byte array where you cannot derive `SchemaWrite` or `SchemaRead`:
/// ```
/// # #[cfg(all(feature = "alloc", feature = "derive"))] {
/// # use wincode::{containers::{self, Pod}};
/// # use wincode_derive::{SchemaWrite, SchemaRead};
/// # use serde::{Serialize, Deserialize};
/// # use std::array;
/// #[derive(Serialize, Deserialize, Clone, Copy)]
/// #[repr(transparent)]
/// struct Address([u8; 32]);
///
/// #[derive(Serialize, Deserialize, SchemaWrite, SchemaRead)]
/// struct MyStruct {
///     #[wincode(with = "Pod<_>")]
///     address: Address
/// }
///
/// let my_struct = MyStruct {
///     address: Address(array::from_fn(|i| i as u8)),
/// };
/// let wincode_bytes = wincode::serialize(&my_struct).unwrap();
/// let bincode_bytes = bincode::serialize(&my_struct).unwrap();
/// assert_eq!(wincode_bytes, bincode_bytes);
/// # }
/// ```
pub struct Pod<T: Copy + 'static>(PhantomData<T>);

// SAFETY:
// - By using `Pod`, user asserts that the type is zero-copy, given the contract of Pod:
//   - The type's in‑memory representation is exactly its serialized bytes.
//   - It can be safely initialized by memcpy (no validation, no endianness/layout work).
//   - Does not contain references or pointers.
unsafe impl<T> ZeroCopy for Pod<T> where T: Copy + 'static {}

impl<T> SchemaWrite for Pod<T>
where
    T: Copy + 'static,
{
    type Src = T;

    const TYPE_META: TypeMeta = TypeMeta::Static {
        size: size_of::<T>(),
        zero_copy: true,
    };

    #[inline]
    fn size_of(_src: &Self::Src) -> WriteResult<usize> {
        Ok(size_of::<T>())
    }

    #[inline]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        // SAFETY: `T` is plain ol' data.
        unsafe { Ok(writer.write_t(src)?) }
    }
}

impl<'de, T> SchemaRead<'de> for Pod<T>
where
    T: Copy + 'static,
{
    type Dst = T;

    const TYPE_META: TypeMeta = TypeMeta::Static {
        size: size_of::<T>(),
        zero_copy: true,
    };

    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        // SAFETY: `T` is plain ol' data.
        unsafe { Ok(reader.copy_into_t(dst)?) }
    }
}

// Provide `SchemaWrite` implementation for `Elem<T>` for backwards compatibility.
//
// Container impls use blanket implementations over `T` where `T` is `SchemaWrite`,
// so this preserves existing behavior, such that `Elem<T>` behaves exactly like `T`.
#[allow(deprecated)]
impl<T> SchemaWrite for Elem<T>
where
    T: SchemaWrite,
{
    type Src = T::Src;

    const TYPE_META: TypeMeta = T::TYPE_META;

    #[inline]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        T::size_of(src)
    }

    #[inline]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        T::write(writer, src)
    }
}

// Provide `SchemaRead` implementation for `Elem<T>` for backwards compatibility.
//
// Container impls use blanket implementations over `T` where `T` is `SchemaRead`,
// so this preserves existing behavior, such that `Elem<T>` behaves exactly like `T`.
#[allow(deprecated)]
impl<'de, T> SchemaRead<'de> for Elem<T>
where
    T: SchemaRead<'de>,
{
    type Dst = T::Dst;

    const TYPE_META: TypeMeta = T::TYPE_META;

    #[inline]
    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        T::read(reader, dst)
    }
}

#[cfg(feature = "alloc")]
impl<T, Len> SchemaWrite for Vec<T, Len>
where
    Len: SeqLen,
    T: SchemaWrite,
    T::Src: Sized,
{
    type Src = vec::Vec<T::Src>;

    #[inline(always)]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        size_of_elem_slice::<T, Len>(src)
    }

    #[inline(always)]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        write_elem_slice::<T, Len>(writer, src)
    }
}

#[cfg(feature = "alloc")]
impl<'de, T, Len> SchemaRead<'de> for Vec<T, Len>
where
    Len: SeqLen,
    T: SchemaRead<'de>,
{
    type Dst = vec::Vec<T::Dst>;

    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        let len = Len::read::<T::Dst>(reader)?;
        let mut vec: vec::Vec<T::Dst> = vec::Vec::with_capacity(len);

        match T::TYPE_META {
            TypeMeta::Static {
                zero_copy: true, ..
            } => {
                let spare_capacity = vec.spare_capacity_mut();
                // SAFETY: T::Dst is zero-copy eligible (no invalid bit patterns, no layout requirements, no endianness checks, etc.).
                unsafe { reader.copy_into_slice_t(spare_capacity)? };
                // SAFETY: `copy_into_slice_t` fills the entire spare capacity or errors.
                unsafe { vec.set_len(len) };
            }
            TypeMeta::Static {
                size,
                zero_copy: false,
            } => {
                let mut ptr = vec.as_mut_ptr().cast::<MaybeUninit<T::Dst>>();
                #[allow(clippy::arithmetic_side_effects)]
                // SAFETY: `T::TYPE_META` specifies a static size, so `len` reads of `T::Dst`
                // will consume `size * len` bytes, fully consuming the trusted window.
                let mut reader = unsafe { reader.as_trusted_for(size * len) }?;
                for i in 0..len {
                    T::read(&mut reader, unsafe { &mut *ptr })?;
                    unsafe {
                        ptr = ptr.add(1);
                        #[allow(clippy::arithmetic_side_effects)]
                        // i <= len
                        vec.set_len(i + 1);
                    }
                }
            }
            TypeMeta::Dynamic => {
                let mut ptr = vec.as_mut_ptr().cast::<MaybeUninit<T::Dst>>();
                for i in 0..len {
                    T::read(reader, unsafe { &mut *ptr })?;
                    unsafe {
                        ptr = ptr.add(1);
                        #[allow(clippy::arithmetic_side_effects)]
                        // i <= len
                        vec.set_len(i + 1);
                    }
                }
            }
        }

        dst.write(vec);
        Ok(())
    }
}

pub(crate) struct SliceDropGuard<T> {
    ptr: *mut MaybeUninit<T>,
    initialized_len: usize,
}

impl<T> SliceDropGuard<T> {
    pub(crate) fn new(ptr: *mut MaybeUninit<T>) -> Self {
        Self {
            ptr,
            initialized_len: 0,
        }
    }

    #[inline(always)]
    #[allow(clippy::arithmetic_side_effects)]
    pub(crate) fn inc_len(&mut self) {
        self.initialized_len += 1;
    }
}

impl<T> Drop for SliceDropGuard<T> {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
                self.ptr.cast::<T>(),
                self.initialized_len,
            ));
        }
    }
}

macro_rules! impl_heap_slice {
    ($container:ident => $target:ident) => {
        #[cfg(feature = "alloc")]
        impl<T, Len> SchemaWrite for $container<[T], Len>
        where
            Len: SeqLen,
            T: SchemaWrite,
            T::Src: Sized,
        {
            type Src = $target<[T::Src]>;

            #[inline(always)]
            fn size_of(src: &Self::Src) -> WriteResult<usize> {
                size_of_elem_slice::<T, Len>(src)
            }

            #[inline(always)]
            fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
                write_elem_slice::<T, Len>(writer, src)
            }
        }

        #[cfg(feature = "alloc")]
        impl<'de, T, Len> SchemaRead<'de> for $container<[T], Len>
        where
            Len: SeqLen,
            T: SchemaRead<'de>,
        {
            type Dst = $target<[T::Dst]>;

            #[inline(always)]
            fn read(
                reader: &mut impl Reader<'de>,
                dst: &mut MaybeUninit<Self::Dst>,
            ) -> ReadResult<()> {
                /// Drop guard for `TypeMeta::Static { zero_copy: true }` types.
                ///
                /// In this case we do not need to drop items individually, as
                /// the container will be initialized by a single memcpy.
                struct DropGuardRawCopy<T>(*mut [MaybeUninit<T>]);
                impl<T> Drop for DropGuardRawCopy<T> {
                    #[inline]
                    fn drop(&mut self) {
                        // SAFETY:
                        // - `self.0` is a valid pointer to the container created
                        //   by `$target::into_raw`.
                        // - `drop` is only called in this drop guard, and the drop guard
                        //   is forgotten if reading succeeds.
                        let container = unsafe { $target::from_raw(self.0) };
                        drop(container);
                    }
                }

                /// Drop guard for `TypeMeta::Static { zero_copy: false } | TypeMeta::Dynamic` types.
                ///
                /// In this case we need to drop items individually, as
                /// the container will be initialized by a series of reads.
                struct DropGuardElemCopy<T> {
                    inner: ManuallyDrop<SliceDropGuard<T>>,
                    fat: *mut [MaybeUninit<T>],
                }

                impl<T> DropGuardElemCopy<T> {
                    #[inline(always)]
                    fn new(fat: *mut [MaybeUninit<T>], raw: *mut MaybeUninit<T>) -> Self {
                        Self {
                            inner: ManuallyDrop::new(SliceDropGuard::new(raw)),
                            // We need to store the fat pointer to deallocate the container.
                            fat,
                        }
                    }
                }

                impl<T> Drop for DropGuardElemCopy<T> {
                    #[inline]
                    fn drop(&mut self) {
                        // SAFETY: `ManuallyDrop::drop` is only called in this drop guard.
                        unsafe {
                            // Drop the initialized elements first.
                            ManuallyDrop::drop(&mut self.inner);
                        }

                        // SAFETY:
                        // - `self.fat` is a valid pointer to the container created with `$target::into_raw`.
                        // - `drop` is only called in this drop guard, and the drop guard is forgotten if read succeeds.
                        let container = unsafe { $target::from_raw(self.fat) };
                        drop(container);
                    }
                }

                let len = Len::read::<T::Dst>(reader)?;
                let mem = $target::<[T::Dst]>::new_uninit_slice(len);
                let fat = $target::into_raw(mem) as *mut [MaybeUninit<T::Dst>];

                match T::TYPE_META {
                    TypeMeta::Static {
                        zero_copy: true, ..
                    } => {
                        let guard = DropGuardRawCopy(fat);
                        // SAFETY: `fat` is a valid pointer to the container created with `$target::into_raw`.
                        let dst = unsafe { &mut *fat };
                        // SAFETY: T is zero-copy eligible (no invalid bit patterns, no layout requirements, no endianness checks, etc.).
                        unsafe { reader.copy_into_slice_t(dst)? };
                        mem::forget(guard);
                    }
                    TypeMeta::Static {
                        size,
                        zero_copy: false,
                    } => {
                        // SAFETY: `fat` is a valid pointer to the container created with `$target::into_raw`.
                        let raw_base = unsafe { (*fat).as_mut_ptr() };
                        let mut guard: DropGuardElemCopy<T::Dst> =
                            DropGuardElemCopy::new(fat, raw_base);

                        // SAFETY: `T::TYPE_META` specifies a static size, so `len` reads of `T::Dst`
                        // will consume `size * len` bytes, fully consuming the trusted window.
                        #[allow(clippy::arithmetic_side_effects)]
                        let reader = &mut unsafe { reader.as_trusted_for(size * len) }?;
                        for i in 0..len {
                            // SAFETY:
                            // - `raw_base` is a valid pointer to the container created with `$target::into_raw`.
                            // - The container is initialized with capacity for `len` elements, and `i` is guaranteed to be
                            //   less than `len`.
                            let slot = unsafe { &mut *raw_base.add(i) };
                            T::read(reader, slot)?;
                            guard.inner.inc_len();
                        }

                        mem::forget(guard);
                    }
                    TypeMeta::Dynamic => {
                        // SAFETY: `fat` is a valid pointer to the container created with `$target::into_raw`.
                        let raw_base = unsafe { (*fat).as_mut_ptr() };
                        let mut guard: DropGuardElemCopy<T::Dst> =
                            DropGuardElemCopy::new(fat, raw_base);

                        for i in 0..len {
                            // SAFETY:
                            // - `raw_base` is a valid pointer to the container created with `$target::into_raw`.
                            // - The container is initialized with capacity for `len` elements, and `i` is guaranteed to be
                            //   less than `len`.
                            let slot = unsafe { &mut *raw_base.add(i) };
                            T::read(reader, slot)?;
                            guard.inner.inc_len();
                        }

                        mem::forget(guard);
                    }
                }

                // SAFETY:
                // - `fat` is a valid pointer to the container created with `$target::into_raw`.
                // - the pointer memory is only deallocated in the drop guard, and the drop guard
                //   is forgotten if reading succeeds.
                let container = unsafe { $target::from_raw(fat) };
                // SAFETY: `container` is fully initialized if read succeeds.
                let container = unsafe { container.assume_init() };

                dst.write(container);
                Ok(())
            }
        }
    };
}

impl_heap_slice!(Box => AllocBox);
impl_heap_slice!(Rc => AllocRc);
impl_heap_slice!(Arc => AllocArc);

#[cfg(feature = "alloc")]
impl<T, Len> SchemaWrite for VecDeque<T, Len>
where
    Len: SeqLen,
    T: SchemaWrite,
    T::Src: Sized,
{
    type Src = collections::VecDeque<T::Src>;

    #[inline(always)]
    fn size_of(value: &Self::Src) -> WriteResult<usize> {
        size_of_elem_iter::<T, Len>(value.iter())
    }

    #[inline(always)]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        if let TypeMeta::Static {
            size,
            zero_copy: true,
        } = T::TYPE_META
        {
            #[allow(clippy::arithmetic_side_effects)]
            let needed = Len::write_bytes_needed(src.len())? + src.len() * size;
            // SAFETY: `needed` is the size of the encoded length plus the size of the items.
            // `Len::write` and `len` writes of `T::Src` will write `needed` bytes,
            // fully initializing the trusted window.
            let writer = &mut unsafe { writer.as_trusted_for(needed) }?;

            Len::write(writer, src.len())?;
            let (front, back) = src.as_slices();
            // SAFETY:
            // - `T` is zero-copy eligible (no invalid bit patterns, no layout requirements, no endianness checks, etc.).
            // - `front` and `back` are valid non-overlapping slices.
            unsafe {
                writer.write_slice_t(front)?;
                writer.write_slice_t(back)?;
            }

            writer.finish()?;

            return Ok(());
        }

        write_elem_iter::<T, Len>(writer, src.iter())
    }
}

#[cfg(feature = "alloc")]
impl<'de, T, Len> SchemaRead<'de> for VecDeque<T, Len>
where
    Len: SeqLen,
    T: SchemaRead<'de>,
{
    type Dst = collections::VecDeque<T::Dst>;

    #[inline(always)]
    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        // Leverage the contiguous read optimization of `Vec`.
        // From<Vec<T>> for VecDeque<T> is basically free.
        let vec = <Vec<T, Len>>::get(reader)?;
        dst.write(vec.into());
        Ok(())
    }
}

#[cfg(feature = "alloc")]
/// A [`BinaryHeap`](alloc::collections::BinaryHeap) with a customizable length encoding.
pub struct BinaryHeap<T, Len = BincodeLen>(PhantomData<Len>, PhantomData<T>);

#[cfg(feature = "alloc")]
impl<T, Len> SchemaWrite for BinaryHeap<T, Len>
where
    Len: SeqLen,
    T: SchemaWrite,
    T::Src: Sized,
{
    type Src = collections::BinaryHeap<T::Src>;

    #[inline(always)]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        size_of_elem_slice::<T, Len>(src.as_slice())
    }

    #[inline(always)]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        write_elem_slice::<T, Len>(writer, src.as_slice())
    }
}

#[cfg(feature = "alloc")]
impl<'de, T, Len> SchemaRead<'de> for BinaryHeap<T, Len>
where
    Len: SeqLen,
    T: SchemaRead<'de>,
    T::Dst: Ord,
{
    type Dst = collections::BinaryHeap<T::Dst>;

    #[inline(always)]
    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        let vec = <Vec<T, Len>>::get(reader)?;
        // Leverage the vec impl.
        dst.write(collections::BinaryHeap::from(vec));
        Ok(())
    }
}

#[cfg(feature = "bytes")]
impl<Len> SchemaWrite for Bytes<Len>
where
    Len: SeqLen,
{
    type Src = bytes::Bytes;

    #[inline]
    #[allow(clippy::arithmetic_side_effects)]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        Ok(Len::write_bytes_needed(src.len())? + src.len())
    }

    #[inline]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        Len::write(writer, src.len())?;
        writer.write(src.as_ref())?;
        Ok(())
    }
}

#[cfg(feature = "bytes")]
impl<'de, Len> SchemaRead<'de> for Bytes<Len>
where
    Len: SeqLen,
{
    type Dst = bytes::Bytes;

    #[inline]
    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        let len = Len::read::<u8>(reader)?;
        let bytes = reader.fill_exact(len)?.to_vec();
        unsafe { reader.consume_unchecked(len) };
        dst.write(bytes::Bytes::from(bytes));
        Ok(())
    }
}

#[cfg(feature = "bytes")]
impl<Len> SchemaWrite for BytesMut<Len>
where
    Len: SeqLen,
{
    type Src = bytes::BytesMut;

    #[inline]
    #[allow(clippy::arithmetic_side_effects)]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        Ok(Len::write_bytes_needed(src.len())? + src.len())
    }

    #[inline]
    fn write(writer: &mut impl Writer, src: &Self::Src) -> WriteResult<()> {
        Len::write(writer, src.len())?;
        writer.write(src.as_ref())?;
        Ok(())
    }
}

#[cfg(feature = "bytes")]
impl<'de, Len> SchemaRead<'de> for BytesMut<Len>
where
    Len: SeqLen,
{
    type Dst = bytes::BytesMut;

    #[inline]
    fn read(reader: &mut impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        let len = Len::read::<u8>(reader)?;
        let bytes = reader.fill_exact(len)?.to_vec();
        unsafe { reader.consume_unchecked(len) };
        dst.write(bytes::BytesMut::from(bytes.as_slice()));
        Ok(())
    }
}