Skip to main content

zerocopy/
macros.rs

1// Copyright 2024 The Fuchsia Authors
2//
3// Licensed under the 2-Clause BSD License <LICENSE-BSD or
4// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
5// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
6// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
7// This file may not be copied, modified, or distributed except according to
8// those terms.
9
10/// Safely transmutes a value of one type to a value of another type of the same
11/// size.
12///
13/// This macro behaves like an invocation of this function:
14///
15/// ```ignore
16/// const fn transmute<Src, Dst>(src: Src) -> Dst
17/// where
18///     Src: IntoBytes,
19///     Dst: FromBytes,
20///     size_of::<Src>() == size_of::<Dst>(),
21/// {
22/// # /*
23///     ...
24/// # */
25/// }
26/// ```
27///
28/// However, unlike a function, this macro can only be invoked when the types of
29/// `Src` and `Dst` are completely concrete. The types `Src` and `Dst` are
30/// inferred from the calling context; they cannot be explicitly specified in
31/// the macro invocation.
32///
33/// Note that the `Src` produced by the expression `$e` will *not* be dropped.
34/// Semantically, its bits will be copied into a new value of type `Dst`, the
35/// original `Src` will be forgotten, and the value of type `Dst` will be
36/// returned.
37///
38/// # `#![allow(shrink)]`
39///
40/// If `#![allow(shrink)]` is provided, `transmute!` additionally supports
41/// transmutations that shrink the size of the value; e.g.:
42///
43/// ```
44/// # use zerocopy::transmute;
45/// let u: u32 = transmute!(#![allow(shrink)] 0u64);
46/// assert_eq!(u, 0u32);
47/// ```
48///
49/// # Examples
50///
51/// ```
52/// # use zerocopy::transmute;
53/// let one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
54///
55/// let two_dimensional: [[u8; 4]; 2] = transmute!(one_dimensional);
56///
57/// assert_eq!(two_dimensional, [[0, 1, 2, 3], [4, 5, 6, 7]]);
58/// ```
59///
60/// # Use in `const` contexts
61///
62/// This macro can be invoked in `const` contexts.
63#[macro_export]
64macro_rules! transmute {
65    // NOTE: This must be a macro (rather than a function with trait bounds)
66    // because there's no way, in a generic context, to enforce that two types
67    // have the same size. `core::mem::transmute` uses compiler magic to enforce
68    // this so long as the types are concrete.
69    (#![allow(shrink)] $e:expr) => {{
70        let mut e = $e;
71        if false {
72            // This branch, though never taken, ensures that the type of `e` is
73            // `IntoBytes` and that the type of the  outer macro invocation
74            // expression is `FromBytes`.
75
76            fn transmute<Src, Dst>(src: Src) -> Dst
77            where
78                Src: $crate::IntoBytes,
79                Dst: $crate::FromBytes,
80            {
81                let _ = src;
82                loop {}
83            }
84            loop {}
85            #[allow(unreachable_code)]
86            transmute(e)
87        } else {
88            use $crate::util::macro_util::core_reexport::mem::ManuallyDrop;
89
90            // NOTE: `repr(packed)` is important! It ensures that the size of
91            // `Transmute` won't be rounded up to accommodate `Src`'s or `Dst`'s
92            // alignment, which would break the size comparison logic below.
93            //
94            // As an example of why this is problematic, consider `Src = [u8;
95            // 5]`, `Dst = u32`. The total size of `Transmute<Src, Dst>` would
96            // be 8, and so we would reject a `[u8; 5]` to `u32` transmute as
97            // being size-increasing, which it isn't.
98            #[repr(C, packed)]
99            union Transmute<Src, Dst> {
100                src: ManuallyDrop<Src>,
101                dst: ManuallyDrop<Dst>,
102            }
103
104            // SAFETY: `Transmute` is a `repr(C)` union whose `src` field has
105            // type `ManuallyDrop<Src>`. Thus, the `src` field starts at byte
106            // offset 0 within `Transmute` [1]. `ManuallyDrop<T>` has the same
107            // layout and bit validity as `T`, so it is sound to transmute `Src`
108            // to `Transmute`.
109            //
110            // [1] https://doc.rust-lang.org/1.85.0/reference/type-layout.html#reprc-unions
111            //
112            // [2] Per https://doc.rust-lang.org/1.85.0/std/mem/struct.ManuallyDrop.html:
113            //
114            //   `ManuallyDrop<T>` is guaranteed to have the same layout and bit
115            //   validity as `T`
116            let u: Transmute<_, _> = unsafe {
117                // Clippy: We can't annotate the types; this macro is designed
118                // to infer the types from the calling context.
119                #[allow(clippy::missing_transmute_annotations)]
120                $crate::util::macro_util::core_reexport::mem::transmute(e)
121            };
122
123            if false {
124                // SAFETY: This code is never executed.
125                e = ManuallyDrop::into_inner(unsafe { u.src });
126                // Suppress the `unused_assignments` lint on the previous line.
127                let _ = e;
128                loop {}
129            } else {
130                // SAFETY: Per the safety comment on `let u` above, the `dst`
131                // field in `Transmute` starts at byte offset 0, and has the
132                // same layout and bit validity as `Dst`.
133                //
134                // Transmuting `Src` to `Transmute<Src, Dst>` above using
135                // `core::mem::transmute` ensures that `size_of::<Src>() ==
136                // size_of::<Transmute<Src, Dst>>()`. A `#[repr(C, packed)]`
137                // union has the maximum size of all of its fields [1], so this
138                // is equivalent to `size_of::<Src>() >= size_of::<Dst>()`.
139                //
140                // The outer `if`'s `false` branch ensures that `Src: IntoBytes`
141                // and `Dst: FromBytes`. This, combined with the size bound,
142                // ensures that this transmute is sound.
143                //
144                // [1] Per https://doc.rust-lang.org/1.85.0/reference/type-layout.html#reprc-unions:
145                //
146                //   The union will have a size of the maximum size of all of
147                //   its fields rounded to its alignment
148                let dst = unsafe { u.dst };
149                $crate::util::macro_util::must_use(ManuallyDrop::into_inner(dst))
150            }
151        }
152    }};
153    ($e:expr) => {{
154        let e = $e;
155        if false {
156            // This branch, though never taken, ensures that the type of `e` is
157            // `IntoBytes` and that the type of the  outer macro invocation
158            // expression is `FromBytes`.
159
160            fn transmute<Src, Dst>(src: Src) -> Dst
161            where
162                Src: $crate::IntoBytes,
163                Dst: $crate::FromBytes,
164            {
165                let _ = src;
166                loop {}
167            }
168            loop {}
169            #[allow(unreachable_code)]
170            transmute(e)
171        } else {
172            // SAFETY: `core::mem::transmute` ensures that the type of `e` and
173            // the type of this macro invocation expression have the same size.
174            // We know this transmute is safe thanks to the `IntoBytes` and
175            // `FromBytes` bounds enforced by the `false` branch.
176            let u = unsafe {
177                // Clippy: We can't annotate the types; this macro is designed
178                // to infer the types from the calling context.
179                #[allow(clippy::missing_transmute_annotations, unnecessary_transmutes)]
180                $crate::util::macro_util::core_reexport::mem::transmute(e)
181            };
182            $crate::util::macro_util::must_use(u)
183        }
184    }};
185}
186
187/// Safely transmutes a mutable or immutable reference of one type to an
188/// immutable reference of another type of the same size and compatible
189/// alignment.
190///
191/// This macro behaves like an invocation of this function:
192///
193/// ```ignore
194/// fn transmute_ref<'src, 'dst, Src, Dst>(src: &'src Src) -> &'dst Dst
195/// where
196///     'src: 'dst,
197///     Src: IntoBytes + Immutable + ?Sized,
198///     Dst: FromBytes + Immutable + ?Sized,
199///     align_of::<Src>() >= align_of::<Dst>(),
200///     size_compatible::<Src, Dst>(),
201/// {
202/// # /*
203///     ...
204/// # */
205/// }
206/// ```
207///
208/// The types `Src` and `Dst` are inferred from the calling context; they cannot
209/// be explicitly specified in the macro invocation.
210///
211/// # Size compatibility
212///
213/// `transmute_ref!` supports transmuting between `Sized` types, between unsized
214/// (i.e., `?Sized`) types, and from a `Sized` type to an unsized type. It
215/// supports any transmutation that preserves the number of bytes of the
216/// referent, even if doing so requires updating the metadata stored in an
217/// unsized "fat" reference:
218///
219/// ```
220/// # use zerocopy::transmute_ref;
221/// # use core::mem::size_of_val; // Not in the prelude on our MSRV
222/// let src: &[[u8; 2]] = &[[0, 1], [2, 3]][..];
223/// let dst: &[u8] = transmute_ref!(src);
224///
225/// assert_eq!(src.len(), 2);
226/// assert_eq!(dst.len(), 4);
227/// assert_eq!(dst, [0, 1, 2, 3]);
228/// assert_eq!(size_of_val(src), size_of_val(dst));
229/// ```
230///
231/// # Errors
232///
233/// Violations of the alignment and size compatibility checks are detected
234/// *after* the compiler performs monomorphization. This has two important
235/// consequences.
236///
237/// First, it means that generic code will *never* fail these conditions:
238///
239/// ```
240/// # use zerocopy::{transmute_ref, FromBytes, IntoBytes, Immutable};
241/// fn transmute_ref<Src, Dst>(src: &Src) -> &Dst
242/// where
243///     Src: IntoBytes + Immutable,
244///     Dst: FromBytes + Immutable,
245/// {
246///     transmute_ref!(src)
247/// }
248/// ```
249///
250/// Instead, failures will only be detected once generic code is instantiated
251/// with concrete types:
252///
253/// ```compile_fail,E0080
254/// # use zerocopy::{transmute_ref, FromBytes, IntoBytes, Immutable};
255/// #
256/// # fn transmute_ref<Src, Dst>(src: &Src) -> &Dst
257/// # where
258/// #     Src: IntoBytes + Immutable,
259/// #     Dst: FromBytes + Immutable,
260/// # {
261/// #     transmute_ref!(src)
262/// # }
263/// let src: &u16 = &0;
264/// let dst: &u8 = transmute_ref(src);
265/// ```
266///
267/// Second, the fact that violations are detected after monomorphization means
268/// that `cargo check` will usually not detect errors, even when types are
269/// concrete. Instead, `cargo build` must be used to detect such errors.
270///
271/// # Examples
272///
273/// Transmuting between `Sized` types:
274///
275/// ```
276/// # use zerocopy::transmute_ref;
277/// let one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
278///
279/// let two_dimensional: &[[u8; 4]; 2] = transmute_ref!(&one_dimensional);
280///
281/// assert_eq!(two_dimensional, &[[0, 1, 2, 3], [4, 5, 6, 7]]);
282/// ```
283///
284/// Transmuting between unsized types:
285///
286/// ```
287/// # use {zerocopy::*, zerocopy_derive::*};
288/// # type u16 = zerocopy::byteorder::native_endian::U16;
289/// # type u32 = zerocopy::byteorder::native_endian::U32;
290/// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
291/// #[repr(C)]
292/// struct SliceDst<T, U> {
293///     t: T,
294///     u: [U],
295/// }
296///
297/// type Src = SliceDst<u32, u16>;
298/// type Dst = SliceDst<u16, u8>;
299///
300/// let src = Src::ref_from_bytes(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
301/// let dst: &Dst = transmute_ref!(src);
302///
303/// assert_eq!(src.t.as_bytes(), [0, 1, 2, 3]);
304/// assert_eq!(src.u.len(), 2);
305/// assert_eq!(src.u.as_bytes(), [4, 5, 6, 7]);
306///
307/// assert_eq!(dst.t.as_bytes(), [0, 1]);
308/// assert_eq!(dst.u, [2, 3, 4, 5, 6, 7]);
309/// ```
310///
311/// # Use in `const` contexts
312///
313/// This macro can be invoked in `const` contexts only when `Src: Sized` and
314/// `Dst: Sized`.
315#[macro_export]
316macro_rules! transmute_ref {
317    ($e:expr) => {{
318        // NOTE: This must be a macro (rather than a function with trait bounds)
319        // because there's no way, in a generic context, to enforce that two
320        // types have the same size or alignment.
321
322        // Ensure that the source type is a reference or a mutable reference
323        // (note that mutable references are implicitly reborrowed here).
324        let e: &_ = $e;
325
326        #[allow(unused, clippy::diverging_sub_expression)]
327        if false {
328            // This branch, though never taken, ensures that the type of `e` is
329            // `&T` where `T: IntoBytes + Immutable`, and that the type of this
330            // macro expression is `&U` where `U: FromBytes + Immutable`.
331
332            struct AssertSrcIsIntoBytes<'a, T: ?::core::marker::Sized + $crate::IntoBytes>(&'a T);
333            struct AssertSrcIsImmutable<'a, T: ?::core::marker::Sized + $crate::Immutable>(&'a T);
334            struct AssertDstIsFromBytes<'a, U: ?::core::marker::Sized + $crate::FromBytes>(&'a U);
335            struct AssertDstIsImmutable<'a, T: ?::core::marker::Sized + $crate::Immutable>(&'a T);
336
337            let _ = AssertSrcIsIntoBytes(e);
338            let _ = AssertSrcIsImmutable(e);
339
340            if true {
341                #[allow(unused, unreachable_code)]
342                let u = AssertDstIsFromBytes(loop {});
343                u.0
344            } else {
345                #[allow(unused, unreachable_code)]
346                let u = AssertDstIsImmutable(loop {});
347                u.0
348            }
349        } else {
350            use $crate::util::macro_util::TransmuteRefDst;
351            let t = $crate::util::macro_util::Wrap::new(e);
352
353            if false {
354                // This branch exists solely to force the compiler to infer the
355                // type of `Dst` *before* it attempts to resolve the method call
356                // to `transmute_ref` in the `else` branch.
357                //
358                // Without this, if `Src` is `Sized` but `Dst` is `!Sized`, the
359                // compiler will eagerly select the inherent impl of
360                // `transmute_ref` (which requires `Dst: Sized`) because inherent
361                // methods take priority over trait methods. It does this before
362                // it realizes `Dst` is `!Sized`, leading to a compile error when
363                // it checks the bounds later.
364                //
365                // By calling this helper (which returns `&Dst`), we force `Dst`
366                // to be fully resolved. By the time it gets to the `else`
367                // branch, the compiler knows `Dst` is `!Sized`, properly
368                // disqualifies the inherent method, and falls back to the trait
369                // implementation.
370                t.transmute_ref_inference_helper()
371            } else {
372                // SAFETY: The outer `if false` branch ensures that:
373                // - `Src: IntoBytes + Immutable`
374                // - `Dst: FromBytes + Immutable`
375                unsafe {
376                    t.transmute_ref()
377                }
378            }
379        }
380    }}
381}
382
383/// Safely transmutes a mutable reference of one type to a mutable reference of
384/// another type of the same size and compatible alignment.
385///
386/// This macro behaves like an invocation of this function:
387///
388/// ```ignore
389/// const fn transmute_mut<'src, 'dst, Src, Dst>(src: &'src mut Src) -> &'dst mut Dst
390/// where
391///     'src: 'dst,
392///     Src: FromBytes + IntoBytes + ?Sized,
393///     Dst: FromBytes + IntoBytes + ?Sized,
394///     align_of::<Src>() >= align_of::<Dst>(),
395///     size_compatible::<Src, Dst>(),
396/// {
397/// # /*
398///     ...
399/// # */
400/// }
401/// ```
402///
403/// The types `Src` and `Dst` are inferred from the calling context; they cannot
404/// be explicitly specified in the macro invocation.
405///
406/// # Size compatibility
407///
408/// `transmute_mut!` supports transmuting between `Sized` types, between unsized
409/// (i.e., `?Sized`) types, and from a `Sized` type to an unsized type. It
410/// supports any transmutation that preserves the number of bytes of the
411/// referent, even if doing so requires updating the metadata stored in an
412/// unsized "fat" reference:
413///
414/// ```
415/// # use zerocopy::transmute_mut;
416/// # use core::mem::size_of_val; // Not in the prelude on our MSRV
417/// let src: &mut [[u8; 2]] = &mut [[0, 1], [2, 3]][..];
418/// let dst: &mut [u8] = transmute_mut!(src);
419///
420/// assert_eq!(dst.len(), 4);
421/// assert_eq!(dst, [0, 1, 2, 3]);
422/// let dst_size = size_of_val(dst);
423/// assert_eq!(src.len(), 2);
424/// assert_eq!(size_of_val(src), dst_size);
425/// ```
426///
427/// # Errors
428///
429/// Violations of the alignment and size compatibility checks are detected
430/// *after* the compiler performs monomorphization. This has two important
431/// consequences.
432///
433/// First, it means that generic code will *never* fail these conditions:
434///
435/// ```
436/// # use zerocopy::{transmute_mut, FromBytes, IntoBytes, Immutable};
437/// fn transmute_mut<Src, Dst>(src: &mut Src) -> &mut Dst
438/// where
439///     Src: FromBytes + IntoBytes,
440///     Dst: FromBytes + IntoBytes,
441/// {
442///     transmute_mut!(src)
443/// }
444/// ```
445///
446/// Instead, failures will only be detected once generic code is instantiated
447/// with concrete types:
448///
449/// ```compile_fail,E0080
450/// # use zerocopy::{transmute_mut, FromBytes, IntoBytes, Immutable};
451/// #
452/// # fn transmute_mut<Src, Dst>(src: &mut Src) -> &mut Dst
453/// # where
454/// #     Src: FromBytes + IntoBytes,
455/// #     Dst: FromBytes + IntoBytes,
456/// # {
457/// #     transmute_mut!(src)
458/// # }
459/// let src: &mut u16 = &mut 0;
460/// let dst: &mut u8 = transmute_mut(src);
461/// ```
462///
463/// Second, the fact that violations are detected after monomorphization means
464/// that `cargo check` will usually not detect errors, even when types are
465/// concrete. Instead, `cargo build` must be used to detect such errors.
466///
467///
468/// # Examples
469///
470/// Transmuting between `Sized` types:
471///
472/// ```
473/// # use zerocopy::transmute_mut;
474/// let mut one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
475///
476/// let two_dimensional: &mut [[u8; 4]; 2] = transmute_mut!(&mut one_dimensional);
477///
478/// assert_eq!(two_dimensional, &[[0, 1, 2, 3], [4, 5, 6, 7]]);
479///
480/// two_dimensional.reverse();
481///
482/// assert_eq!(one_dimensional, [4, 5, 6, 7, 0, 1, 2, 3]);
483/// ```
484///
485/// Transmuting between unsized types:
486///
487/// ```
488/// # use {zerocopy::*, zerocopy_derive::*};
489/// # type u16 = zerocopy::byteorder::native_endian::U16;
490/// # type u32 = zerocopy::byteorder::native_endian::U32;
491/// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
492/// #[repr(C)]
493/// struct SliceDst<T, U> {
494///     t: T,
495///     u: [U],
496/// }
497///
498/// type Src = SliceDst<u32, u16>;
499/// type Dst = SliceDst<u16, u8>;
500///
501/// let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
502/// let src = Src::mut_from_bytes(&mut bytes[..]).unwrap();
503/// let dst: &mut Dst = transmute_mut!(src);
504///
505/// assert_eq!(dst.t.as_bytes(), [0, 1]);
506/// assert_eq!(dst.u, [2, 3, 4, 5, 6, 7]);
507///
508/// assert_eq!(src.t.as_bytes(), [0, 1, 2, 3]);
509/// assert_eq!(src.u.len(), 2);
510/// assert_eq!(src.u.as_bytes(), [4, 5, 6, 7]);
511///
512/// ```
513#[macro_export]
514macro_rules! transmute_mut {
515    ($e:expr) => {{
516        // NOTE: This must be a macro (rather than a function with trait bounds)
517        // because, for backwards-compatibility on v0.8.x, we use the autoref
518        // specialization trick to dispatch to different `transmute_mut`
519        // implementations: one which doesn't require `Src: KnownLayout + Dst:
520        // KnownLayout` when `Src: Sized + Dst: Sized`, and one which requires
521        // `KnownLayout` bounds otherwise.
522
523        // Ensure that the source type is a mutable reference.
524        let e: &mut _ = $e;
525
526        #[allow(unused)]
527        use $crate::util::macro_util::TransmuteMutDst as _;
528        let t = $crate::util::macro_util::Wrap::new(e);
529        if false {
530            // This branch exists solely to force the compiler to infer the type
531            // of `Dst` *before* it attempts to resolve the method call to
532            // `transmute_mut` in the `else` branch.
533            //
534            // Without this, if `Src` is `Sized` but `Dst` is `!Sized`, the
535            // compiler will eagerly select the inherent impl of `transmute_mut`
536            // (which requires `Dst: Sized`) because inherent methods take
537            // priority over trait methods. It does this before it realizes
538            // `Dst` is `!Sized`, leading to a compile error when it checks the
539            // bounds later.
540            //
541            // By calling this helper (which returns `&mut Dst`), we force `Dst`
542            // to be fully resolved. By the time it gets to the `else` branch,
543            // the compiler knows `Dst` is `!Sized`, properly disqualifies the
544            // inherent method, and falls back to the trait implementation.
545            t.transmute_mut_inference_helper()
546        } else {
547            t.transmute_mut()
548        }
549    }}
550}
551
552/// Conditionally transmutes a value of one type to a value of another type of
553/// the same size.
554///
555/// This macro behaves like an invocation of this function:
556///
557/// ```ignore
558/// fn try_transmute<Src, Dst>(src: Src) -> Result<Dst, ValidityError<Src, Dst>>
559/// where
560///     Src: IntoBytes,
561///     Dst: TryFromBytes,
562///     size_of::<Src>() == size_of::<Dst>(),
563/// {
564/// # /*
565///     ...
566/// # */
567/// }
568/// ```
569///
570/// However, unlike a function, this macro can only be invoked when the types of
571/// `Src` and `Dst` are completely concrete. The types `Src` and `Dst` are
572/// inferred from the calling context; they cannot be explicitly specified in
573/// the macro invocation.
574///
575/// Note that the `Src` produced by the expression `$e` will *not* be dropped.
576/// Semantically, its bits will be copied into a new value of type `Dst`, the
577/// original `Src` will be forgotten, and the value of type `Dst` will be
578/// returned.
579///
580/// # Examples
581///
582/// ```
583/// # use zerocopy::*;
584/// // 0u8 → bool = false
585/// assert_eq!(try_transmute!(0u8), Ok(false));
586///
587/// // 1u8 → bool = true
588///  assert_eq!(try_transmute!(1u8), Ok(true));
589///
590/// // 2u8 → bool = error
591/// assert!(matches!(
592///     try_transmute!(2u8),
593///     Result::<bool, _>::Err(ValidityError { .. })
594/// ));
595/// ```
596#[macro_export]
597macro_rules! try_transmute {
598    ($e:expr) => {{
599        // NOTE: This must be a macro (rather than a function with trait bounds)
600        // because there's no way, in a generic context, to enforce that two
601        // types have the same size. `core::mem::transmute` uses compiler magic
602        // to enforce this so long as the types are concrete.
603
604        let e = $e;
605        if false {
606            // Check that the sizes of the source and destination types are
607            // equal.
608
609            // SAFETY: This code is never executed.
610            Ok(unsafe {
611                // Clippy: We can't annotate the types; this macro is designed
612                // to infer the types from the calling context.
613                #[allow(clippy::missing_transmute_annotations)]
614                $crate::util::macro_util::core_reexport::mem::transmute(e)
615            })
616        } else {
617            $crate::util::macro_util::try_transmute::<_, _>(e)
618        }
619    }}
620}
621
622/// Conditionally transmutes a mutable or immutable reference of one type to an
623/// immutable reference of another type of the same size and compatible
624/// alignment.
625///
626/// *Note that while the **value** of the referent is checked for validity at
627/// runtime, the **size** and **alignment** are checked at compile time. For
628/// conversions which are fallible with respect to size and alignment, see the
629/// methods on [`TryFromBytes`].*
630///
631/// This macro behaves like an invocation of this function:
632///
633/// ```ignore
634/// fn try_transmute_ref<Src, Dst>(src: &Src) -> Result<&Dst, ValidityError<&Src, Dst>>
635/// where
636///     Src: IntoBytes + Immutable + ?Sized,
637///     Dst: TryFromBytes + Immutable + ?Sized,
638///     align_of::<Src>() >= align_of::<Dst>(),
639///     size_compatible::<Src, Dst>(),
640/// {
641/// # /*
642///     ...
643/// # */
644/// }
645/// ```
646///
647/// The types `Src` and `Dst` are inferred from the calling context; they cannot
648/// be explicitly specified in the macro invocation.
649///
650/// [`TryFromBytes`]: crate::TryFromBytes
651///
652/// # Size compatibility
653///
654/// `try_transmute_ref!` supports transmuting between `Sized` types, between
655/// unsized (i.e., `?Sized`) types, and from a `Sized` type to an unsized type.
656/// It supports any transmutation that preserves the number of bytes of the
657/// referent, even if doing so requires updating the metadata stored in an
658/// unsized "fat" reference:
659///
660/// ```
661/// # use zerocopy::try_transmute_ref;
662/// # use core::mem::size_of_val; // Not in the prelude on our MSRV
663/// let src: &[[u8; 2]] = &[[0, 1], [2, 3]][..];
664/// let dst: &[u8] = try_transmute_ref!(src).unwrap();
665///
666/// assert_eq!(src.len(), 2);
667/// assert_eq!(dst.len(), 4);
668/// assert_eq!(dst, [0, 1, 2, 3]);
669/// assert_eq!(size_of_val(src), size_of_val(dst));
670/// ```
671///
672/// # Examples
673///
674/// Transmuting between `Sized` types:
675///
676/// ```
677/// # use zerocopy::*;
678/// // 0u8 → bool = false
679/// assert_eq!(try_transmute_ref!(&0u8), Ok(&false));
680///
681/// // 1u8 → bool = true
682///  assert_eq!(try_transmute_ref!(&1u8), Ok(&true));
683///
684/// // 2u8 → bool = error
685/// assert!(matches!(
686///     try_transmute_ref!(&2u8),
687///     Result::<&bool, _>::Err(ValidityError { .. })
688/// ));
689/// ```
690///
691/// Transmuting between unsized types:
692///
693/// ```
694/// # use {zerocopy::*, zerocopy_derive::*};
695/// # type u16 = zerocopy::byteorder::native_endian::U16;
696/// # type u32 = zerocopy::byteorder::native_endian::U32;
697/// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
698/// #[repr(C)]
699/// struct SliceDst<T, U> {
700///     t: T,
701///     u: [U],
702/// }
703///
704/// type Src = SliceDst<u32, u16>;
705/// type Dst = SliceDst<u16, bool>;
706///
707/// let src = Src::ref_from_bytes(&[0, 1, 0, 1, 0, 1, 0, 1]).unwrap();
708/// let dst: &Dst = try_transmute_ref!(src).unwrap();
709///
710/// assert_eq!(src.t.as_bytes(), [0, 1, 0, 1]);
711/// assert_eq!(src.u.len(), 2);
712/// assert_eq!(src.u.as_bytes(), [0, 1, 0, 1]);
713///
714/// assert_eq!(dst.t.as_bytes(), [0, 1]);
715/// assert_eq!(dst.u, [false, true, false, true, false, true]);
716/// ```
717#[macro_export]
718macro_rules! try_transmute_ref {
719    ($e:expr) => {{
720        // Ensure that the source type is a reference or a mutable reference
721        // (note that mutable references are implicitly reborrowed here).
722        let e: &_ = $e;
723
724        #[allow(unused_imports)]
725        use $crate::util::macro_util::TryTransmuteRefDst as _;
726        let t = $crate::util::macro_util::Wrap::new(e);
727        if false {
728            // This branch exists solely to force the compiler to infer the type
729            // of `Dst` *before* it attempts to resolve the method call to
730            // `try_transmute_ref` in the `else` branch.
731            //
732            // Without this, if `Src` is `Sized` but `Dst` is `!Sized`, the
733            // compiler will eagerly select the inherent impl of
734            // `try_transmute_ref` (which requires `Dst: Sized`) because
735            // inherent methods take priority over trait methods. It does this
736            // before it realizes `Dst` is `!Sized`, leading to a compile error
737            // when it checks the bounds later.
738            //
739            // By calling this helper (which returns `&Dst`), we force `Dst`
740            // to be fully resolved. By the time it gets to the `else`
741            // branch, the compiler knows `Dst` is `!Sized`, properly
742            // disqualifies the inherent method, and falls back to the trait
743            // implementation.
744            Ok(t.transmute_ref_inference_helper())
745        } else {
746            t.try_transmute_ref()
747        }
748    }}
749}
750
751/// Conditionally transmutes a mutable reference of one type to a mutable
752/// reference of another type of the same size and compatible alignment.
753///
754/// *Note that while the **value** of the referent is checked for validity at
755/// runtime, the **size** and **alignment** are checked at compile time. For
756/// conversions which are fallible with respect to size and alignment, see the
757/// methods on [`TryFromBytes`].*
758///
759/// This macro behaves like an invocation of this function:
760///
761/// ```ignore
762/// fn try_transmute_mut<Src, Dst>(src: &mut Src) -> Result<&mut Dst, ValidityError<&mut Src, Dst>>
763/// where
764///     Src: FromBytes + IntoBytes + ?Sized,
765///     Dst: TryFromBytes + IntoBytes + ?Sized,
766///     align_of::<Src>() >= align_of::<Dst>(),
767///     size_compatible::<Src, Dst>(),
768/// {
769/// # /*
770///     ...
771/// # */
772/// }
773/// ```
774///
775/// The types `Src` and `Dst` are inferred from the calling context; they cannot
776/// be explicitly specified in the macro invocation.
777///
778/// [`TryFromBytes`]: crate::TryFromBytes
779///
780/// # Size compatibility
781///
782/// `try_transmute_mut!` supports transmuting between `Sized` types, between
783/// unsized (i.e., `?Sized`) types, and from a `Sized` type to an unsized type.
784/// It supports any transmutation that preserves the number of bytes of the
785/// referent, even if doing so requires updating the metadata stored in an
786/// unsized "fat" reference:
787///
788/// ```
789/// # use zerocopy::try_transmute_mut;
790/// # use core::mem::size_of_val; // Not in the prelude on our MSRV
791/// let src: &mut [[u8; 2]] = &mut [[0, 1], [2, 3]][..];
792/// let dst: &mut [u8] = try_transmute_mut!(src).unwrap();
793///
794/// assert_eq!(dst.len(), 4);
795/// assert_eq!(dst, [0, 1, 2, 3]);
796/// let dst_size = size_of_val(dst);
797/// assert_eq!(src.len(), 2);
798/// assert_eq!(size_of_val(src), dst_size);
799/// ```
800///
801/// # Examples
802///
803/// Transmuting between `Sized` types:
804///
805/// ```
806/// # use zerocopy::*;
807/// // 0u8 → bool = false
808/// let src = &mut 0u8;
809/// assert_eq!(try_transmute_mut!(src), Ok(&mut false));
810///
811/// // 1u8 → bool = true
812/// let src = &mut 1u8;
813///  assert_eq!(try_transmute_mut!(src), Ok(&mut true));
814///
815/// // 2u8 → bool = error
816/// let src = &mut 2u8;
817/// assert!(matches!(
818///     try_transmute_mut!(src),
819///     Result::<&mut bool, _>::Err(ValidityError { .. })
820/// ));
821/// ```
822///
823/// Transmuting between unsized types:
824///
825/// ```
826/// # use {zerocopy::*, zerocopy_derive::*};
827/// # type u16 = zerocopy::byteorder::native_endian::U16;
828/// # type u32 = zerocopy::byteorder::native_endian::U32;
829/// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
830/// #[repr(C)]
831/// struct SliceDst<T, U> {
832///     t: T,
833///     u: [U],
834/// }
835///
836/// type Src = SliceDst<u32, u16>;
837/// type Dst = SliceDst<u16, bool>;
838///
839/// let mut bytes = [0, 1, 0, 1, 0, 1, 0, 1];
840/// let src = Src::mut_from_bytes(&mut bytes).unwrap();
841///
842/// assert_eq!(src.t.as_bytes(), [0, 1, 0, 1]);
843/// assert_eq!(src.u.len(), 2);
844/// assert_eq!(src.u.as_bytes(), [0, 1, 0, 1]);
845///
846/// let dst: &Dst = try_transmute_mut!(src).unwrap();
847///
848/// assert_eq!(dst.t.as_bytes(), [0, 1]);
849/// assert_eq!(dst.u, [false, true, false, true, false, true]);
850/// ```
851#[macro_export]
852macro_rules! try_transmute_mut {
853    ($e:expr) => {{
854        // Ensure that the source type is a mutable reference.
855        let e: &mut _ = $e;
856
857        #[allow(unused_imports)]
858        use $crate::util::macro_util::TryTransmuteMutDst as _;
859        let t = $crate::util::macro_util::Wrap::new(e);
860        if false {
861            // This branch exists solely to force the compiler to infer the type
862            // of `Dst` *before* it attempts to resolve the method call to
863            // `try_transmute_mut` in the `else` branch.
864            //
865            // Without this, if `Src` is `Sized` but `Dst` is `!Sized`, the
866            // compiler will eagerly select the inherent impl of
867            // `try_transmute_mut` (which requires `Dst: Sized`) because
868            // inherent methods take priority over trait methods. It does this
869            // before it realizes `Dst` is `!Sized`, leading to a compile error
870            // when it checks the bounds later.
871            //
872            // By calling this helper (which returns `&Dst`), we force `Dst`
873            // to be fully resolved. By the time it gets to the `else`
874            // branch, the compiler knows `Dst` is `!Sized`, properly
875            // disqualifies the inherent method, and falls back to the trait
876            // implementation.
877            Ok(t.transmute_mut_inference_helper())
878        } else {
879            t.try_transmute_mut()
880        }
881    }}
882}
883
884/// Includes a file and safely transmutes it to a value of an arbitrary type.
885///
886/// The file will be included as a byte array, `[u8; N]`, which will be
887/// transmuted to another type, `T`. `T` is inferred from the calling context,
888/// and must implement [`FromBytes`].
889///
890/// The file is located relative to the current file (similarly to how modules
891/// are found). The provided path is interpreted in a platform-specific way at
892/// compile time. So, for instance, an invocation with a Windows path containing
893/// backslashes `\` would not compile correctly on Unix.
894///
895/// `include_value!` is ignorant of byte order. For byte order-aware types, see
896/// the [`byteorder`] module.
897///
898/// [`FromBytes`]: crate::FromBytes
899/// [`byteorder`]: crate::byteorder
900///
901/// # Examples
902///
903/// Assume there are two files in the same directory with the following
904/// contents:
905///
906/// File `data` (no trailing newline):
907///
908/// ```text
909/// abcd
910/// ```
911///
912/// File `main.rs`:
913///
914/// ```rust
915/// use zerocopy::include_value;
916/// # macro_rules! include_value {
917/// # ($file:expr) => { zerocopy::include_value!(concat!("../testdata/include_value/", $file)) };
918/// # }
919///
920/// fn main() {
921///     let as_u32: u32 = include_value!("data");
922///     assert_eq!(as_u32, u32::from_ne_bytes([b'a', b'b', b'c', b'd']));
923///     let as_i32: i32 = include_value!("data");
924///     assert_eq!(as_i32, i32::from_ne_bytes([b'a', b'b', b'c', b'd']));
925/// }
926/// ```
927///
928/// # Use in `const` contexts
929///
930/// This macro can be invoked in `const` contexts.
931#[doc(alias("include_bytes", "include_data", "include_type"))]
932#[macro_export]
933macro_rules! include_value {
934    ($file:expr $(,)?) => {
935        $crate::transmute!(*::core::include_bytes!($file))
936    };
937}
938
939#[doc(hidden)]
940#[macro_export]
941macro_rules! cryptocorrosion_derive_traits {
942    (
943        #[repr($repr:ident)]
944        $(#[$attr:meta])*
945        $vis:vis struct $name:ident $(<$($tyvar:ident),*>)?
946        $(
947            (
948                $($tuple_field_vis:vis $tuple_field_ty:ty),*
949            );
950        )?
951
952        $(
953            {
954                $($field_vis:vis $field_name:ident: $field_ty:ty,)*
955            }
956        )?
957    ) => {
958        $crate::cryptocorrosion_derive_traits!(@assert_allowed_struct_repr #[repr($repr)]);
959
960        $(#[$attr])*
961        #[repr($repr)]
962        $vis struct $name $(<$($tyvar),*>)?
963        $(
964            (
965                $($tuple_field_vis $tuple_field_ty),*
966            );
967        )?
968
969        $(
970            {
971                $($field_vis $field_name: $field_ty,)*
972            }
973        )?
974
975        // SAFETY: See inline.
976        unsafe impl $(<$($tyvar),*>)? $crate::TryFromBytes for $name$(<$($tyvar),*>)?
977        where
978            $(
979                $($tuple_field_ty: $crate::FromBytes,)*
980            )?
981
982            $(
983                $($field_ty: $crate::FromBytes,)*
984            )?
985        {
986            #[inline]
987            fn is_bit_valid(_c: $crate::Maybe<'_, Self>) -> bool {
988                // SAFETY: This macro only accepts `#[repr(C)]` and
989                // `#[repr(transparent)]` structs, and this `impl` block
990                // requires all field types to be `FromBytes`. Thus, all
991                // initialized byte sequences constitutes valid instances of
992                // `Self`.
993                true
994            }
995
996            fn only_derive_is_allowed_to_implement_this_trait() {}
997        }
998
999        // SAFETY: This macro only accepts `#[repr(C)]` and
1000        // `#[repr(transparent)]` structs, and this `impl` block requires all
1001        // field types to be `FromBytes`, which is a sub-trait of `FromZeros`.
1002        unsafe impl $(<$($tyvar),*>)? $crate::FromZeros for $name$(<$($tyvar),*>)?
1003        where
1004            $(
1005                $($tuple_field_ty: $crate::FromBytes,)*
1006            )?
1007
1008            $(
1009                $($field_ty: $crate::FromBytes,)*
1010            )?
1011        {
1012            fn only_derive_is_allowed_to_implement_this_trait() {}
1013        }
1014
1015        // SAFETY: This macro only accepts `#[repr(C)]` and
1016        // `#[repr(transparent)]` structs, and this `impl` block requires all
1017        // field types to be `FromBytes`.
1018        unsafe impl $(<$($tyvar),*>)? $crate::FromBytes for $name$(<$($tyvar),*>)?
1019        where
1020            $(
1021                $($tuple_field_ty: $crate::FromBytes,)*
1022            )?
1023
1024            $(
1025                $($field_ty: $crate::FromBytes,)*
1026            )?
1027        {
1028            fn only_derive_is_allowed_to_implement_this_trait() {}
1029        }
1030
1031        // SAFETY: This macro only accepts `#[repr(C)]` and
1032        // `#[repr(transparent)]` structs, this `impl` block requires all field
1033        // types to be `IntoBytes`, and a padding check is used to ensures that
1034        // there are no padding bytes.
1035        unsafe impl $(<$($tyvar),*>)? $crate::IntoBytes for $name$(<$($tyvar),*>)?
1036        where
1037            $(
1038                $($tuple_field_ty: $crate::IntoBytes,)*
1039            )?
1040
1041            $(
1042                $($field_ty: $crate::IntoBytes,)*
1043            )?
1044
1045            (): $crate::util::macro_util::PaddingFree<
1046                Self,
1047                {
1048                    $crate::cryptocorrosion_derive_traits!(
1049                        @struct_padding_check #[repr($repr)]
1050                        $(($($tuple_field_ty),*))?
1051                        $({$($field_ty),*})?
1052                    )
1053                },
1054            >,
1055        {
1056            fn only_derive_is_allowed_to_implement_this_trait() {}
1057        }
1058
1059        // SAFETY: This macro only accepts `#[repr(C)]` and
1060        // `#[repr(transparent)]` structs, and this `impl` block requires all
1061        // field types to be `Immutable`.
1062        unsafe impl $(<$($tyvar),*>)? $crate::Immutable for $name$(<$($tyvar),*>)?
1063        where
1064            $(
1065                $($tuple_field_ty: $crate::Immutable,)*
1066            )?
1067
1068            $(
1069                $($field_ty: $crate::Immutable,)*
1070            )?
1071        {
1072            fn only_derive_is_allowed_to_implement_this_trait() {}
1073        }
1074    };
1075    (@assert_allowed_struct_repr #[repr(transparent)]) => {};
1076    (@assert_allowed_struct_repr #[repr(C)]) => {};
1077    (@assert_allowed_struct_repr #[$_attr:meta]) => {
1078        compile_error!("repr must be `#[repr(transparent)]` or `#[repr(C)]`");
1079    };
1080    (
1081        @struct_padding_check #[repr(transparent)]
1082        $(($($tuple_field_ty:ty),*))?
1083        $({$($field_ty:ty),*})?
1084    ) => {
1085        // SAFETY: `#[repr(transparent)]` structs cannot have the same layout as
1086        // their single non-zero-sized field, and so cannot have any padding
1087        // outside of that field.
1088        0
1089    };
1090    (
1091        @struct_padding_check #[repr(C)]
1092        $(($($tuple_field_ty:ty),*))?
1093        $({$($field_ty:ty),*})?
1094    ) => {
1095        $crate::struct_padding!(
1096            Self,
1097            [
1098                $($($tuple_field_ty),*)?
1099                $($($field_ty),*)?
1100            ]
1101        )
1102    };
1103    (
1104        #[repr(C)]
1105        $(#[$attr:meta])*
1106        $vis:vis union $name:ident {
1107            $(
1108                $field_name:ident: $field_ty:ty,
1109            )*
1110        }
1111    ) => {
1112        $(#[$attr])*
1113        #[repr(C)]
1114        $vis union $name {
1115            $(
1116                $field_name: $field_ty,
1117            )*
1118        }
1119
1120        // SAFETY: See inline.
1121        unsafe impl $crate::TryFromBytes for $name
1122        where
1123            $(
1124                $field_ty: $crate::FromBytes,
1125            )*
1126        {
1127            #[inline]
1128            fn is_bit_valid(_c: $crate::Maybe<'_, Self>) -> bool {
1129                // SAFETY: This macro only accepts `#[repr(C)]` unions, and this
1130                // `impl` block requires all field types to be `FromBytes`.
1131                // Thus, all initialized byte sequences constitutes valid
1132                // instances of `Self`.
1133                true
1134            }
1135
1136            fn only_derive_is_allowed_to_implement_this_trait() {}
1137        }
1138
1139        // SAFETY: This macro only accepts `#[repr(C)]` unions, and this `impl`
1140        // block requires all field types to be `FromBytes`, which is a
1141        // sub-trait of `FromZeros`.
1142        unsafe impl $crate::FromZeros for $name
1143        where
1144            $(
1145                $field_ty: $crate::FromBytes,
1146            )*
1147        {
1148            fn only_derive_is_allowed_to_implement_this_trait() {}
1149        }
1150
1151        // SAFETY: This macro only accepts `#[repr(C)]` unions, and this `impl`
1152        // block requires all field types to be `FromBytes`.
1153        unsafe impl $crate::FromBytes for $name
1154        where
1155            $(
1156                $field_ty: $crate::FromBytes,
1157            )*
1158        {
1159            fn only_derive_is_allowed_to_implement_this_trait() {}
1160        }
1161
1162        // SAFETY: This macro only accepts `#[repr(C)]` unions, this `impl`
1163        // block requires all field types to be `IntoBytes`, and a padding check
1164        // is used to ensures that there are no padding bytes before or after
1165        // any field.
1166        unsafe impl $crate::IntoBytes for $name
1167        where
1168            $(
1169                $field_ty: $crate::IntoBytes,
1170            )*
1171            (): $crate::util::macro_util::PaddingFree<
1172                Self,
1173                {
1174                    $crate::union_padding!(
1175                        Self,
1176                        [$($field_ty),*]
1177                    )
1178                },
1179            >,
1180        {
1181            fn only_derive_is_allowed_to_implement_this_trait() {}
1182        }
1183
1184        // SAFETY: This macro only accepts `#[repr(C)]` unions, and this `impl`
1185        // block requires all field types to be `Immutable`.
1186        unsafe impl $crate::Immutable for $name
1187        where
1188            $(
1189                $field_ty: $crate::Immutable,
1190            )*
1191        {
1192            fn only_derive_is_allowed_to_implement_this_trait() {}
1193        }
1194    };
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199    use crate::{
1200        byteorder::native_endian::{U16, U32},
1201        util::testutil::*,
1202        *,
1203    };
1204
1205    #[derive(KnownLayout, Immutable, FromBytes, IntoBytes, PartialEq, Debug)]
1206    #[repr(C)]
1207    struct SliceDst<T, U> {
1208        a: T,
1209        b: [U],
1210    }
1211
1212    #[test]
1213    fn test_transmute() {
1214        // Test that memory is transmuted as expected.
1215        let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1216        let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1217        let x: [[u8; 2]; 4] = transmute!(array_of_u8s);
1218        assert_eq!(x, array_of_arrays);
1219        let x: [u8; 8] = transmute!(array_of_arrays);
1220        assert_eq!(x, array_of_u8s);
1221
1222        // Test that memory is transmuted as expected when shrinking.
1223        let x: [[u8; 2]; 3] = transmute!(#![allow(shrink)] array_of_u8s);
1224        assert_eq!(x, [[0u8, 1], [2, 3], [4, 5]]);
1225
1226        // Test that the source expression's value is forgotten rather than
1227        // dropped.
1228        #[derive(IntoBytes)]
1229        #[repr(transparent)]
1230        struct PanicOnDrop(());
1231        impl Drop for PanicOnDrop {
1232            fn drop(&mut self) {
1233                panic!("PanicOnDrop::drop");
1234            }
1235        }
1236        #[allow(clippy::let_unit_value)]
1237        let _: () = transmute!(PanicOnDrop(()));
1238        #[allow(clippy::let_unit_value)]
1239        let _: () = transmute!(#![allow(shrink)] PanicOnDrop(()));
1240
1241        // Test that `transmute!` is legal in a const context.
1242        const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
1243        const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
1244        const X: [[u8; 2]; 4] = transmute!(ARRAY_OF_U8S);
1245        assert_eq!(X, ARRAY_OF_ARRAYS);
1246        const X_SHRINK: [[u8; 2]; 3] = transmute!(#![allow(shrink)] ARRAY_OF_U8S);
1247        assert_eq!(X_SHRINK, [[0u8, 1], [2, 3], [4, 5]]);
1248
1249        // Test that `transmute!` works with `!Immutable` types.
1250        let x: usize = transmute!(UnsafeCell::new(1usize));
1251        assert_eq!(x, 1);
1252        let x: UnsafeCell<usize> = transmute!(1usize);
1253        assert_eq!(x.into_inner(), 1);
1254        let x: UnsafeCell<isize> = transmute!(UnsafeCell::new(1usize));
1255        assert_eq!(x.into_inner(), 1);
1256    }
1257
1258    // A `Sized` type which doesn't implement `KnownLayout` (it is "not
1259    // `KnownLayout`", or `Nkl`).
1260    //
1261    // This permits us to test that `transmute_ref!` and `transmute_mut!` work
1262    // for types which are `Sized + !KnownLayout`. When we added support for
1263    // slice DSTs in #1924, this new support relied on `KnownLayout`, but we
1264    // need to make sure to remain backwards-compatible with code which uses
1265    // these macros with types which are `!KnownLayout`.
1266    #[derive(FromBytes, IntoBytes, Immutable, PartialEq, Eq, Debug)]
1267    #[repr(transparent)]
1268    struct Nkl<T>(T);
1269
1270    #[test]
1271    fn test_transmute_ref() {
1272        // Test that memory is transmuted as expected.
1273        let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1274        let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1275        let x: &[[u8; 2]; 4] = transmute_ref!(&array_of_u8s);
1276        assert_eq!(*x, array_of_arrays);
1277        let x: &[u8; 8] = transmute_ref!(&array_of_arrays);
1278        assert_eq!(*x, array_of_u8s);
1279
1280        // Test that `transmute_ref!` is legal in a const context.
1281        const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
1282        const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
1283        #[allow(clippy::redundant_static_lifetimes)]
1284        const X: &'static [[u8; 2]; 4] = transmute_ref!(&ARRAY_OF_U8S);
1285        assert_eq!(*X, ARRAY_OF_ARRAYS);
1286
1287        // Test sized -> unsized transmutation.
1288        let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1289        let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1290        let slice_of_arrays = &array_of_arrays[..];
1291        let x: &[[u8; 2]] = transmute_ref!(&array_of_u8s);
1292        assert_eq!(x, slice_of_arrays);
1293
1294        // Before 1.61.0, we can't define the `const fn transmute_ref` function
1295        // that we do on and after 1.61.0.
1296        #[cfg(no_zerocopy_generic_bounds_in_const_fn_1_61_0)]
1297        {
1298            // Test that `transmute_ref!` supports non-`KnownLayout` `Sized`
1299            // types.
1300            const ARRAY_OF_NKL_U8S: Nkl<[u8; 8]> = Nkl([0u8, 1, 2, 3, 4, 5, 6, 7]);
1301            const ARRAY_OF_NKL_ARRAYS: Nkl<[[u8; 2]; 4]> = Nkl([[0, 1], [2, 3], [4, 5], [6, 7]]);
1302            const X_NKL: &Nkl<[[u8; 2]; 4]> = transmute_ref!(&ARRAY_OF_NKL_U8S);
1303            assert_eq!(*X_NKL, ARRAY_OF_NKL_ARRAYS);
1304        }
1305
1306        #[cfg(not(no_zerocopy_generic_bounds_in_const_fn_1_61_0))]
1307        {
1308            // Call through a generic function to make sure our autoref
1309            // specialization trick works even when types are generic.
1310            const fn transmute_ref<T, U>(t: &T) -> &U
1311            where
1312                T: IntoBytes + Immutable,
1313                U: FromBytes + Immutable,
1314            {
1315                transmute_ref!(t)
1316            }
1317
1318            // Test that `transmute_ref!` supports non-`KnownLayout` `Sized`
1319            // types.
1320            const ARRAY_OF_NKL_U8S: Nkl<[u8; 8]> = Nkl([0u8, 1, 2, 3, 4, 5, 6, 7]);
1321            const ARRAY_OF_NKL_ARRAYS: Nkl<[[u8; 2]; 4]> = Nkl([[0, 1], [2, 3], [4, 5], [6, 7]]);
1322            const X_NKL: &Nkl<[[u8; 2]; 4]> = transmute_ref(&ARRAY_OF_NKL_U8S);
1323            assert_eq!(*X_NKL, ARRAY_OF_NKL_ARRAYS);
1324        }
1325
1326        // Test that `transmute_ref!` works on slice DSTs in and that memory is
1327        // transmuted as expected.
1328        let slice_dst_of_u8s =
1329            SliceDst::<U16, [u8; 2]>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1330        let slice_dst_of_u16s =
1331            SliceDst::<U16, U16>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1332        let x: &SliceDst<U16, U16> = transmute_ref!(slice_dst_of_u8s);
1333        assert_eq!(x, slice_dst_of_u16s);
1334
1335        let slice_dst_of_u8s =
1336            SliceDst::<U16, u8>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1337        let x: &[u8] = transmute_ref!(slice_dst_of_u8s);
1338        assert_eq!(x, [0, 1, 2, 3, 4, 5]);
1339
1340        let x: &[u8] = transmute_ref!(slice_dst_of_u16s);
1341        assert_eq!(x, [0, 1, 2, 3, 4, 5]);
1342
1343        let x: &[U16] = transmute_ref!(slice_dst_of_u16s);
1344        let slice_of_u16s: &[U16] = <[U16]>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1345        assert_eq!(x, slice_of_u16s);
1346
1347        // Test that transmuting from a type with larger trailing slice offset
1348        // and larger trailing slice element works.
1349        let bytes = &[0, 1, 2, 3, 4, 5, 6, 7][..];
1350        let slice_dst_big = SliceDst::<U32, U16>::ref_from_bytes(bytes).unwrap();
1351        let slice_dst_small = SliceDst::<U16, u8>::ref_from_bytes(bytes).unwrap();
1352        let x: &SliceDst<U16, u8> = transmute_ref!(slice_dst_big);
1353        assert_eq!(x, slice_dst_small);
1354
1355        // Test that it's legal to transmute a reference while shrinking the
1356        // lifetime (note that `X` has the lifetime `'static`).
1357        let x: &[u8; 8] = transmute_ref!(X);
1358        assert_eq!(*x, ARRAY_OF_U8S);
1359
1360        // Test that `transmute_ref!` supports decreasing alignment.
1361        let u = AU64(0);
1362        let array = [0, 0, 0, 0, 0, 0, 0, 0];
1363        let x: &[u8; 8] = transmute_ref!(&u);
1364        assert_eq!(*x, array);
1365
1366        // Test that a mutable reference can be turned into an immutable one.
1367        let mut x = 0u8;
1368        #[allow(clippy::useless_transmute)]
1369        let y: &u8 = transmute_ref!(&mut x);
1370        assert_eq!(*y, 0);
1371    }
1372
1373    #[test]
1374    fn test_try_transmute() {
1375        // Test that memory is transmuted with `try_transmute` as expected.
1376        let array_of_bools = [false, true, false, true, false, true, false, true];
1377        let array_of_arrays = [[0, 1], [0, 1], [0, 1], [0, 1]];
1378        let x: Result<[[u8; 2]; 4], _> = try_transmute!(array_of_bools);
1379        assert_eq!(x, Ok(array_of_arrays));
1380        let x: Result<[bool; 8], _> = try_transmute!(array_of_arrays);
1381        assert_eq!(x, Ok(array_of_bools));
1382
1383        // Test that `try_transmute!` works with `!Immutable` types.
1384        let x: Result<usize, _> = try_transmute!(UnsafeCell::new(1usize));
1385        assert_eq!(x.unwrap(), 1);
1386        let x: Result<UnsafeCell<usize>, _> = try_transmute!(1usize);
1387        assert_eq!(x.unwrap().into_inner(), 1);
1388        let x: Result<UnsafeCell<isize>, _> = try_transmute!(UnsafeCell::new(1usize));
1389        assert_eq!(x.unwrap().into_inner(), 1);
1390
1391        #[derive(FromBytes, IntoBytes, Debug, PartialEq)]
1392        #[repr(transparent)]
1393        struct PanicOnDrop<T>(T);
1394
1395        impl<T> Drop for PanicOnDrop<T> {
1396            fn drop(&mut self) {
1397                panic!("PanicOnDrop dropped");
1398            }
1399        }
1400
1401        // Since `try_transmute!` semantically moves its argument on failure,
1402        // the `PanicOnDrop` is not dropped, and thus this shouldn't panic.
1403        let x: Result<usize, _> = try_transmute!(PanicOnDrop(1usize));
1404        assert_eq!(x, Ok(1));
1405
1406        // Since `try_transmute!` semantically returns ownership of its argument
1407        // on failure, the `PanicOnDrop` is returned rather than dropped, and
1408        // thus this shouldn't panic.
1409        let y: Result<bool, _> = try_transmute!(PanicOnDrop(2u8));
1410        // We have to use `map_err` instead of comparing against
1411        // `Err(PanicOnDrop(2u8))` because the latter would create and then drop
1412        // its `PanicOnDrop` temporary, which would cause a panic.
1413        assert_eq!(y.as_ref().map_err(|p| &p.src.0), Err::<&bool, _>(&2u8));
1414        mem::forget(y);
1415    }
1416
1417    #[test]
1418    fn test_try_transmute_ref() {
1419        // Test that memory is transmuted with `try_transmute_ref` as expected.
1420        let array_of_bools = &[false, true, false, true, false, true, false, true];
1421        let array_of_arrays = &[[0, 1], [0, 1], [0, 1], [0, 1]];
1422        let x: Result<&[[u8; 2]; 4], _> = try_transmute_ref!(array_of_bools);
1423        assert_eq!(x, Ok(array_of_arrays));
1424        let x: Result<&[bool; 8], _> = try_transmute_ref!(array_of_arrays);
1425        assert_eq!(x, Ok(array_of_bools));
1426
1427        // Test that it's legal to transmute a reference while shrinking the
1428        // lifetime.
1429        {
1430            let x: Result<&[[u8; 2]; 4], _> = try_transmute_ref!(array_of_bools);
1431            assert_eq!(x, Ok(array_of_arrays));
1432        }
1433
1434        // Test that `try_transmute_ref!` supports decreasing alignment.
1435        let u = AU64(0);
1436        let array = [0u8, 0, 0, 0, 0, 0, 0, 0];
1437        let x: Result<&[u8; 8], _> = try_transmute_ref!(&u);
1438        assert_eq!(x, Ok(&array));
1439
1440        // Test that a mutable reference can be turned into an immutable one.
1441        let mut x = 0u8;
1442        #[allow(clippy::useless_transmute)]
1443        let y: Result<&u8, _> = try_transmute_ref!(&mut x);
1444        assert_eq!(y, Ok(&0));
1445
1446        // Test that sized types work which don't implement `KnownLayout`.
1447        let array_of_nkl_u8s = Nkl([0u8, 1, 2, 3, 4, 5, 6, 7]);
1448        let array_of_nkl_arrays = Nkl([[0, 1], [2, 3], [4, 5], [6, 7]]);
1449        let x: Result<&Nkl<[[u8; 2]; 4]>, _> = try_transmute_ref!(&array_of_nkl_u8s);
1450        assert_eq!(x, Ok(&array_of_nkl_arrays));
1451
1452        // Test sized -> unsized transmutation.
1453        let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1454        let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1455        let slice_of_arrays = &array_of_arrays[..];
1456        let x: Result<&[[u8; 2]], _> = try_transmute_ref!(&array_of_u8s);
1457        assert_eq!(x, Ok(slice_of_arrays));
1458
1459        // Test unsized -> unsized transmutation.
1460        let slice_dst_of_u8s =
1461            SliceDst::<U16, [u8; 2]>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1462        let slice_dst_of_u16s =
1463            SliceDst::<U16, U16>::ref_from_bytes(&[0, 1, 2, 3, 4, 5][..]).unwrap();
1464        let x: Result<&SliceDst<U16, U16>, _> = try_transmute_ref!(slice_dst_of_u8s);
1465        assert_eq!(x, Ok(slice_dst_of_u16s));
1466    }
1467
1468    #[test]
1469    fn test_try_transmute_mut() {
1470        // Test that memory is transmuted with `try_transmute_mut` as expected.
1471        let array_of_u8s = &mut [0u8, 1, 0, 1, 0, 1, 0, 1];
1472        let array_of_arrays = &mut [[0u8, 1], [0, 1], [0, 1], [0, 1]];
1473        let x: Result<&mut [[u8; 2]; 4], _> = try_transmute_mut!(array_of_u8s);
1474        assert_eq!(x, Ok(array_of_arrays));
1475
1476        let array_of_bools = &mut [false, true, false, true, false, true, false, true];
1477        let array_of_arrays = &mut [[0u8, 1], [0, 1], [0, 1], [0, 1]];
1478        let x: Result<&mut [bool; 8], _> = try_transmute_mut!(array_of_arrays);
1479        assert_eq!(x, Ok(array_of_bools));
1480
1481        // Test that it's legal to transmute a reference while shrinking the
1482        // lifetime.
1483        let array_of_bools = &mut [false, true, false, true, false, true, false, true];
1484        let array_of_arrays = &mut [[0u8, 1], [0, 1], [0, 1], [0, 1]];
1485        {
1486            let x: Result<&mut [bool; 8], _> = try_transmute_mut!(array_of_arrays);
1487            assert_eq!(x, Ok(array_of_bools));
1488        }
1489
1490        // Test that `try_transmute_mut!` supports decreasing alignment.
1491        let u = &mut AU64(0);
1492        let array = &mut [0u8, 0, 0, 0, 0, 0, 0, 0];
1493        let x: Result<&mut [u8; 8], _> = try_transmute_mut!(u);
1494        assert_eq!(x, Ok(array));
1495
1496        // Test that a mutable reference can be turned into an immutable one.
1497        let mut x = 0u8;
1498        #[allow(clippy::useless_transmute)]
1499        let y: Result<&mut u8, _> = try_transmute_mut!(&mut x);
1500        assert_eq!(y, Ok(&mut 0));
1501
1502        // Test that sized types work which don't implement `KnownLayout`.
1503        let mut array_of_nkl_u8s = Nkl([0u8, 1, 2, 3, 4, 5, 6, 7]);
1504        let mut array_of_nkl_arrays = Nkl([[0, 1], [2, 3], [4, 5], [6, 7]]);
1505        let x: Result<&mut Nkl<[[u8; 2]; 4]>, _> = try_transmute_mut!(&mut array_of_nkl_u8s);
1506        assert_eq!(x, Ok(&mut array_of_nkl_arrays));
1507
1508        // Test sized -> unsized transmutation.
1509        let mut array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1510        let mut array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1511        let slice_of_arrays = &mut array_of_arrays[..];
1512        let x: Result<&mut [[u8; 2]], _> = try_transmute_mut!(&mut array_of_u8s);
1513        assert_eq!(x, Ok(slice_of_arrays));
1514
1515        // Test unsized -> unsized transmutation.
1516        let mut bytes = [0, 1, 2, 3, 4, 5, 6];
1517        let slice_dst_of_u8s = SliceDst::<u8, [u8; 2]>::mut_from_bytes(&mut bytes[..]).unwrap();
1518        let mut bytes = [0, 1, 2, 3, 4, 5, 6];
1519        let slice_dst_of_u16s = SliceDst::<u8, U16>::mut_from_bytes(&mut bytes[..]).unwrap();
1520        let x: Result<&mut SliceDst<u8, U16>, _> = try_transmute_mut!(slice_dst_of_u8s);
1521        assert_eq!(x, Ok(slice_dst_of_u16s));
1522    }
1523
1524    #[test]
1525    fn test_transmute_mut() {
1526        // Test that memory is transmuted as expected.
1527        let mut array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1528        let mut array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1529        let x: &mut [[u8; 2]; 4] = transmute_mut!(&mut array_of_u8s);
1530        assert_eq!(*x, array_of_arrays);
1531        let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays);
1532        assert_eq!(*x, array_of_u8s);
1533
1534        {
1535            // Test that it's legal to transmute a reference while shrinking the
1536            // lifetime.
1537            let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays);
1538            assert_eq!(*x, array_of_u8s);
1539        }
1540
1541        // Test that `transmute_mut!` supports non-`KnownLayout` types.
1542        let mut array_of_u8s = Nkl([0u8, 1, 2, 3, 4, 5, 6, 7]);
1543        let mut array_of_arrays = Nkl([[0, 1], [2, 3], [4, 5], [6, 7]]);
1544        let x: &mut Nkl<[[u8; 2]; 4]> = transmute_mut!(&mut array_of_u8s);
1545        assert_eq!(*x, array_of_arrays);
1546        let x: &mut Nkl<[u8; 8]> = transmute_mut!(&mut array_of_arrays);
1547        assert_eq!(*x, array_of_u8s);
1548
1549        // Test that `transmute_mut!` supports decreasing alignment.
1550        let mut u = AU64(0);
1551        let array = [0, 0, 0, 0, 0, 0, 0, 0];
1552        let x: &[u8; 8] = transmute_mut!(&mut u);
1553        assert_eq!(*x, array);
1554
1555        // Test that a mutable reference can be turned into an immutable one.
1556        let mut x = 0u8;
1557        #[allow(clippy::useless_transmute)]
1558        let y: &u8 = transmute_mut!(&mut x);
1559        assert_eq!(*y, 0);
1560
1561        // Test that `transmute_mut!` works on slice DSTs in and that memory is
1562        // transmuted as expected.
1563        let mut bytes = [0, 1, 2, 3, 4, 5, 6];
1564        let slice_dst_of_u8s = SliceDst::<u8, [u8; 2]>::mut_from_bytes(&mut bytes[..]).unwrap();
1565        let mut bytes = [0, 1, 2, 3, 4, 5, 6];
1566        let slice_dst_of_u16s = SliceDst::<u8, U16>::mut_from_bytes(&mut bytes[..]).unwrap();
1567        let x: &mut SliceDst<u8, U16> = transmute_mut!(slice_dst_of_u8s);
1568        assert_eq!(x, slice_dst_of_u16s);
1569
1570        // Test that `transmute_mut!` works on slices that memory is transmuted
1571        // as expected.
1572        let array_of_u16s: &mut [u16] = &mut [0u16, 1, 2];
1573        let array_of_i16s: &mut [i16] = &mut [0i16, 1, 2];
1574        let x: &mut [i16] = transmute_mut!(array_of_u16s);
1575        assert_eq!(x, array_of_i16s);
1576
1577        // Test that transmuting from a type with larger trailing slice offset
1578        // and larger trailing slice element works.
1579        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
1580        let slice_dst_big = SliceDst::<U32, U16>::mut_from_bytes(&mut bytes[..]).unwrap();
1581        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
1582        let slice_dst_small = SliceDst::<U16, u8>::mut_from_bytes(&mut bytes[..]).unwrap();
1583        let x: &mut SliceDst<U16, u8> = transmute_mut!(slice_dst_big);
1584        assert_eq!(x, slice_dst_small);
1585
1586        // Test sized -> unsized transmutation.
1587        let mut array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
1588        let mut array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
1589        let slice_of_arrays = &mut array_of_arrays[..];
1590        let x: &mut [[u8; 2]] = transmute_mut!(&mut array_of_u8s);
1591        assert_eq!(x, slice_of_arrays);
1592    }
1593
1594    #[test]
1595    fn test_macros_evaluate_args_once() {
1596        let mut ctr = 0;
1597        #[allow(clippy::useless_transmute)]
1598        let _: usize = transmute!({
1599            ctr += 1;
1600            0usize
1601        });
1602        assert_eq!(ctr, 1);
1603
1604        let mut ctr = 0;
1605        let _: &usize = transmute_ref!({
1606            ctr += 1;
1607            &0usize
1608        });
1609        assert_eq!(ctr, 1);
1610
1611        let mut ctr: usize = 0;
1612        let _: &mut usize = transmute_mut!({
1613            ctr += 1;
1614            &mut ctr
1615        });
1616        assert_eq!(ctr, 1);
1617
1618        let mut ctr = 0;
1619        #[allow(clippy::useless_transmute)]
1620        let _: usize = try_transmute!({
1621            ctr += 1;
1622            0usize
1623        })
1624        .unwrap();
1625        assert_eq!(ctr, 1);
1626    }
1627
1628    #[test]
1629    fn test_include_value() {
1630        const AS_U32: u32 = include_value!("../testdata/include_value/data");
1631        assert_eq!(AS_U32, u32::from_ne_bytes([b'a', b'b', b'c', b'd']));
1632        const AS_I32: i32 = include_value!("../testdata/include_value/data");
1633        assert_eq!(AS_I32, i32::from_ne_bytes([b'a', b'b', b'c', b'd']));
1634    }
1635
1636    #[test]
1637    #[allow(non_camel_case_types, unreachable_pub, dead_code)]
1638    fn test_cryptocorrosion_derive_traits() {
1639        // Test the set of invocations added in
1640        // https://github.com/cryptocorrosion/cryptocorrosion/pull/85
1641
1642        fn assert_impls<T: FromBytes + IntoBytes + Immutable>() {}
1643
1644        cryptocorrosion_derive_traits! {
1645            #[repr(C)]
1646            #[derive(Clone, Copy)]
1647            pub union vec128_storage {
1648                d: [u32; 4],
1649                q: [u64; 2],
1650            }
1651        }
1652
1653        assert_impls::<vec128_storage>();
1654
1655        cryptocorrosion_derive_traits! {
1656            #[repr(transparent)]
1657            #[derive(Copy, Clone, Debug, PartialEq)]
1658            pub struct u32x4_generic([u32; 4]);
1659        }
1660
1661        assert_impls::<u32x4_generic>();
1662
1663        cryptocorrosion_derive_traits! {
1664            #[repr(transparent)]
1665            #[derive(Copy, Clone, Debug, PartialEq)]
1666            pub struct u64x2_generic([u64; 2]);
1667        }
1668
1669        assert_impls::<u64x2_generic>();
1670
1671        cryptocorrosion_derive_traits! {
1672            #[repr(transparent)]
1673            #[derive(Copy, Clone, Debug, PartialEq)]
1674            pub struct u128x1_generic([u128; 1]);
1675        }
1676
1677        assert_impls::<u128x1_generic>();
1678
1679        cryptocorrosion_derive_traits! {
1680            #[repr(transparent)]
1681            #[derive(Copy, Clone, Default)]
1682            #[allow(non_camel_case_types)]
1683            pub struct x2<W, G>(pub [W; 2], PhantomData<G>);
1684        }
1685
1686        enum NotZerocopy {}
1687        assert_impls::<x2<(), NotZerocopy>>();
1688
1689        cryptocorrosion_derive_traits! {
1690            #[repr(transparent)]
1691            #[derive(Copy, Clone, Default)]
1692            #[allow(non_camel_case_types)]
1693            pub struct x4<W>(pub [W; 4]);
1694        }
1695
1696        assert_impls::<x4<()>>();
1697
1698        #[cfg(feature = "simd")]
1699        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1700        {
1701            #[cfg(target_arch = "x86")]
1702            use core::arch::x86::{__m128i, __m256i};
1703            #[cfg(target_arch = "x86_64")]
1704            use core::arch::x86_64::{__m128i, __m256i};
1705
1706            cryptocorrosion_derive_traits! {
1707                #[repr(C)]
1708                #[derive(Copy, Clone)]
1709                pub struct X4(__m128i, __m128i, __m128i, __m128i);
1710            }
1711
1712            assert_impls::<X4>();
1713
1714            cryptocorrosion_derive_traits! {
1715                #[repr(C)]
1716                /// Generic wrapper for unparameterized storage of any of the
1717                /// possible impls. Converting into and out of this type should
1718                /// be essentially free, although it may be more aligned than a
1719                /// particular impl requires.
1720                #[allow(non_camel_case_types)]
1721                #[derive(Copy, Clone)]
1722                pub union vec128_storage {
1723                    u32x4: [u32; 4],
1724                    u64x2: [u64; 2],
1725                    u128x1: [u128; 1],
1726                    sse2: __m128i,
1727                }
1728            }
1729
1730            assert_impls::<vec128_storage>();
1731
1732            cryptocorrosion_derive_traits! {
1733                #[repr(transparent)]
1734                #[allow(non_camel_case_types)]
1735                #[derive(Copy, Clone)]
1736                pub struct vec<S3, S4, NI> {
1737                    x: __m128i,
1738                    s3: PhantomData<S3>,
1739                    s4: PhantomData<S4>,
1740                    ni: PhantomData<NI>,
1741                }
1742            }
1743
1744            assert_impls::<vec<NotZerocopy, NotZerocopy, NotZerocopy>>();
1745
1746            cryptocorrosion_derive_traits! {
1747                #[repr(transparent)]
1748                #[derive(Copy, Clone)]
1749                pub struct u32x4x2_avx2<NI> {
1750                    x: __m256i,
1751                    ni: PhantomData<NI>,
1752                }
1753            }
1754
1755            assert_impls::<u32x4x2_avx2<NotZerocopy>>();
1756        }
1757
1758        // Make sure that our derive works for `#[repr(C)]` structs even though
1759        // cryptocorrosion doesn't currently have any.
1760        cryptocorrosion_derive_traits! {
1761            #[repr(C)]
1762            #[derive(Copy, Clone, Debug, PartialEq)]
1763            pub struct ReprC(u8, u8, u16);
1764        }
1765    }
1766}