bytemuck/
lib.rs

1#![no_std]
2#![warn(missing_docs)]
3#![allow(unused_mut)]
4#![allow(clippy::match_like_matches_macro)]
5#![allow(clippy::uninlined_format_args)]
6#![allow(clippy::result_unit_err)]
7#![allow(clippy::type_complexity)]
8#![allow(clippy::manual_is_multiple_of)]
9#![cfg_attr(feature = "nightly_docs", feature(doc_cfg))]
10#![cfg_attr(feature = "nightly_portable_simd", feature(portable_simd))]
11#![cfg_attr(feature = "nightly_float", feature(f16, f128))]
12
13//! This crate gives small utilities for casting between plain data types.
14//!
15//! ## Basics
16//!
17//! Data comes in five basic forms in Rust, so we have five basic casting
18//! functions:
19//!
20//! * `T` uses [`cast`]
21//! * `&T` uses [`cast_ref`]
22//! * `&mut T` uses [`cast_mut`]
23//! * `&[T]` uses [`cast_slice`]
24//! * `&mut [T]` uses [`cast_slice_mut`]
25//!
26//! Depending on the function, the [`NoUninit`] and/or [`AnyBitPattern`] traits
27//! are used to maintain memory safety.
28//!
29//! **Historical Note:** When the crate first started the [`Pod`] trait was used
30//! instead, and so you may hear people refer to that, but it has the strongest
31//! requirements and people eventually wanted the more fine-grained system, so
32//! here we are. All types that impl `Pod` have a blanket impl to also support
33//! `NoUninit` and `AnyBitPattern`. The traits unfortunately do not have a
34//! perfectly clean hierarchy for semver reasons.
35//!
36//! ## Failures
37//!
38//! Some casts will never fail, and other casts might fail.
39//!
40//! * `cast::<u32, f32>` always works (and [`f32::from_bits`]).
41//! * `cast_ref::<[u8; 4], u32>` might fail if the specific array reference
42//!   given at runtime doesn't have alignment 4.
43//!
44//! In addition to the "normal" forms of each function, which will panic on
45//! invalid input, there's also `try_` versions which will return a `Result`.
46//!
47//! If you would like to statically ensure that a cast will work at runtime you
48//! can use the `must_cast` crate feature and the `must_` casting functions. A
49//! "must cast" that can't be statically known to be valid will cause a
50//! compilation error (and sometimes a very hard to read compilation error).
51//!
52//! ## Using Your Own Types
53//!
54//! All the functions listed above are guarded by the [`Pod`] trait, which is a
55//! sub-trait of the [`Zeroable`] trait.
56//!
57//! If you enable the crate's `derive` feature then these traits can be derived
58//! on your own types. The derive macros will perform the necessary checks on
59//! your type declaration, and trigger an error if your type does not qualify.
60//!
61//! The derive macros might not cover all edge cases, and sometimes they will
62//! error when actually everything is fine. As a last resort you can impl these
63//! traits manually. However, these traits are `unsafe`, and you should
64//! carefully read the requirements before using a manual implementation.
65//!
66//! ## Cargo Features
67//!
68//! The crate supports Rust 1.34 when no features are enabled, and so there's
69//! cargo features for thing that you might consider "obvious".
70//!
71//! The cargo features **do not** promise any particular MSRV, and they may
72//! increase their MSRV in new versions.
73//!
74//! * `derive`: Provide derive macros for the various traits.
75//! * `extern_crate_alloc`: Provide utilities for `alloc` related types such as
76//!   Box and Vec.
77//! * `zeroable_maybe_uninit` and `zeroable_atomics`: Provide more [`Zeroable`]
78//!   impls.
79//! * `pod_saturating`: Provide more [`Pod`] and [`Zeroable`] impls.
80//! * `wasm_simd` and `aarch64_simd`: Support more SIMD types.
81//! * `min_const_generics`: Provides appropriate impls for arrays of all lengths
82//!   instead of just for a select list of array lengths.
83//! * `must_cast`: Provides the `must_` functions, which will compile error if
84//!   the requested cast can't be statically verified.
85//! * `const_zeroed`: Provides a const version of the `zeroed` function.
86//!
87//! ## Related Crates
88//!
89//! - [`pack1`](https://docs.rs/pack1), which contains `bytemuck`-compatible
90//!   packed little-endian, big-endian and native-endian integer and floating
91//!   point number types.
92
93#[cfg(all(target_arch = "aarch64", feature = "aarch64_simd"))]
94use core::arch::aarch64;
95#[cfg(all(target_arch = "wasm32", feature = "wasm_simd"))]
96use core::arch::wasm32;
97#[cfg(target_arch = "x86")]
98use core::arch::x86;
99#[cfg(target_arch = "x86_64")]
100use core::arch::x86_64;
101//
102use core::{
103  marker::*,
104  mem::{align_of, size_of},
105  num::*,
106  ptr::*,
107};
108
109// Used from macros to ensure we aren't using some locally defined name and
110// actually are referencing libcore. This also would allow pre-2018 edition
111// crates to use our macros, but I'm not sure how important that is.
112#[doc(hidden)]
113pub use ::core as __core;
114
115#[cfg(not(feature = "min_const_generics"))]
116macro_rules! impl_unsafe_marker_for_array {
117  ( $marker:ident , $( $n:expr ),* ) => {
118    $(unsafe impl<T> $marker for [T; $n] where T: $marker {})*
119  }
120}
121
122/// A macro to transmute between two types without requiring knowing size
123/// statically.
124macro_rules! transmute {
125  ($val:expr) => {
126    ::core::mem::transmute_copy(&::core::mem::ManuallyDrop::new($val))
127  };
128  // This arm is for use in const contexts, where the borrow required to use
129  // transmute_copy poses an issue since the compiler hedges that the type
130  // being borrowed could have interior mutability.
131  ($srcty:ty; $dstty:ty; $val:expr) => {{
132    #[repr(C)]
133    union Transmute<A, B> {
134      src: ::core::mem::ManuallyDrop<A>,
135      dst: ::core::mem::ManuallyDrop<B>,
136    }
137    ::core::mem::ManuallyDrop::into_inner(
138      Transmute::<$srcty, $dstty> { src: ::core::mem::ManuallyDrop::new($val) }
139        .dst,
140    )
141  }};
142}
143
144/// A macro to implement marker traits for various simd types.
145/// #[allow(unused)] because the impls are only compiled on relevant platforms
146/// with relevant cargo features enabled.
147#[allow(unused)]
148macro_rules! impl_unsafe_marker_for_simd {
149  ($(#[cfg($cfg_predicate:meta)])? unsafe impl $trait:ident for $platform:ident :: {}) => {};
150  ($(#[cfg($cfg_predicate:meta)])? unsafe impl $trait:ident for $platform:ident :: { $first_type:ident $(, $types:ident)* $(,)? }) => {
151    $( #[cfg($cfg_predicate)] )?
152    $( #[cfg_attr(feature = "nightly_docs", doc(cfg($cfg_predicate)))] )?
153    unsafe impl $trait for $platform::$first_type {}
154    $( #[cfg($cfg_predicate)] )? // To prevent recursion errors if nothing is going to be expanded anyway.
155    impl_unsafe_marker_for_simd!($( #[cfg($cfg_predicate)] )? unsafe impl $trait for $platform::{ $( $types ),* });
156  };
157}
158
159/// A macro for conditionally const-ifying a function.
160/// #[allow(unused)] because currently it is only used with the `must_cast` feature.
161#[allow(unused)]
162macro_rules! maybe_const_fn {
163  (
164      #[cfg($cfg_predicate:meta)]
165      $(#[$attr:meta])*
166      $vis:vis $(unsafe $($unsafe:lifetime)?)? fn $name:ident $($rest:tt)*
167  ) => {
168      #[cfg($cfg_predicate)]
169      $(#[$attr])*
170      $vis const $(unsafe $($unsafe)?)? fn $name $($rest)*
171
172      #[cfg(not($cfg_predicate))]
173      $(#[$attr])*
174      $vis $(unsafe $($unsafe)?)? fn $name $($rest)*
175    };
176}
177
178#[cfg(feature = "extern_crate_std")]
179extern crate std;
180
181#[cfg(feature = "extern_crate_alloc")]
182extern crate alloc;
183#[cfg(feature = "extern_crate_alloc")]
184#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_alloc")))]
185pub mod allocation;
186#[cfg(feature = "extern_crate_alloc")]
187pub use allocation::*;
188
189mod anybitpattern;
190pub use anybitpattern::*;
191
192pub mod checked;
193pub use checked::CheckedBitPattern;
194
195mod internal;
196
197mod zeroable;
198pub use zeroable::*;
199mod zeroable_in_option;
200pub use zeroable_in_option::*;
201
202mod pod;
203pub use pod::*;
204mod pod_in_option;
205pub use pod_in_option::*;
206
207#[cfg(feature = "must_cast")]
208mod must;
209#[cfg(feature = "must_cast")]
210#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "must_cast")))]
211pub use must::*;
212
213mod no_uninit;
214pub use no_uninit::*;
215
216mod contiguous;
217pub use contiguous::*;
218
219mod offset_of;
220// ^ no import, the module only has a macro_rules, which are cursed and don't
221// follow normal import/export rules.
222
223mod transparent;
224pub use transparent::*;
225
226// This module is just an implementation detail for the derive macros. It needs
227// to be public to be usable from the macros, but it shouldn't be considered
228// part of bytemuck's public API.
229#[cfg(feature = "derive")]
230#[doc(hidden)]
231pub mod derive;
232
233#[cfg(feature = "derive")]
234#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "derive")))]
235pub use bytemuck_derive::{
236  AnyBitPattern, ByteEq, ByteHash, CheckedBitPattern, Contiguous, NoUninit,
237  Pod, TransparentWrapper, Zeroable,
238};
239
240/// The things that can go wrong when casting between [`Pod`] data forms.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242pub enum PodCastError {
243  /// You tried to cast a reference into a reference to a type with a higher
244  /// alignment requirement but the input reference wasn't aligned.
245  TargetAlignmentGreaterAndInputNotAligned,
246  /// If the element size of a slice changes, then the output slice changes
247  /// length accordingly. If the output slice wouldn't be a whole number of
248  /// elements, then the conversion fails.
249  OutputSliceWouldHaveSlop,
250  /// When casting an individual `T`, `&T`, or `&mut T` value the
251  /// source size and destination size must be an exact match.
252  SizeMismatch,
253  /// For this type of cast the alignments must be exactly the same and they
254  /// were not so now you're sad.
255  ///
256  /// This error is generated **only** by operations that cast allocated types
257  /// (such as `Box` and `Vec`), because in that case the alignment must stay
258  /// exact.
259  AlignmentMismatch,
260}
261#[cfg(not(target_arch = "spirv"))]
262impl core::fmt::Display for PodCastError {
263  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
264    write!(f, "{:?}", self)
265  }
266}
267#[cfg(feature = "extern_crate_std")]
268#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_std")))]
269impl std::error::Error for PodCastError {}
270
271// Rust 1.81+
272#[cfg(all(feature = "impl_core_error", not(feature = "extern_crate_std")))]
273impl core::error::Error for PodCastError {}
274
275/// Re-interprets `&T` as `&[u8]`.
276///
277/// Any ZST becomes an empty slice, and in that case the pointer value of that
278/// empty slice might not match the pointer value of the input reference.
279#[inline]
280pub fn bytes_of<T: NoUninit>(t: &T) -> &[u8] {
281  unsafe { internal::bytes_of(t) }
282}
283
284/// Re-interprets `&mut T` as `&mut [u8]`.
285///
286/// Any ZST becomes an empty slice, and in that case the pointer value of that
287/// empty slice might not match the pointer value of the input reference.
288#[inline]
289pub fn bytes_of_mut<T: NoUninit + AnyBitPattern>(t: &mut T) -> &mut [u8] {
290  unsafe { internal::bytes_of_mut(t) }
291}
292
293/// Re-interprets `&[u8]` as `&T`.
294///
295/// ## Panics
296///
297/// This is like [`try_from_bytes`] but will panic on error.
298#[inline]
299#[cfg_attr(feature = "track_caller", track_caller)]
300pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
301  unsafe { internal::from_bytes(s) }
302}
303
304/// Re-interprets `&mut [u8]` as `&mut T`.
305///
306/// ## Panics
307///
308/// This is like [`try_from_bytes_mut`] but will panic on error.
309#[inline]
310#[cfg_attr(feature = "track_caller", track_caller)]
311pub fn from_bytes_mut<T: NoUninit + AnyBitPattern>(s: &mut [u8]) -> &mut T {
312  unsafe { internal::from_bytes_mut(s) }
313}
314
315/// Reads from the bytes as if they were a `T`.
316///
317/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
318/// only sizes must match.
319///
320/// ## Failure
321/// * If the `bytes` length is not equal to `size_of::<T>()`.
322#[inline]
323pub fn try_pod_read_unaligned<T: AnyBitPattern>(
324  bytes: &[u8],
325) -> Result<T, PodCastError> {
326  unsafe { internal::try_pod_read_unaligned(bytes) }
327}
328
329/// Reads the slice into a `T` value.
330///
331/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
332/// only sizes must match.
333///
334/// ## Panics
335/// * This is like `try_pod_read_unaligned` but will panic on failure.
336#[inline]
337#[cfg_attr(feature = "track_caller", track_caller)]
338pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
339  unsafe { internal::pod_read_unaligned(bytes) }
340}
341
342/// Re-interprets `&[u8]` as `&T`.
343///
344/// ## Failure
345///
346/// * If the slice isn't aligned for the new type
347/// * If the slice's length isn’t exactly the size of the new type
348#[inline]
349pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
350  unsafe { internal::try_from_bytes(s) }
351}
352
353/// Re-interprets `&mut [u8]` as `&mut T`.
354///
355/// ## Failure
356///
357/// * If the slice isn't aligned for the new type
358/// * If the slice's length isn’t exactly the size of the new type
359#[inline]
360pub fn try_from_bytes_mut<T: NoUninit + AnyBitPattern>(
361  s: &mut [u8],
362) -> Result<&mut T, PodCastError> {
363  unsafe { internal::try_from_bytes_mut(s) }
364}
365
366/// Cast `A` into `B`
367///
368/// ## Panics
369///
370/// * This is like [`try_cast`], but will panic on a size mismatch.
371#[inline]
372#[cfg_attr(feature = "track_caller", track_caller)]
373pub fn cast<A: NoUninit, B: AnyBitPattern>(a: A) -> B {
374  unsafe { internal::cast(a) }
375}
376
377/// Cast `&mut A` into `&mut B`.
378///
379/// ## Panics
380///
381/// This is [`try_cast_mut`] but will panic on error.
382#[inline]
383#[cfg_attr(feature = "track_caller", track_caller)]
384pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
385  a: &mut A,
386) -> &mut B {
387  unsafe { internal::cast_mut(a) }
388}
389
390/// Cast `&A` into `&B`.
391///
392/// ## Panics
393///
394/// This is [`try_cast_ref`] but will panic on error.
395#[inline]
396#[cfg_attr(feature = "track_caller", track_caller)]
397pub fn cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> &B {
398  unsafe { internal::cast_ref(a) }
399}
400
401/// Cast `&[A]` into `&[B]`.
402///
403/// ## Panics
404///
405/// This is [`try_cast_slice`] but will panic on error.
406#[inline]
407#[cfg_attr(feature = "track_caller", track_caller)]
408pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
409  unsafe { internal::cast_slice(a) }
410}
411
412/// Cast `&mut [A]` into `&mut [B]`.
413///
414/// ## Panics
415///
416/// This is [`try_cast_slice_mut`] but will panic on error.
417#[inline]
418#[cfg_attr(feature = "track_caller", track_caller)]
419pub fn cast_slice_mut<
420  A: NoUninit + AnyBitPattern,
421  B: NoUninit + AnyBitPattern,
422>(
423  a: &mut [A],
424) -> &mut [B] {
425  unsafe { internal::cast_slice_mut(a) }
426}
427
428/// As [`align_to`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to),
429/// but safe because of the [`Pod`] bound.
430#[inline]
431pub fn pod_align_to<T: NoUninit, U: AnyBitPattern>(
432  vals: &[T],
433) -> (&[T], &[U], &[T]) {
434  unsafe { vals.align_to::<U>() }
435}
436
437/// As [`align_to_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut),
438/// but safe because of the [`Pod`] bound.
439#[inline]
440pub fn pod_align_to_mut<
441  T: NoUninit + AnyBitPattern,
442  U: NoUninit + AnyBitPattern,
443>(
444  vals: &mut [T],
445) -> (&mut [T], &mut [U], &mut [T]) {
446  unsafe { vals.align_to_mut::<U>() }
447}
448
449/// Try to cast `A` into `B`.
450///
451/// Note that for this particular type of cast, alignment isn't a factor. The
452/// input value is semantically copied into the function and then returned to a
453/// new memory location which will have whatever the required alignment of the
454/// output type is.
455///
456/// ## Failure
457///
458/// * If the types don't have the same size this fails.
459#[inline]
460pub fn try_cast<A: NoUninit, B: AnyBitPattern>(
461  a: A,
462) -> Result<B, PodCastError> {
463  unsafe { internal::try_cast(a) }
464}
465
466/// Try to convert a `&A` into `&B`.
467///
468/// ## Failure
469///
470/// * If the reference isn't aligned in the new type
471/// * If the source type and target type aren't the same size.
472#[inline]
473pub fn try_cast_ref<A: NoUninit, B: AnyBitPattern>(
474  a: &A,
475) -> Result<&B, PodCastError> {
476  unsafe { internal::try_cast_ref(a) }
477}
478
479/// Try to convert a `&mut A` into `&mut B`.
480///
481/// As [`try_cast_ref`], but `mut`.
482#[inline]
483pub fn try_cast_mut<
484  A: NoUninit + AnyBitPattern,
485  B: NoUninit + AnyBitPattern,
486>(
487  a: &mut A,
488) -> Result<&mut B, PodCastError> {
489  unsafe { internal::try_cast_mut(a) }
490}
491
492/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
493///
494/// * `input.as_ptr() as usize == output.as_ptr() as usize`
495/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
496///
497/// ## Failure
498///
499/// * If the target type has a greater alignment requirement and the input slice
500///   isn't aligned.
501/// * If the target element type is a different size from the current element
502///   type, and the output slice wouldn't be a whole number of elements when
503///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
504///   that's a failure).
505/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
506///   and a non-ZST.
507#[inline]
508pub fn try_cast_slice<A: NoUninit, B: AnyBitPattern>(
509  a: &[A],
510) -> Result<&[B], PodCastError> {
511  unsafe { internal::try_cast_slice(a) }
512}
513
514/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
515/// length).
516///
517/// As [`try_cast_slice`], but `&mut`.
518#[inline]
519pub fn try_cast_slice_mut<
520  A: NoUninit + AnyBitPattern,
521  B: NoUninit + AnyBitPattern,
522>(
523  a: &mut [A],
524) -> Result<&mut [B], PodCastError> {
525  unsafe { internal::try_cast_slice_mut(a) }
526}
527
528/// Fill all bytes of `target` with zeroes (see [`Zeroable`]).
529///
530/// This is similar to `*target = Zeroable::zeroed()`, but guarantees that any
531/// padding bytes in `target` are zeroed as well.
532///
533/// See also [`fill_zeroes`], if you have a slice rather than a single value.
534#[inline]
535pub fn write_zeroes<T: Zeroable>(target: &mut T) {
536  struct EnsureZeroWrite<T>(*mut T);
537  impl<T> Drop for EnsureZeroWrite<T> {
538    #[inline(always)]
539    fn drop(&mut self) {
540      unsafe {
541        core::ptr::write_bytes(self.0, 0u8, 1);
542      }
543    }
544  }
545  unsafe {
546    let guard = EnsureZeroWrite(target);
547    core::ptr::drop_in_place(guard.0);
548    drop(guard);
549  }
550}
551
552/// Fill all bytes of `slice` with zeroes (see [`Zeroable`]).
553///
554/// This is similar to `slice.fill(Zeroable::zeroed())`, but guarantees that any
555/// padding bytes in `slice` are zeroed as well.
556///
557/// See also [`write_zeroes`], which zeroes all bytes of a single value rather
558/// than a slice.
559#[inline]
560pub fn fill_zeroes<T: Zeroable>(slice: &mut [T]) {
561  if core::mem::needs_drop::<T>() {
562    // If `T` needs to be dropped then we have to do this one item at a time, in
563    // case one of the intermediate drops does a panic.
564    slice.iter_mut().for_each(write_zeroes);
565  } else {
566    // Otherwise we can be really fast and just fill everything with zeros.
567    let len = slice.len();
568    unsafe { core::ptr::write_bytes(slice.as_mut_ptr(), 0u8, len) }
569  }
570}
571
572/// Same as [`Zeroable::zeroed`], but as a `const fn` const.
573#[cfg(feature = "const_zeroed")]
574#[inline]
575#[must_use]
576pub const fn zeroed<T: Zeroable>() -> T {
577  unsafe { core::mem::zeroed() }
578}