Skip to main content

zerocopy/
macros.rs

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