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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! # bytecheck
//!
//! bytecheck is a type validation framework for Rust.
//!
//! For some types, creating an invalid value immediately results in undefined
//! behavior. This can cause some issues when trying to validate potentially
//! invalid bytes, as just casting the bytes to your type can technically cause
//! errors. This makes it difficult to write validation routines, because until
//! you're certain that the bytes represent valid values you cannot cast them.
//!
//! bytecheck provides a framework for performing these byte-level validations
//! and implements checks for basic types along with a derive macro to implement
//! validation for custom structs and enums.
//!
//! ## Design
//!
//! [`CheckBytes`] is at the heart of bytecheck, and does the heavy lifting of
//! verifying that some bytes represent a valid type. Implementing it can be
//! done manually or automatically with the [derive macro](macro@CheckBytes).
//!
//! ## Examples
//!
//! ```
//! use bytecheck::{CheckBytes, check_bytes, rancor::Failure};
//!
//! #[derive(CheckBytes, Debug)]
//! #[repr(C)]
//! struct Test {
//!     a: u32,
//!     b: char,
//!     c: bool,
//! }
//!
//! #[repr(C, align(4))]
//! struct Aligned<const N: usize>([u8; N]);
//!
//! macro_rules! bytes {
//!     ($($byte:literal,)*) => {
//!         (&Aligned([$($byte,)*]).0 as &[u8]).as_ptr()
//!     };
//!     ($($byte:literal),*) => {
//!         bytes!($($byte,)*)
//!     };
//! }
//!
//! // In this example, the architecture is assumed to be little-endian
//! #[cfg(target_endian = "little")]
//! unsafe {
//!     // These are valid bytes for a `Test`
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             0u8, 0u8, 0u8, 0u8,
//!             0x78u8, 0u8, 0u8, 0u8,
//!             1u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap();
//!
//!     // Changing the bytes for the u32 is OK, any bytes are a valid u32
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             42u8, 16u8, 20u8, 3u8,
//!             0x78u8, 0u8, 0u8, 0u8,
//!             1u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap();
//!
//!     // Characters outside the valid ranges are invalid
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             0u8, 0u8, 0u8, 0u8,
//!             0x00u8, 0xd8u8, 0u8, 0u8,
//!             1u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap_err();
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             0u8, 0u8, 0u8, 0u8,
//!             0x00u8, 0x00u8, 0x11u8, 0u8,
//!             1u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap_err();
//!
//!     // 0 is a valid boolean value (false) but 2 is not
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             0u8, 0u8, 0u8, 0u8,
//!             0x78u8, 0u8, 0u8, 0u8,
//!             0u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap();
//!     check_bytes::<Test, Failure>(
//!         bytes![
//!             0u8, 0u8, 0u8, 0u8,
//!             0x78u8, 0u8, 0u8, 0u8,
//!             2u8, 255u8, 255u8, 255u8,
//!         ].cast()
//!     ).unwrap_err();
//! }
//! ```
//!
//! ## Features
//!
//! - `std`: (Enabled by default) Enables standard library support.
//!
//! ## Crate support
//!
//! Some common crates need to be supported by bytecheck before an official
//! integration has been made. Support is provided by bytecheck for these
//! crates, but in the future crates should depend on bytecheck and provide
//! their own implementations. The crates that already have support provided by
//! bytecheck should work toward integrating the implementations into
//! themselves.
//!
//! Crates supported by bytecheck:
//!
//! - [`uuid`](https://docs.rs/uuid)

#![deny(
    future_incompatible,
    missing_docs,
    nonstandard_style,
    unsafe_op_in_unsafe_fn,
    unused,
    warnings,
    clippy::all,
    clippy::missing_safety_doc,
    clippy::undocumented_unsafe_blocks,
    rustdoc::broken_intra_doc_links,
    rustdoc::missing_crate_level_docs
)]
#![cfg_attr(not(feature = "std"), no_std)]

// Support for various common crates. These are primarily to get users off the
// ground and build some momentum.

// These are NOT PLANNED to remain in bytecheck for the final release. Much like
// serde, these implementations should be moved into their respective crates
// over time. Before adding support for another crate, please consider getting
// bytecheck support in the crate instead.

#[cfg(feature = "uuid")]
pub mod uuid;

#[cfg(not(feature = "simdutf8"))]
use core::str::from_utf8;
#[cfg(target_has_atomic = "8")]
use core::sync::atomic::{AtomicBool, AtomicI8, AtomicU8};
#[cfg(target_has_atomic = "16")]
use core::sync::atomic::{AtomicI16, AtomicU16};
#[cfg(target_has_atomic = "32")]
use core::sync::atomic::{AtomicI32, AtomicU32};
#[cfg(target_has_atomic = "64")]
use core::sync::atomic::{AtomicI64, AtomicU64};
use core::{
    fmt,
    marker::{PhantomData, PhantomPinned},
    mem::ManuallyDrop,
    num::{
        NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
        NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8,
    },
    ops, ptr,
};
use rancor::{Context, Contextual, Error};
#[cfg(feature = "simdutf8")]
use simdutf8::basic::from_utf8;

pub use bytecheck_derive::CheckBytes;
pub use rancor;

/// A type that can check whether a pointer points to a valid value.
///
/// `CheckBytes` can be derived with [`CheckBytes`](macro@CheckBytes) or
/// implemented manually for custom behavior.
///
/// # Safety
///
/// `check_bytes` must only return `Ok` if `value` points to a valid instance of
/// `Self`. Because `value` must always be properly aligned for `Self` and point
/// to enough bytes to represent the type, this implies that `value` may be
/// dereferenced safely.
pub unsafe trait CheckBytes<C: ?Sized, E> {
    /// Checks whether the given pointer points to a valid value within the
    /// given context.
    ///
    /// # Safety
    ///
    /// The passed pointer must be aligned and point to enough initialized bytes
    /// to represent the type.
    unsafe fn check_bytes(value: *const Self, context: &mut C)
        -> Result<(), E>;
}

/// Checks whether the given pointer points to a valid value.
///
/// # Safety
///
/// The passed pointer must be aligned and point to enough initialized bytes to
/// represent the type.
#[inline]
pub unsafe fn check_bytes<T: CheckBytes<(), E> + ?Sized, E>(
    value: *const T,
) -> Result<(), E> {
    // SAFETY: The safety conditions of `check_bytes` are the same as the safety
    // conditions of this function.
    unsafe { T::check_bytes(value, &mut ()) }
}

/// Checks whether the given pointer points to a valid value within the given
/// context.
///
/// # Safety
///
/// The passed pointer must be aligned and point to enough initialized bytes to
/// represent the type.
pub unsafe fn check_bytes_with_context<T, C, E>(
    value: *const T,
    context: &mut C,
) -> Result<(), E>
where
    T: CheckBytes<C, E> + ?Sized,
    C: ?Sized,
{
    // SAFETY: The safety conditions of `check_bytes` are the same as the safety
    // conditions of this function.
    unsafe { T::check_bytes(value, context) }
}

macro_rules! impl_primitive {
    ($type:ty) => {
        // SAFETY: All bit patterns are valid for these primitive types.
        unsafe impl<C: ?Sized, E> CheckBytes<C, E> for $type {
            #[inline]
            unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), E> {
                Ok(())
            }
        }
    };
}

macro_rules! impl_primitives {
    ($($type:ty),* $(,)?) => {
        $(
            impl_primitive!($type);
        )*
    }
}

impl_primitives! {
    (),
    i8, i16, i32, i64, i128,
    u8, u16, u32, u64, u128,
    f32, f64,
}
#[cfg(target_has_atomic = "8")]
impl_primitives!(AtomicI8, AtomicU8);
#[cfg(target_has_atomic = "16")]
impl_primitives!(AtomicI16, AtomicU16);
#[cfg(target_has_atomic = "32")]
impl_primitives!(AtomicI32, AtomicU32);
#[cfg(target_has_atomic = "64")]
impl_primitives!(AtomicI64, AtomicU64);

// SAFETY: `PhantomData` is a zero-sized type and so all bit patterns are valid.
unsafe impl<T: ?Sized, C: ?Sized, E> CheckBytes<C, E> for PhantomData<T> {
    #[inline]
    unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), E> {
        Ok(())
    }
}

// SAFETY: `PhantomPinned` is a zero-sized type and so all bit patterns are
// valid.
unsafe impl<C: ?Sized, E> CheckBytes<C, E> for PhantomPinned {
    #[inline]
    unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), E> {
        Ok(())
    }
}

// SAFETY: `ManuallyDrop<T>` is a `#[repr(transparent)]` wrapper around a `T`,
// and so `value` points to a valid `ManuallyDrop<T>` if it also points to a
// valid `T`.
unsafe impl<T, C, E> CheckBytes<C, E> for ManuallyDrop<T>
where
    T: CheckBytes<C, E> + ?Sized,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(value: *const Self, c: &mut C) -> Result<(), E> {
        let inner_ptr =
            // SAFETY: Because `ManuallyDrop<T>` is `#[repr(transparent)]`, a
            // pointer to a `ManuallyDrop<T>` is guaranteed to be the same as a
            // pointer to `T`. We can't call `.cast()` here because `T` may be
            // an unsized type.
            unsafe { core::mem::transmute::<*const Self, *const T>(value) };
        // SAFETY: The caller has guaranteed that `value` is aligned for
        // `ManuallyDrop<T>` and points to enough bytes to represent
        // `ManuallyDrop<T>`. Since `ManuallyDrop<T>` is `#[repr(transparent)]`,
        // `inner_ptr` is also aligned for `T` and points to enough bytes to
        // represent it.
        unsafe {
            T::check_bytes(inner_ptr, c)
                .context("while checking inner value of `ManuallyDrop`")
        }
    }
}

#[derive(Debug)]
struct BoolCheckError {
    byte: u8,
}

impl fmt::Display for BoolCheckError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "expected bool byte to be 0 or 1, actual was {}",
            self.byte
        )
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BoolCheckError {}

// SAFETY: A bool is a one byte value that must either be 0 or 1. `check_bytes`
// only returns `Ok` if `value` is 0 or 1.
unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for bool {
    #[inline]
    unsafe fn check_bytes(value: *const Self, _: &mut C) -> Result<(), E> {
        // SAFETY: `value` is a pointer to a `bool`, which has a size and
        // alignment of one. `u8` also has a size and alignment of one, and all
        // bit patterns are valid for `u8`. So we can cast `value` to a `u8`
        // pointer and read from it.
        let byte = unsafe { *value.cast::<u8>() };
        match byte {
            0 | 1 => Ok(()),
            _ => Err(E::new(BoolCheckError { byte })),
        }
    }
}

#[cfg(target_has_atomic = "8")]
// SAFETY: `AtomicBool` has the same ABI as `bool`, so if `value` points to a
// valid `bool` then it also points to a valid `AtomicBool`.
unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for AtomicBool {
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        // SAFETY: `AtomicBool` has the same ABI as `bool`, so a pointer that is
        // aligned for `AtomicBool` and points to enough bytes for `AtomicBool`
        // is also aligned for `bool` and points to enough bytes for `bool`.
        unsafe { bool::check_bytes(value.cast(), context) }
    }
}

// SAFETY: If `char::try_from` succeeds with the pointed-to-value, then it must
// be a valid value for `char`.
unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for char {
    #[inline]
    unsafe fn check_bytes(ptr: *const Self, _: &mut C) -> Result<(), E> {
        // SAFETY: `char` and `u32` are both four bytes, but we're not
        // guaranteed that they have the same alignment. Using `read_unaligned`
        // ensures that we can read a `u32` regardless and try to convert it to
        // a `char`.
        let value = unsafe { ptr.cast::<u32>().read_unaligned() };
        char::try_from(value).map_err(E::new)?;
        Ok(())
    }
}

#[derive(Debug)]
struct TupleIndexContext {
    index: usize,
}

impl fmt::Display for TupleIndexContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "while checking index {} of tuple", self.index)
    }
}

macro_rules! impl_tuple {
    ($($type:ident $index:tt),*) => {
        // SAFETY: A tuple is valid if all of its elements are valid, and
        // `check_bytes` only returns `Ok` when all of the elements validated
        // successfully.
        unsafe impl<$($type,)* C, E> CheckBytes<C, E> for ($($type,)*)
        where
            $($type: CheckBytes<C, E>,)*
            C: ?Sized,
            E: Contextual,
        {
            #[inline]
            #[allow(clippy::unneeded_wildcard_pattern)]
            unsafe fn check_bytes(
                value: *const Self,
                context: &mut C,
            ) -> Result<(), E> {
                $(
                    // SAFETY: The caller has guaranteed that `value` points to
                    // enough bytes for this tuple and is properly aligned, so
                    // we can create pointers to each element and check them.
                    unsafe {
                        <$type>::check_bytes(
                            ptr::addr_of!((*value).$index),
                            context,
                        ).with_context(|| TupleIndexContext { index: $index })?;
                    }
                )*
                Ok(())
            }
        }
    }
}

impl_tuple!(T0 0);
impl_tuple!(T0 0, T1 1);
impl_tuple!(T0 0, T1 1, T2 2);
impl_tuple!(T0 0, T1 1, T2 2, T3 3);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10);
impl_tuple!(
    T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11
);
impl_tuple!(
    T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11,
    T12 12
);

#[derive(Debug)]
struct ArrayCheckContext {
    index: usize,
}

impl fmt::Display for ArrayCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "while checking index '{}' of array", self.index)
    }
}

// SAFETY: `check_bytes` only returns `Ok` if each element of the array is
// valid. If each element of the array is valid then the whole array is also
// valid.
unsafe impl<T, const N: usize, C, E> CheckBytes<C, E> for [T; N]
where
    T: CheckBytes<C, E>,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        let base = value.cast::<T>();
        for index in 0..N {
            // SAFETY: The caller has guaranteed that `value` points to enough
            // bytes for this array and is properly aligned, so we can create
            // pointers to each element and check them.
            unsafe {
                T::check_bytes(base.add(index), context)
                    .with_context(|| ArrayCheckContext { index })?;
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
struct SliceCheckContext {
    index: usize,
}

impl fmt::Display for SliceCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "while checking index '{}' of slice", self.index)
    }
}

// SAFETY: `check_bytes` only returns `Ok` if each element of the slice is
// valid. If each element of the slice is valid then the whole slice is also
// valid.
unsafe impl<T, C, E> CheckBytes<C, E> for [T]
where
    T: CheckBytes<C, E>,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        let (data_address, len) = ptr_meta::PtrExt::to_raw_parts(value);
        let base = data_address.cast::<T>();
        for index in 0..len {
            // SAFETY: The caller has guaranteed that `value` points to enough
            // bytes for this slice and is properly aligned, so we can create
            // pointers to each element and check them.
            unsafe {
                T::check_bytes(base.add(index), context)
                    .with_context(|| SliceCheckContext { index })?;
            }
        }
        Ok(())
    }
}

// SAFETY: `check_bytes` only returns `Ok` if the bytes pointed to by `str` are
// valid UTF-8. If they are valid UTF-8 then the overall `str` is also valid.
unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for str {
    #[inline]
    unsafe fn check_bytes(value: *const Self, _: &mut C) -> Result<(), E> {
        let slice_ptr = value as *const [u8];
        // SAFETY: The caller has guaranteed that `value` is properly-aligned
        // and points to enough bytes for its `str`. Because a `u8` slice has
        // the same layout as a `str`, we can dereference it for UTF-8
        // validation.
        let slice = unsafe { &*slice_ptr };
        from_utf8(slice).map(|_| ()).map_err(E::new)
    }
}

#[cfg(feature = "std")]
// SAFETY: `check_bytes` only returns `Ok` when the bytes constitute a valid
// `CStr` per `CStr::from_bytes_with_nul`.
unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for std::ffi::CStr {
    #[inline]
    unsafe fn check_bytes(value: *const Self, _: &mut C) -> Result<(), E> {
        let slice_ptr = value as *const [u8];
        // SAFETY: The caller has guaranteed that `value` is properly-aligned
        // and points to enough bytes for its `CStr`. Because a `u8` slice has
        // the same layout as a `CStr`, we can dereference it for validation.
        let slice = unsafe { &*slice_ptr };
        std::ffi::CStr::from_bytes_with_nul(slice).map_err(E::new)?;
        Ok(())
    }
}

// Generic contexts used by the derive.

/// Context for errors resulting from invalid structs.
#[derive(Debug)]
pub struct StructCheckContext {
    /// The name of the struct with an invalid field.
    pub struct_name: &'static str,
    /// The name of the struct field that was invalid.
    pub field_name: &'static str,
}

impl fmt::Display for StructCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "while checking field '{}' of struct '{}'",
            self.field_name, self.struct_name
        )
    }
}

/// Context for errors resulting from invalid tuple structs.
#[derive(Debug)]
pub struct TupleStructCheckContext {
    /// The name of the tuple struct with an invalid field.
    pub tuple_struct_name: &'static str,
    /// The index of the tuple struct field that was invalid.
    pub field_index: usize,
}

impl fmt::Display for TupleStructCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "while checking field index {} of tuple struct '{}'",
            self.field_index, self.tuple_struct_name,
        )
    }
}

/// An error resulting from an invalid enum tag.
#[derive(Debug)]
pub struct InvalidEnumDiscriminantError<T> {
    /// The name of the enum with an invalid discriminant.
    pub enum_name: &'static str,
    /// The invalid value of the enum discriminant.
    pub invalid_discriminant: T,
}

impl<T: fmt::Display> fmt::Display for InvalidEnumDiscriminantError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid discriminant '{}' for enum '{}'",
            self.invalid_discriminant, self.enum_name
        )
    }
}

#[cfg(feature = "std")]
impl<T> std::error::Error for InvalidEnumDiscriminantError<T> where
    T: fmt::Debug + fmt::Display
{
}

/// Context for errors resulting from checking enum variants with named fields.
#[derive(Debug)]
pub struct NamedEnumVariantCheckContext {
    /// The name of the enum with an invalid variant.
    pub enum_name: &'static str,
    /// The name of the variant that was invalid.
    pub variant_name: &'static str,
    /// The name of the field that was invalid.
    pub field_name: &'static str,
}

impl fmt::Display for NamedEnumVariantCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "while checking field '{}' of variant '{}' of enum '{}'",
            self.field_name, self.variant_name, self.enum_name,
        )
    }
}

/// Context for errors resulting from checking enum variants with unnamed
/// fields.
#[derive(Debug)]
pub struct UnnamedEnumVariantCheckContext {
    /// The name of the enum with an invalid variant.
    pub enum_name: &'static str,
    /// The name of the variant that was invalid.
    pub variant_name: &'static str,
    /// The name of the field that was invalid.
    pub field_index: usize,
}

impl fmt::Display for UnnamedEnumVariantCheckContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "while checking field index {} of variant '{}' of enum '{}'",
            self.field_index, self.variant_name, self.enum_name,
        )
    }
}

// Range types

// SAFETY: A `Range<T>` is valid if its `start` and `end` are both valid, and
// `check_bytes` only returns `Ok` when both `start` and `end` are valid. Note
// that `Range` does not require `start` be less than `end`.
unsafe impl<T, C, E> CheckBytes<C, E> for ops::Range<T>
where
    T: CheckBytes<C, E>,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        // SAFETY: The caller has guaranteed that `value` is aligned for a
        // `Range<T>` and points to enough initialized bytes for one, so a
        // pointer projected to the `start` field will be properly aligned for
        // a `T` and point to enough initialized bytes for one too.
        unsafe {
            T::check_bytes(ptr::addr_of!((*value).start), context)
                .with_context(|| StructCheckContext {
                    struct_name: "Range",
                    field_name: "start",
                })?;
        }
        // SAFETY: Same reasoning as above, but for `end`.
        unsafe {
            T::check_bytes(ptr::addr_of!((*value).end), context).with_context(
                || StructCheckContext {
                    struct_name: "Range",
                    field_name: "end",
                },
            )?;
        }
        Ok(())
    }
}

// SAFETY: A `RangeFrom<T>` is valid if its `start` is valid, and `check_bytes`
// only returns `Ok` when its `start` is valid.
unsafe impl<T, E, C> CheckBytes<C, E> for ops::RangeFrom<T>
where
    T: CheckBytes<C, E>,
    E: Contextual,
    C: ?Sized,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        // SAFETY: The caller has guaranteed that `value` is aligned for a
        // `RangeFrom<T>` and points to enough initialized bytes for one, so a
        // pointer projected to the `start` field will be properly aligned for
        // a `T` and point to enough initialized bytes for one too.
        unsafe {
            T::check_bytes(ptr::addr_of!((*value).start), context)
                .with_context(|| StructCheckContext {
                    struct_name: "RangeFrom",
                    field_name: "start",
                })?;
        }
        Ok(())
    }
}

// SAFETY: `RangeFull` is a ZST and so every pointer to one is valid.
unsafe impl<C: ?Sized, E> CheckBytes<C, E> for ops::RangeFull {
    #[inline]
    unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), E> {
        Ok(())
    }
}

// SAFETY: A `RangeTo<T>` is valid if its `end` is valid, and `check_bytes` only
// returns `Ok` when its `end` is valid.
unsafe impl<T, C, E> CheckBytes<C, E> for ops::RangeTo<T>
where
    T: CheckBytes<C, E>,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        // SAFETY: The caller has guaranteed that `value` is aligned for a
        // `RangeTo<T>` and points to enough initialized bytes for one, so a
        // pointer projected to the `end` field will be properly aligned for
        // a `T` and point to enough initialized bytes for one too.
        unsafe {
            T::check_bytes(ptr::addr_of!((*value).end), context).with_context(
                || StructCheckContext {
                    struct_name: "RangeTo",
                    field_name: "end",
                },
            )?;
        }
        Ok(())
    }
}

// SAFETY: A `RangeToInclusive<T>` is valid if its `end` is valid, and
// `check_bytes` only returns `Ok` when its `end` is valid.
unsafe impl<T, C, E> CheckBytes<C, E> for ops::RangeToInclusive<T>
where
    T: CheckBytes<C, E>,
    C: ?Sized,
    E: Contextual,
{
    #[inline]
    unsafe fn check_bytes(
        value: *const Self,
        context: &mut C,
    ) -> Result<(), E> {
        // SAFETY: The caller has guaranteed that `value` is aligned for a
        // `RangeToInclusive<T>` and points to enough initialized bytes for one,
        // so a pointer projected to the `end` field will be properly aligned
        // for a `T` and point to enough initialized bytes for one too.
        unsafe {
            T::check_bytes(ptr::addr_of!((*value).end), context).with_context(
                || StructCheckContext {
                    struct_name: "RangeToInclusive",
                    field_name: "end",
                },
            )?;
        }
        Ok(())
    }
}

#[derive(Debug)]
struct NonZeroCheckError;

impl fmt::Display for NonZeroCheckError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "nonzero integer is zero")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for NonZeroCheckError {}

macro_rules! impl_nonzero {
    ($nonzero:ident, $underlying:ident) => {
        // SAFETY: `check_bytes` only returns `Ok` when `value` is not zero, the
        // only validity condition for non-zero integer types.
        unsafe impl<C: ?Sized, E: Error> CheckBytes<C, E> for $nonzero {
            #[inline]
            unsafe fn check_bytes(
                value: *const Self,
                _: &mut C,
            ) -> Result<(), E> {
                // SAFETY: Non-zero integer types are guaranteed to have the
                // same ABI as their corresponding integer types. Those integers
                // have no validity requirements, so we can cast and dereference
                // value to check if it is equal to zero.
                if unsafe { *value.cast::<$underlying>() } == 0 {
                    Err(E::new(NonZeroCheckError))
                } else {
                    Ok(())
                }
            }
        }
    };
}

impl_nonzero!(NonZeroI8, i8);
impl_nonzero!(NonZeroI16, i16);
impl_nonzero!(NonZeroI32, i32);
impl_nonzero!(NonZeroI64, i64);
impl_nonzero!(NonZeroI128, i128);
impl_nonzero!(NonZeroU8, u8);
impl_nonzero!(NonZeroU16, u16);
impl_nonzero!(NonZeroU32, u32);
impl_nonzero!(NonZeroU64, u64);
impl_nonzero!(NonZeroU128, u128);