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(
273 feature = "impl_core_error",
274 not(feature = "extern_crate_std"),
275 not(target_arch = "spirv")
276))]
277impl core::error::Error for PodCastError {}
278
279/// Re-interprets `&T` as `&[u8]`.
280///
281/// Any ZST becomes an empty slice, and in that case the pointer value of that
282/// empty slice might not match the pointer value of the input reference.
283#[inline]
284pub fn bytes_of<T: NoUninit>(t: &T) -> &[u8] {
285 unsafe { internal::bytes_of(t) }
286}
287
288/// Re-interprets `&mut T` as `&mut [u8]`.
289///
290/// Any ZST becomes an empty slice, and in that case the pointer value of that
291/// empty slice might not match the pointer value of the input reference.
292#[inline]
293pub fn bytes_of_mut<T: NoUninit + AnyBitPattern>(t: &mut T) -> &mut [u8] {
294 unsafe { internal::bytes_of_mut(t) }
295}
296
297/// Re-interprets `&[u8]` as `&T`.
298///
299/// ## Panics
300///
301/// This is like [`try_from_bytes`] but will panic on error.
302#[inline]
303#[cfg_attr(feature = "track_caller", track_caller)]
304pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
305 unsafe { internal::from_bytes(s) }
306}
307
308/// Re-interprets `&mut [u8]` as `&mut T`.
309///
310/// ## Panics
311///
312/// This is like [`try_from_bytes_mut`] but will panic on error.
313#[inline]
314#[cfg_attr(feature = "track_caller", track_caller)]
315pub fn from_bytes_mut<T: NoUninit + AnyBitPattern>(s: &mut [u8]) -> &mut T {
316 unsafe { internal::from_bytes_mut(s) }
317}
318
319/// Reads from the bytes as if they were a `T`.
320///
321/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
322/// only sizes must match.
323///
324/// ## Failure
325/// * If the `bytes` length is not equal to `size_of::<T>()`.
326#[inline]
327pub fn try_pod_read_unaligned<T: AnyBitPattern>(
328 bytes: &[u8],
329) -> Result<T, PodCastError> {
330 unsafe { internal::try_pod_read_unaligned(bytes) }
331}
332
333/// Reads the slice into a `T` value.
334///
335/// Unlike [`from_bytes`], the slice doesn't need to respect alignment of `T`,
336/// only sizes must match.
337///
338/// ## Panics
339/// * This is like `try_pod_read_unaligned` but will panic on failure.
340#[inline]
341#[cfg_attr(feature = "track_caller", track_caller)]
342pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
343 unsafe { internal::pod_read_unaligned(bytes) }
344}
345
346/// Re-interprets `&[u8]` as `&T`.
347///
348/// ## Failure
349///
350/// * If the slice isn't aligned for the new type
351/// * If the slice's length isn’t exactly the size of the new type
352#[inline]
353pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
354 unsafe { internal::try_from_bytes(s) }
355}
356
357/// Re-interprets `&mut [u8]` as `&mut T`.
358///
359/// ## Failure
360///
361/// * If the slice isn't aligned for the new type
362/// * If the slice's length isn’t exactly the size of the new type
363#[inline]
364pub fn try_from_bytes_mut<T: NoUninit + AnyBitPattern>(
365 s: &mut [u8],
366) -> Result<&mut T, PodCastError> {
367 unsafe { internal::try_from_bytes_mut(s) }
368}
369
370/// Cast `A` into `B`
371///
372/// ## Panics
373///
374/// * This is like [`try_cast`], but will panic on a size mismatch.
375#[inline]
376#[cfg_attr(feature = "track_caller", track_caller)]
377pub fn cast<A: NoUninit, B: AnyBitPattern>(a: A) -> B {
378 unsafe { internal::cast(a) }
379}
380
381/// Cast `&mut A` into `&mut B`.
382///
383/// ## Panics
384///
385/// This is [`try_cast_mut`] but will panic on error.
386#[inline]
387#[cfg_attr(feature = "track_caller", track_caller)]
388pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
389 a: &mut A,
390) -> &mut B {
391 unsafe { internal::cast_mut(a) }
392}
393
394/// Cast `&A` into `&B`.
395///
396/// ## Panics
397///
398/// This is [`try_cast_ref`] but will panic on error.
399#[inline]
400#[cfg_attr(feature = "track_caller", track_caller)]
401pub fn cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> &B {
402 unsafe { internal::cast_ref(a) }
403}
404
405/// Cast `&[A]` into `&[B]`.
406///
407/// ## Panics
408///
409/// This is [`try_cast_slice`] but will panic on error.
410#[inline]
411#[cfg_attr(feature = "track_caller", track_caller)]
412pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
413 unsafe { internal::cast_slice(a) }
414}
415
416/// Cast `&mut [A]` into `&mut [B]`.
417///
418/// ## Panics
419///
420/// This is [`try_cast_slice_mut`] but will panic on error.
421#[inline]
422#[cfg_attr(feature = "track_caller", track_caller)]
423pub fn cast_slice_mut<
424 A: NoUninit + AnyBitPattern,
425 B: NoUninit + AnyBitPattern,
426>(
427 a: &mut [A],
428) -> &mut [B] {
429 unsafe { internal::cast_slice_mut(a) }
430}
431
432/// As [`align_to`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to),
433/// but safe because of the [`Pod`] bound.
434#[inline]
435pub fn pod_align_to<T: NoUninit, U: AnyBitPattern>(
436 vals: &[T],
437) -> (&[T], &[U], &[T]) {
438 unsafe { vals.align_to::<U>() }
439}
440
441/// As [`align_to_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut),
442/// but safe because of the [`Pod`] bound.
443#[inline]
444pub fn pod_align_to_mut<
445 T: NoUninit + AnyBitPattern,
446 U: NoUninit + AnyBitPattern,
447>(
448 vals: &mut [T],
449) -> (&mut [T], &mut [U], &mut [T]) {
450 unsafe { vals.align_to_mut::<U>() }
451}
452
453/// Try to cast `A` into `B`.
454///
455/// Note that for this particular type of cast, alignment isn't a factor. The
456/// input value is semantically copied into the function and then returned to a
457/// new memory location which will have whatever the required alignment of the
458/// output type is.
459///
460/// ## Failure
461///
462/// * If the types don't have the same size this fails.
463#[inline]
464pub fn try_cast<A: NoUninit, B: AnyBitPattern>(
465 a: A,
466) -> Result<B, PodCastError> {
467 unsafe { internal::try_cast(a) }
468}
469
470/// Try to convert a `&A` into `&B`.
471///
472/// ## Failure
473///
474/// * If the reference isn't aligned in the new type
475/// * If the source type and target type aren't the same size.
476#[inline]
477pub fn try_cast_ref<A: NoUninit, B: AnyBitPattern>(
478 a: &A,
479) -> Result<&B, PodCastError> {
480 unsafe { internal::try_cast_ref(a) }
481}
482
483/// Try to convert a `&mut A` into `&mut B`.
484///
485/// As [`try_cast_ref`], but `mut`.
486#[inline]
487pub fn try_cast_mut<
488 A: NoUninit + AnyBitPattern,
489 B: NoUninit + AnyBitPattern,
490>(
491 a: &mut A,
492) -> Result<&mut B, PodCastError> {
493 unsafe { internal::try_cast_mut(a) }
494}
495
496/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
497///
498/// * `input.as_ptr() as usize == output.as_ptr() as usize`
499/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
500///
501/// ## Failure
502///
503/// * If the target type has a greater alignment requirement and the input slice
504/// isn't aligned. **Note:** This rule applies even if the slice is empty!
505/// * If the target element type is a different size from the current element
506/// type, and the output slice wouldn't be a whole number of elements when
507/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
508/// that's a failure).
509/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
510/// and a non-ZST.
511#[inline]
512pub fn try_cast_slice<A: NoUninit, B: AnyBitPattern>(
513 a: &[A],
514) -> Result<&[B], PodCastError> {
515 unsafe { internal::try_cast_slice(a) }
516}
517
518/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
519/// length).
520///
521/// As [`try_cast_slice`], but `&mut`.
522#[inline]
523pub fn try_cast_slice_mut<
524 A: NoUninit + AnyBitPattern,
525 B: NoUninit + AnyBitPattern,
526>(
527 a: &mut [A],
528) -> Result<&mut [B], PodCastError> {
529 unsafe { internal::try_cast_slice_mut(a) }
530}
531
532/// Fill all bytes of `target` with zeroes (see [`Zeroable`]).
533///
534/// This is similar to `*target = Zeroable::zeroed()`, but guarantees that any
535/// padding bytes in `target` are zeroed as well.
536///
537/// See also [`fill_zeroes`], if you have a slice rather than a single value.
538#[inline]
539pub fn write_zeroes<T: Zeroable>(target: &mut T) {
540 struct EnsureZeroWrite<T>(*mut T);
541 impl<T> Drop for EnsureZeroWrite<T> {
542 #[inline(always)]
543 fn drop(&mut self) {
544 unsafe {
545 core::ptr::write_bytes(self.0, 0u8, 1);
546 }
547 }
548 }
549 unsafe {
550 let guard = EnsureZeroWrite(target);
551 core::ptr::drop_in_place(guard.0);
552 drop(guard);
553 }
554}
555
556/// Fill all bytes of `slice` with zeroes (see [`Zeroable`]).
557///
558/// This is similar to `slice.fill(Zeroable::zeroed())`, but guarantees that any
559/// padding bytes in `slice` are zeroed as well.
560///
561/// See also [`write_zeroes`], which zeroes all bytes of a single value rather
562/// than a slice.
563#[inline]
564pub fn fill_zeroes<T: Zeroable>(slice: &mut [T]) {
565 if core::mem::needs_drop::<T>() {
566 // If `T` needs to be dropped then we have to do this one item at a time, in
567 // case one of the intermediate drops does a panic.
568 slice.iter_mut().for_each(write_zeroes);
569 } else {
570 // Otherwise we can be really fast and just fill everything with zeros.
571 let len = slice.len();
572 unsafe { core::ptr::write_bytes(slice.as_mut_ptr(), 0u8, len) }
573 }
574}
575
576/// Same as [`Zeroable::zeroed`], but as a `const fn` const.
577#[cfg(feature = "const_zeroed")]
578#[inline]
579#[must_use]
580pub const fn zeroed<T: Zeroable>() -> T {
581 unsafe { core::mem::zeroed() }
582}