epserde 0.12.6

ε-serde is an ε-copy (i.e., almost zero-copy) serialization/deserialization framework
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
/*
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
 */

//! Deserialization traits and types
//!
//! [`Deserialize`] is the main deserialization trait, providing methods
//! [`Deserialize::deserialize_eps`] and [`Deserialize::deserialize_full`] which
//! implement ε-copy and full-copy deserialization, respectively. The
//! implementation of this trait is based on [`DeserInner`], which is
//! automatically derived with `#[derive(Epserde)]`.

use crate::ser::SerInner;
use crate::traits::*;
use crate::{MAGIC, MAGIC_REV, VERSION};
use core::hash::Hasher;
use core::{mem::MaybeUninit, ptr::addr_of_mut};

pub mod helpers;
pub use helpers::*;
pub mod mem_case;
pub use mem_case::*;
pub mod read;
pub use read::*;
pub mod reader_with_pos;
pub use reader_with_pos::*;
pub mod slice_with_pos;
pub use slice_with_pos::*;

#[cfg(not(feature = "std"))]
use alloc::{
    string::{String, ToString},
    vec::Vec,
};
#[cfg(feature = "std")]
use std::{io::BufReader, path::Path};

pub type Result<T> = core::result::Result<T, Error>;

/// A shorthand for the [deserialization type associated with a deserializable
/// type](DeserInner::DeserType).
pub type DeserType<'a, T> = <T as DeserInner>::DeserType<'a>;

/// A zero-sized type covariant in `T` whose private field prevents construction
/// outside this crate, making it impossible to implement
/// [`DeserInner::__check_covariance`] with a returning body without `unsafe`.
#[doc(hidden)]
pub struct CovariantProof<T>(core::marker::PhantomData<fn() -> T>);

impl<T> CovariantProof<T> {
    #[doc(hidden)]
    pub(crate) const fn new() -> Self {
        CovariantProof(core::marker::PhantomData)
    }
}

/// Calls [`DeserInner::__check_covariance`] on `T`, detecting non-returning
/// implementations at runtime.
///
/// This function can be used in custom implementations to verify field-level
/// covariance without accessing [`CovariantProof`]'s constructor. In
/// particular, it is used by the derive macro.
#[inline(always)]
pub fn __check_type_covariance<T: DeserInner>() {
    let _ = T::__check_covariance(CovariantProof::<T::DeserType<'static>>::new());
}

/// Implements [`DeserInner::__check_covariance`] for types whose
/// [`DeserType`] is directly covariant in its lifetime parameter (i.e.,
/// `{ proof }` compiles).
///
/// Use this when [`DeserType<'a>`](DeserInner::DeserType) does not involve
/// any associated-type projection, so the compiler can verify covariance
/// directly. Typical cases include types where `DeserType<'a>` is `Self`,
/// `&'a Self`, or any other concrete covariant type.
#[macro_export]
macro_rules! check_covariance {
    () => {
        #[inline(always)]
        fn __check_covariance<'__long: '__short, '__short>(
            proof: $crate::deser::CovariantProof<Self::DeserType<'__long>>,
        ) -> $crate::deser::CovariantProof<Self::DeserType<'__short>> {
            proof
        }
    };
}

/// Implements [`DeserInner::__check_covariance`] with an `unsafe` transmute for
/// types in which the compiler cannot see through associated-type projections.
///
/// The macro accepts a list of types whose covariance is verified by
/// calling [`__check_type_covariance`] on each, mirroring what the derive
/// macro does for structs and enums.
///
/// # Safety
///
/// The caller must ensure that the type itself is covariant in its type
/// parameters. The macro verifies that the [`DeserType`](DeserInner::DeserType)
/// of each listed type is covariant (via its own
/// [`__check_covariance`](crate::deser::DeserInner::__check_covariance)), but
/// the type's own covariance (e.g., `Vec`, `Box` being covariant) must be known
/// from its definition.
#[macro_export]
macro_rules! unsafe_assume_covariance {
    ($($type:ty),* $(,)?) => {
        #[allow(clippy::useless_transmute)]
        #[inline(always)]
        fn __check_covariance<'__long: '__short, '__short>(
            proof: $crate::deser::CovariantProof<Self::DeserType<'__long>>,
        ) -> $crate::deser::CovariantProof<Self::DeserType<'__short>> {
            $(
                $crate::deser::__check_type_covariance::<$type>();
            )*
            // SAFETY: see the safety documentation of this macro.
            unsafe { ::core::mem::transmute(proof) }
        }
    };
}

/// Main deserialization trait. It is separated from [`DeserInner`] to
/// avoid that the user modify its behavior, and hide internal serialization
/// methods.
///
/// It provides several convenience methods to load or map into memory
/// structures that have been previously serialized. See, for example,
/// [`Deserialize::load_full`], [`Deserialize::load_mem`], and
/// [`Deserialize::mmap`].
///
/// # Safety
///
/// All deserialization methods are unsafe.
///
/// - No validation is performed on zero-copy types. For example, by altering a
///   serialized form you can deserialize a vector of
///   [`NonZeroUsize`](core::num::NonZeroUsize) containing zeros.
/// - The code assume that the [`read_exact`](ReadNoStd::read_exact) method of
///   the backend does not read the buffer. If the method reads the buffer, it
///   will cause undefined behavior. This is a general issue with Rust as the
///   I/O traits were written before [`MaybeUninit`] was stabilized.
/// - Malicious [`TypeHash`]/[`AlignHash`] implementations maybe lead to read
///   incompatible structures using the same code, or cause undefined behavior
///   by loading data with an incorrect alignment.
/// - Memory-mapped files might be modified externally.
///
/// The first problem can be solved by traits like
/// [`FromByte`](https://docs.rs/zerocopy/latest/zerocopy/trait.FromBytes.html).
/// The second issue is a non-problem with the standard library.
///
/// The last two issues are more an issue of security than undefined behavior,
/// but that is in the eye of the beholder.
pub trait Deserialize: DeserInner {
    /// Fully deserializes a structure of this type from the given backend.
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    unsafe fn deserialize_full(backend: &mut impl ReadNoStd) -> Result<Self>;
    /// ε-copy deserializes a structure of this type from the given backend.
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    unsafe fn deserialize_eps(backend: &'_ [u8]) -> Result<Self::DeserType<'_>>;

    /// Convenience method to fully deserialize from a file.
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    #[cfg(feature = "std")]
    unsafe fn load_full(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let file = std::fs::File::open(path).map_err(Error::FileOpenError)?;
        let mut buf_reader = BufReader::new(file);
        unsafe { Self::deserialize_full(&mut buf_reader).map_err(|e| e.into()) }
    }

    /// Reads data from a reader into heap-allocated memory and ε-deserialize a
    /// data structure from it, returning a [`MemCase`] containing the data
    /// structure and the memory. Excess bytes are zeroed out.
    ///
    /// The allocated memory will have [`MemoryAlignment`] as alignment: types
    /// with a higher alignment requirement will cause an [alignment
    /// error](`Error::AlignmentError`).
    ///
    /// For a version using a file path, see [`load_mem`](Self::load_mem).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use epserde::prelude::*;
    /// let data = vec![1, 2, 3, 4, 5];
    /// let mut buffer = Vec::new();
    /// unsafe { data.serialize(&mut buffer)? };
    ///
    /// let cursor = <AlignedCursor>::from_slice(&buffer);
    /// let mem_case = unsafe { <Vec<i32>>::read_mem(cursor, buffer.len())? };
    /// assert_eq!(data, **mem_case.uncase());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    unsafe fn read_mem(mut read: impl ReadNoStd, size: usize) -> anyhow::Result<MemCase<Self>> {
        let align_to = align_of::<MemoryAlignment>();
        if align_of::<Self>() > align_to {
            return Err(Error::AlignmentError.into());
        }
        // Round up to u128 size
        let capacity = size + crate::pad_align_to(size, align_to);

        let mut uninit: MaybeUninit<MemCase<Self>> = MaybeUninit::uninit();
        let ptr = uninit.as_mut_ptr();

        // SAFETY: the entire vector will be filled with data read from the reader,
        // or with zeroes if the reader provides less data than expected.
        #[allow(invalid_value)]
        let mut aligned_vec = unsafe {
            #[cfg(not(feature = "std"))]
            let alloc_func = alloc::alloc::alloc;
            #[cfg(feature = "std")]
            let alloc_func = std::alloc::alloc;

            <Vec<MemoryAlignment>>::from_raw_parts(
                alloc_func(core::alloc::Layout::from_size_align(capacity, align_to)?)
                    as *mut MemoryAlignment,
                capacity / align_to,
                capacity / align_to,
            )
        };

        let bytes = unsafe {
            core::slice::from_raw_parts_mut(aligned_vec.as_mut_ptr() as *mut u8, capacity)
        };

        read.read_exact(&mut bytes[..size])?;
        // Fixes the last few bytes to guarantee zero-extension semantics
        // for bit vectors and full-vector initialization.
        bytes[size..].fill(0);

        // SAFETY: the vector is aligned to 64 bytes.
        let backend = MemBackend::Memory(aligned_vec.into_boxed_slice());

        // store the backend inside the MemCase
        unsafe {
            addr_of_mut!((*ptr).1).write(backend);
        }
        // deserialize the data structure
        let mem = unsafe { (*ptr).1.as_ref().unwrap() };
        let s = unsafe { Self::deserialize_eps(mem) }?;
        // write the deserialized struct in the MemCase
        unsafe {
            addr_of_mut!((*ptr).0).write(s);
        }
        // finish init
        Ok(unsafe { uninit.assume_init() })
    }

    /// Loads a file into heap-allocated memory and ε-deserialize a data
    /// structure from it, returning a [`MemCase`] containing the data structure
    /// and the memory. Excess bytes are zeroed out.
    ///
    /// The allocated memory will have [`MemoryAlignment`] as alignment: types
    /// with a higher alignment requirement will cause an [alignment
    /// error](`Error::AlignmentError`).
    ///
    /// For a version using a generic [`std::io::Read`], see
    /// [`read_mem`](Self::read_mem).
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    #[cfg(feature = "std")]
    unsafe fn load_mem(path: impl AsRef<Path>) -> anyhow::Result<MemCase<Self>> {
        let file_len = path.as_ref().metadata()?.len();
        anyhow::ensure!(
            file_len <= isize::MAX as u64,
            "File too large for the current architecture (longer than isize::MAX)"
        );
        let file_len = file_len as usize;
        let file = std::fs::File::open(path)?;
        unsafe { Self::read_mem(file, file_len) }
    }

    /// Reads data from a reader into `mmap()`-allocated memory and ε-deserialize
    /// a data structure from it, returning a [`MemCase`] containing the data
    /// structure and the memory. Excess bytes are zeroed out.
    ///
    /// The behavior of `mmap()` can be modified by passing some [`Flags`];
    /// otherwise, just pass `Flags::empty()`.
    ///
    /// For a version using a file path, see [`load_mmap`](Self::load_mmap).
    ///
    /// Requires the `mmap` feature.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[cfg(feature = "mmap")]
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # use epserde::prelude::*;
    /// # use std::io::Cursor;
    /// let data = vec![1, 2, 3, 4, 5];
    /// let mut buffer = Vec::new();
    /// unsafe { data.serialize(&mut buffer)? };
    ///
    /// let cursor = Cursor::new(&buffer);
    /// let mmap_case = unsafe { <Vec<i32>>::read_mmap(cursor, buffer.len(), Flags::empty())? };
    /// assert_eq!(data, **mmap_case.uncase());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize).
    #[cfg(feature = "mmap")]
    unsafe fn read_mmap(
        mut read: impl ReadNoStd,
        size: usize,
        flags: Flags,
    ) -> anyhow::Result<MemCase<Self>> {
        let capacity = size + crate::pad_align_to(size, 16);

        let mut uninit: MaybeUninit<MemCase<Self>> = MaybeUninit::uninit();
        let ptr = uninit.as_mut_ptr();

        let mut mmap = mmap_rs::MmapOptions::new(capacity)?
            .with_flags(flags.mmap_flags())
            .map_mut()?;
        read.read_exact(&mut mmap[..size])?;
        // Fixes the last few bytes to guarantee zero-extension semantics
        // for bit vectors.
        mmap[size..].fill(0);

        let backend = MemBackend::Mmap(mmap.make_read_only().map_err(|(_, err)| err)?);

        // store the backend inside the MemCase
        unsafe {
            addr_of_mut!((*ptr).1).write(backend);
        }
        // deserialize the data structure
        let mem = unsafe { (*ptr).1.as_ref().unwrap() };
        let s = unsafe { Self::deserialize_eps(mem) }?;
        // write the deserialized struct in the MemCase
        unsafe {
            addr_of_mut!((*ptr).0).write(s);
        }
        // finish init
        Ok(unsafe { uninit.assume_init() })
    }

    /// Loads a file into `mmap()`-allocated memory and ε-deserialize a data
    /// structure from it, returning a [`MemCase`] containing the data structure
    /// and the memory. Excess bytes are zeroed out.
    ///
    /// The behavior of `mmap()` can be modified by passing some [`Flags`];
    /// otherwise, just pass `Flags::empty()`.
    ///
    /// For a version using a generic [`std::io::Read`], see
    /// [`read_mmap`](Self::read_mmap).
    ///
    /// Requires the `mmap` feature.
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize) and [mmap's `with_file`'s
    /// documentation](mmap_rs::MmapOptions::with_file).
    #[cfg(all(feature = "mmap", feature = "std"))]
    unsafe fn load_mmap(path: impl AsRef<Path>, flags: Flags) -> anyhow::Result<MemCase<Self>> {
        let file_len = path.as_ref().metadata()?.len();
        anyhow::ensure!(
            file_len <= isize::MAX as u64,
            "File too large for the current architecture (longer than isize::MAX)"
        );
        let file_len = file_len as usize;
        let file = std::fs::File::open(path)?;
        unsafe { Self::read_mmap(file, file_len, flags) }
    }

    /// Memory maps a file and ε-deserializes a data structure from it,
    /// returning a [`MemCase`] containing the data structure and the
    /// memory mapping.
    ///
    /// The behavior of `mmap()` can be modified by passing some [`Flags`]; otherwise,
    /// just pass `Flags::empty()`.
    ///
    /// Requires the `mmap` feature.
    ///
    /// # Safety
    ///
    /// See the [trait documentation](Deserialize) and [mmap's `with_file`'s documentation](mmap_rs::MmapOptions::with_file).
    #[cfg(all(feature = "mmap", feature = "std"))]
    unsafe fn mmap(path: impl AsRef<Path>, flags: Flags) -> anyhow::Result<MemCase<Self>> {
        let file_len = path.as_ref().metadata()?.len();
        anyhow::ensure!(
            file_len <= isize::MAX as u64,
            "File too large for the current architecture (longer than isize::MAX)"
        );
        let file_len = file_len as usize;
        let file = std::fs::File::open(path)?;

        let mut uninit: MaybeUninit<MemCase<Self>> = MaybeUninit::uninit();
        let ptr = uninit.as_mut_ptr();

        let mmap = unsafe {
            mmap_rs::MmapOptions::new(file_len)?
                .with_flags(flags.mmap_flags())
                .with_file(&file, 0)
                .map()?
        };

        // store the backend inside the MemCase
        unsafe {
            addr_of_mut!((*ptr).1).write(MemBackend::Mmap(mmap));
        }

        let mmap = unsafe { (*ptr).1.as_ref().unwrap() };
        // deserialize the data structure
        let s = unsafe { Self::deserialize_eps(mmap) }?;
        // write the deserialized struct in the MemCase
        unsafe {
            addr_of_mut!((*ptr).0).write(s);
        }
        // finish init
        Ok(unsafe { uninit.assume_init() })
    }
}

/// Inner trait to implement deserialization of a type.
///
/// This trait exists to separate the user-facing [`Deserialize`] trait from the
/// low-level deserialization mechanisms of [`DeserInner::_deser_full_inner`]
/// and [`DeserInner::_deser_eps_inner`]. Moreover, it makes it possible to
/// behave slightly differently at the top of the recursion tree (e.g., to check
/// the endianness marker), and to prevent the user from modifying the methods
/// in [`Deserialize`].
///
/// The [`__check_covariance`](Self::__check_covariance) method guarantees that
/// the deserialization type associated with this type is covariant in its
/// lifetime parameter, which is necessary for the safety of the inner workings
/// of [`MemCase`].
///
/// The user should not implement this trait directly, but rather derive it.
///
/// # Safety
///
/// See [`Deserialize`].
pub trait DeserInner: Sized {
    /// The deserialization type associated with this type. It can be retrieved
    /// conveniently with the alias [`DeserType`].
    type DeserType<'a>;

    /// Internal method for checking the covariance of [`DeserType`].
    ///
    /// [`MemCase::uncase`](crate::deser::MemCase::uncase) transmutes
    /// `DeserType<'static, S>` to `DeserType<'a, S>`, which is only sound if
    /// [`DeserType`] is covariant in its lifetime parameter.
    ///
    /// This method enforces that invariant: the only safe, returning
    /// implementation is `{ proof }`, which compiles only when [`DeserType`] is
    /// covariant. This happens because
    /// [`CovariantProof<T>`](crate::deser::CovariantProof) is covariant in `T`, so an
    /// implicit coercion from `CovariantProof<DeserType<'long>>` to
    /// `CovariantProof<DeserType<'short>>` is only possible when
    /// `DeserType<'long>` is a subtype of `DeserType<'short>`, which is the
    /// definition of covariance.
    ///
    /// For structures where the compiler cannot see through associated-type
    /// projections, the body must be `unsafe { core::mem::transmute(proof) }`
    /// with a safety comment justifying covariance compositionally. The method
    /// [`__check_type_covariance`] should be called when relying on the
    /// covariance of field types, as the call will detect at runtime
    /// non-returning implementations (`todo!()`, `panic!()`,
    /// `unimplemented!()`, `loop {}`, etc.).
    ///
    /// All implementations must be `#[inline(always)]` to ensure that the
    /// covariance check has no cost.
    ///
    /// Two ready-made implementations are provided as macros:
    /// - [`check_covariance!()`]: the safe `{ proof }` body, for types
    ///   whose `DeserType` is a concrete covariant type;
    /// - [`unsafe_assume_covariance!()`]: the `unsafe` transmute body, for
    ///   generic containers that are compositionally covariant.
    fn __check_covariance<'__long: '__short, '__short>(
        proof: CovariantProof<Self::DeserType<'__long>>,
    ) -> CovariantProof<Self::DeserType<'__short>>;

    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn _deser_full_inner(backend: &mut impl ReadWithPos) -> Result<Self>;

    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn _deser_eps_inner<'a>(backend: &mut SliceWithPos<'a>) -> Result<Self::DeserType<'a>>;
}

/// Blanket implementation that prevents the user from overwriting the
/// methods in [`Deserialize`].
///
/// This implementation [checks the header](`check_header`) written
/// by the blanket implementation of [`crate::ser::Serialize`] and then delegates to
/// [`DeserInner::_deser_full_inner`] or
/// [`DeserInner::_deser_eps_inner`].
impl<T: SerInner<SerType: TypeHash + AlignHash> + DeserInner> Deserialize for T {
    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn deserialize_full(backend: &mut impl ReadNoStd) -> Result<Self> {
        let mut backend = ReaderWithPos::new(backend);
        check_header::<Self>(&mut backend)?;
        unsafe { Self::_deser_full_inner(&mut backend) }
    }

    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn deserialize_eps(backend: &'_ [u8]) -> Result<Self::DeserType<'_>> {
        let mut backend = SliceWithPos::new(backend);
        check_header::<Self>(&mut backend)?;
        unsafe { Self::_deser_eps_inner(&mut backend) }
    }
}

/// Common header check code for both ε-copy and full-copy deserialization.
///
/// Must be kept in sync with [`crate::ser::write_header`].
pub fn check_header<T: SerInner<SerType: TypeHash + AlignHash>>(
    backend: &mut impl ReadWithPos,
) -> Result<()> {
    let self_type_name = core::any::type_name::<T>().to_string();
    let self_ser_type_name = core::any::type_name::<T::SerType>().to_string();
    let mut type_hasher = xxhash_rust::xxh3::Xxh3::new();
    T::SerType::type_hash(&mut type_hasher);
    let self_type_hash = type_hasher.finish();

    let mut align_hasher = xxhash_rust::xxh3::Xxh3::new();
    let mut offset_of = 0;
    T::SerType::align_hash(&mut align_hasher, &mut offset_of);
    let self_align_hash = align_hasher.finish();

    let magic = unsafe { u64::_deser_full_inner(backend)? };
    match magic {
        MAGIC => Ok(()),
        MAGIC_REV => Err(Error::EndiannessError),
        magic => Err(Error::MagicCookieError(magic)),
    }?;

    let major = unsafe { u16::_deser_full_inner(backend)? };
    if major != VERSION.0 {
        return Err(Error::MajorVersionMismatch(major));
    }
    let minor = unsafe { u16::_deser_full_inner(backend)? };
    if minor > VERSION.1 {
        return Err(Error::MinorVersionMismatch(minor));
    };

    let usize_size = unsafe { u8::_deser_full_inner(backend)? };
    let usize_size = usize_size as usize;
    let native_usize_size = core::mem::size_of::<usize>();
    if usize_size != native_usize_size {
        return Err(Error::UsizeSizeMismatch(usize_size));
    };

    let ser_type_hash = unsafe { u64::_deser_full_inner(backend)? };
    let ser_align_hash = unsafe { u64::_deser_full_inner(backend)? };
    let ser_type_name = unsafe { String::_deser_full_inner(backend)? }.to_string();

    if ser_type_hash != self_type_hash {
        return Err(Error::WrongTypeHash {
            ser_type_name,
            ser_type_hash,
            self_type_name,
            self_ser_type_name,
            self_type_hash,
        });
    }
    if ser_align_hash != self_align_hash {
        return Err(Error::WrongAlignHash {
            ser_type_name,
            ser_align_hash,
            self_type_name,
            self_ser_type_name,
            self_align_hash,
        });
    }

    Ok(())
}

/// A helper trait that makes it possible to implement differently
/// deserialization for [`crate::traits::ZeroCopy`] and [`crate::traits::DeepCopy`] types.
/// See [`crate::traits::CopyType`] for more information.
pub trait DeserHelper<T: CopySelector> {
    type FullType;
    type DeserType<'a>;

    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn _deser_full_inner_impl(backend: &mut impl ReadWithPos) -> Result<Self::FullType>;

    /// # Safety
    ///
    /// See the documentation of [`Deserialize`].
    unsafe fn _deser_eps_inner_impl<'a>(
        backend: &mut SliceWithPos<'a>,
    ) -> Result<Self::DeserType<'a>>;
}

#[derive(thiserror::Error, Debug)]
/// Errors that can happen during deserialization.
pub enum Error {
    #[error("Error reading stats for file during ε-serde deserialization: {0}")]
    /// [`Deserialize::load_full`] could not open the provided file.
    #[cfg(feature = "std")]
    FileOpenError(std::io::Error),
    #[error("Read error during ε-serde deserialization")]
    /// The underlying reader returned an error.
    ReadError,
    /// The file is from ε-serde but the endianness is wrong.
    #[cfg_attr(
        target_endian = "big",
        error("The current arch is big-endian but the data is little-endian.")
    )]
    #[cfg_attr(
        target_endian = "little",
        error("The current arch is little-endian but the data is big-endian.")
    )]
    EndiannessError,
    #[error(
        "Alignment error. Most likely you are deserializing from a memory region with insufficient alignment."
    )]
    /// Some fields are not properly aligned.
    AlignmentError,
    #[error("Major version mismatch. Expected {major} but got {0}.", major = VERSION.0)]
    /// The file was serialized with a version of ε-serde that is not compatible.
    MajorVersionMismatch(u16),
    #[error("Minor version mismatch. Expected {minor} but got {0}.", minor = VERSION.1)]
    /// The file was serialized with a compatible, but too new version of ε-serde
    /// so we might be missing features.
    MinorVersionMismatch(u16),
    #[error("The file was serialized on an architecture where a usize has size {0}, but on the current architecture it has size {size}.", size = core::mem::size_of::<usize>())]
    /// The pointer width of the serialized file is different from the pointer
    /// width of the current architecture. For example, the file was serialized
    /// on a 64-bit machine and we are trying to deserialize it on a 32-bit
    /// machine.
    UsizeSizeMismatch(usize),
    #[error("Wrong magic cookie 0x{0:016x}. The byte stream does not come from ε-serde.")]
    /// The magic cookie is wrong. The byte sequence does not come from ε-serde.
    MagicCookieError(u64),
    #[error("Invalid tag: 0x{0:02x}")]
    /// A tag is wrong (e.g., for [`Option`]).
    InvalidTag(usize),
    #[error(
        r#"Wrong type hash
Actual: 0x{ser_type_hash:016x}; expected: 0x{self_type_hash:016x}.

The serialized type is
    '{ser_type_name}',
but the deserializable type on which the deserialization method was invoked is
    '{self_type_name}',
which has serialization type
    {self_ser_type_name}.

You are trying to deserialize a file with the wrong type. You might also be
trying to deserialize a tuple of mixed zero-copy types, which is no longer
supported since 0.8.0, an instance containing tuples, whose type hash was fixed
in 0.9.0, or an instance containing a vector or a string that was serialized
before 0.10.0."#
    )]
    /// The type hash is wrong. Probably the user is trying to deserialize a
    /// file with the wrong type.
    WrongTypeHash {
        // The name of the type that was serialized.
        ser_type_name: String,
        // The [`TypeHash`] of the type that was serialized.
        ser_type_hash: u64,
        // The name of the type on which the deserialization method was called.
        self_type_name: String,
        // The name of the serialization type of `self_type_name`.
        self_ser_type_name: String,
        // The [`TypeHash`] of the type on which the deserialization method was called.
        self_type_hash: u64,
    },
    #[error(
        r#"Wrong alignment hash
Actual: 0x{ser_align_hash:016x}; expected: 0x{self_align_hash:016x}.

The serialized type is
    '{ser_type_name}',
but the deserializable type on which the deserialization method was invoked is
    '{self_type_name}',
which has serialization type
    {self_ser_type_name}.

You might be trying to deserialize a file that was serialized on an
architecture with different alignment requirements, or some of the fields of
the type might have changed their copy type (zero or deep). You might also be
trying to deserialize an array, whose alignment hash has been fixed in 0.8.0.
It is also possible that you are trying to deserialize a file serialized before
version 0.10.0 in which repr attributes were not sorted lexicographically, or
a range in a file serialized before version 0.12.0."#
    )]
    /// The type representation hash is wrong. Probably the user is trying to
    /// deserialize a file with some zero-copy type that has different
    /// in-memory representations on the serialization arch and on the current one,
    /// usually because of alignment issues. There are also some backward-compatibility
    /// issues discussed in the error message.
    WrongAlignHash {
        // The name of the type that was serialized.
        ser_type_name: String,
        // The [`AlignHash`] of the type that was serialized.
        ser_align_hash: u64,
        // The name of the type on which the deserialization method was called.
        self_type_name: String,
        // The name of the serialization type of `self_type_name`.
        self_ser_type_name: String,
        // The [`AlignHash`] of the type on which the deserialization method was called.
        self_align_hash: u64,
    },
}