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