1 #![no_std]
2 #![warn(missing_docs)]
3 
4 //! This crate gives small utilities for casting between plain data types.
5 //!
6 //! ## Basics
7 //!
8 //! Data comes in five basic forms in Rust, so we have five basic casting
9 //! functions:
10 //!
11 //! * `T` uses [`cast`]
12 //! * `&T` uses [`cast_ref`]
13 //! * `&mut T` uses [`cast_mut`]
14 //! * `&[T]` uses [`cast_slice`]
15 //! * `&mut [T]` uses [`cast_slice_mut`]
16 //!
17 //! Some casts will never fail (eg: `cast::<u32, f32>` always works), other
18 //! casts might fail (eg: `cast_ref::<[u8; 4], u32>` will fail if the reference
19 //! isn't already aligned to 4). Each casting function has a "try" version which
20 //! will return a `Result`, and the "normal" version which will simply panic on
21 //! invalid input.
22 //!
23 //! ## Using Your Own Types
24 //!
25 //! All the functions here are guarded by the [`Pod`] trait, which is a
26 //! sub-trait of the [`Zeroable`] trait.
27 //!
28 //! If you're very sure that your type is eligible, you can implement those
29 //! traits for your type and then they'll have full casting support. However,
30 //! these traits are `unsafe`, and you should carefully read the requirements
31 //! before adding the them to your own types.
32 //!
33 //! ## Features
34 //!
35 //! * This crate is core only by default, but if you're using Rust 1.36 or later
36 //!   you can enable the `extern_crate_alloc` cargo feature for some additional
37 //!   methods related to `Box` and `Vec`. Note that the `docs.rs` documentation
38 //!   is always built with `extern_crate_alloc` cargo feature enabled.
39 
40 #[cfg(target_arch = "x86")]
41 use core::arch::x86;
42 #[cfg(target_arch = "x86_64")]
43 use core::arch::x86_64;
44 //
45 use core::{marker::*, mem::*, num::*, ptr::*};
46 
47 // Used from macros to ensure we aren't using some locally defined name and
48 // actually are referencing libcore. This also would allow pre-2018 edition
49 // crates to use our macros, but I'm not sure how important that is.
50 #[doc(hidden)]
51 pub use ::core as __core;
52 
53 macro_rules! impl_unsafe_marker_for_array {
54   ( $marker:ident , $( $n:expr ),* ) => {
55     $(unsafe impl<T> $marker for [T; $n] where T: $marker {})*
56   }
57 }
58 
59 #[cfg(feature = "extern_crate_std")]
60 extern crate std;
61 
62 #[cfg(feature = "extern_crate_alloc")]
63 extern crate alloc;
64 #[cfg(feature = "extern_crate_alloc")]
65 pub mod allocation;
66 #[cfg(feature = "extern_crate_alloc")]
67 pub use allocation::*;
68 
69 mod zeroable;
70 pub use zeroable::*;
71 
72 mod pod;
73 pub use pod::*;
74 
75 mod contiguous;
76 pub use contiguous::*;
77 
78 mod offset_of;
79 pub use offset_of::*;
80 
81 mod transparent;
82 pub use transparent::*;
83 
84 #[cfg(feature = "derive")]
85 pub use bytemuck_derive::{Zeroable, Pod, TransparentWrapper, Contiguous};
86 
87 /*
88 
89 Note(Lokathor): We've switched all of the `unwrap` to `match` because there is
90 apparently a bug: https://github.com/rust-lang/rust/issues/68667
91 and it doesn't seem to show up in simple godbolt examples but has been reported
92 as having an impact when there's a cast mixed in with other more complicated
93 code around it. Rustc/LLVM ends up missing that the `Err` can't ever happen for
94 particular type combinations, and then it doesn't fully eliminated the panic
95 possibility code branch.
96 
97 */
98 
99 /// Immediately panics.
100 #[cold]
101 #[inline(never)]
something_went_wrong(src: &str, err: PodCastError) -> !102 fn something_went_wrong(src: &str, err: PodCastError) -> ! {
103   // Note(Lokathor): Keeping the panic here makes the panic _formatting_ go
104   // here too, which helps assembly readability and also helps keep down
105   // the inline pressure.
106   panic!("{src}>{err:?}", src = src, err = err)
107 }
108 
109 /// Re-interprets `&T` as `&[u8]`.
110 ///
111 /// Any ZST becomes an empty slice, and in that case the pointer value of that
112 /// empty slice might not match the pointer value of the input reference.
113 #[inline]
bytes_of<T: Pod>(t: &T) -> &[u8]114 pub fn bytes_of<T: Pod>(t: &T) -> &[u8] {
115   match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
116     Ok(s) => s,
117     Err(_) => unreachable!(),
118   }
119 }
120 
121 /// Re-interprets `&mut T` as `&mut [u8]`.
122 ///
123 /// Any ZST becomes an empty slice, and in that case the pointer value of that
124 /// empty slice might not match the pointer value of the input reference.
125 #[inline]
bytes_of_mut<T: Pod>(t: &mut T) -> &mut [u8]126 pub fn bytes_of_mut<T: Pod>(t: &mut T) -> &mut [u8] {
127   match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
128     Ok(s) => s,
129     Err(_) => unreachable!(),
130   }
131 }
132 
133 /// Re-interprets `&[u8]` as `&T`.
134 ///
135 /// ## Panics
136 ///
137 /// This is [`try_from_bytes`] but will panic on error.
138 #[inline]
from_bytes<T: Pod>(s: &[u8]) -> &T139 pub fn from_bytes<T: Pod>(s: &[u8]) -> &T {
140   match try_from_bytes(s) {
141     Ok(t) => t,
142     Err(e) => something_went_wrong("from_bytes", e),
143   }
144 }
145 
146 /// Re-interprets `&mut [u8]` as `&mut T`.
147 ///
148 /// ## Panics
149 ///
150 /// This is [`try_from_bytes_mut`] but will panic on error.
151 #[inline]
from_bytes_mut<T: Pod>(s: &mut [u8]) -> &mut T152 pub fn from_bytes_mut<T: Pod>(s: &mut [u8]) -> &mut T {
153   match try_from_bytes_mut(s) {
154     Ok(t) => t,
155     Err(e) => something_went_wrong("from_bytes_mut", e),
156   }
157 }
158 
159 /// Re-interprets `&[u8]` as `&T`.
160 ///
161 /// ## Failure
162 ///
163 /// * If the slice isn't aligned for the new type
164 /// * If the slice's length isn’t exactly the size of the new type
165 #[inline]
try_from_bytes<T: Pod>(s: &[u8]) -> Result<&T, PodCastError>166 pub fn try_from_bytes<T: Pod>(s: &[u8]) -> Result<&T, PodCastError> {
167   if s.len() != size_of::<T>() {
168     Err(PodCastError::SizeMismatch)
169   } else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
170     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
171   } else {
172     Ok(unsafe { &*(s.as_ptr() as *const T) })
173   }
174 }
175 
176 /// Re-interprets `&mut [u8]` as `&mut T`.
177 ///
178 /// ## Failure
179 ///
180 /// * If the slice isn't aligned for the new type
181 /// * If the slice's length isn’t exactly the size of the new type
182 #[inline]
try_from_bytes_mut<T: Pod>( s: &mut [u8], ) -> Result<&mut T, PodCastError>183 pub fn try_from_bytes_mut<T: Pod>(
184   s: &mut [u8],
185 ) -> Result<&mut T, PodCastError> {
186   if s.len() != size_of::<T>() {
187     Err(PodCastError::SizeMismatch)
188   } else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
189     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
190   } else {
191     Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
192   }
193 }
194 
195 /// The things that can go wrong when casting between [`Pod`] data forms.
196 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
197 pub enum PodCastError {
198   /// You tried to cast a slice to an element type with a higher alignment
199   /// requirement but the slice wasn't aligned.
200   TargetAlignmentGreaterAndInputNotAligned,
201   /// If the element size changes then the output slice changes length
202   /// accordingly. If the output slice wouldn't be a whole number of elements
203   /// then the conversion fails.
204   OutputSliceWouldHaveSlop,
205   /// When casting a slice you can't convert between ZST elements and non-ZST
206   /// elements. When casting an individual `T`, `&T`, or `&mut T` value the
207   /// source size and destination size must be an exact match.
208   SizeMismatch,
209   /// For this type of cast the alignments must be exactly the same and they
210   /// were not so now you're sad.
211   ///
212   /// This error is generated **only** by operations that cast allocated types
213   /// (such as `Box` and `Vec`), because in that case the alignment must stay
214   /// exact.
215   AlignmentMismatch,
216 }
217 impl core::fmt::Display for PodCastError {
fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result218   fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
219     write!(f, "{:?}", self)
220   }
221 }
222 #[cfg(feature = "extern_crate_std")]
223 impl std::error::Error for PodCastError {}
224 
225 /// Cast `T` into `U`
226 ///
227 /// ## Panics
228 ///
229 /// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
230 #[inline]
cast<A: Pod, B: Pod>(a: A) -> B231 pub fn cast<A: Pod, B: Pod>(a: A) -> B {
232   if size_of::<A>() == size_of::<B>() {
233     unsafe { core::mem::transmute_copy(&a) }
234   } else {
235     something_went_wrong("cast", PodCastError::SizeMismatch)
236   }
237 }
238 
239 /// Cast `&mut T` into `&mut U`.
240 ///
241 /// ## Panics
242 ///
243 /// This is [`try_cast_mut`] but will panic on error.
244 #[inline]
cast_mut<A: Pod, B: Pod>(a: &mut A) -> &mut B245 pub fn cast_mut<A: Pod, B: Pod>(a: &mut A) -> &mut B {
246   if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
247     // Plz mr compiler, just notice that we can't ever hit Err in this case.
248     match try_cast_mut(a) {
249       Ok(b) => b,
250       Err(_) => unreachable!(),
251     }
252   } else {
253     match try_cast_mut(a) {
254       Ok(b) => b,
255       Err(e) => something_went_wrong("cast_mut", e),
256     }
257   }
258 }
259 
260 /// Cast `&T` into `&U`.
261 ///
262 /// ## Panics
263 ///
264 /// This is [`try_cast_ref`] but will panic on error.
265 #[inline]
cast_ref<A: Pod, B: Pod>(a: &A) -> &B266 pub fn cast_ref<A: Pod, B: Pod>(a: &A) -> &B {
267   if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
268     // Plz mr compiler, just notice that we can't ever hit Err in this case.
269     match try_cast_ref(a) {
270       Ok(b) => b,
271       Err(_) => unreachable!(),
272     }
273   } else {
274     match try_cast_ref(a) {
275       Ok(b) => b,
276       Err(e) => something_went_wrong("cast_ref", e),
277     }
278   }
279 }
280 
281 /// Cast `&[A]` into `&[B]`.
282 ///
283 /// ## Panics
284 ///
285 /// This is [`try_cast_slice`] but will panic on error.
286 #[inline]
cast_slice<A: Pod, B: Pod>(a: &[A]) -> &[B]287 pub fn cast_slice<A: Pod, B: Pod>(a: &[A]) -> &[B] {
288   match try_cast_slice(a) {
289     Ok(b) => b,
290     Err(e) => something_went_wrong("cast_slice", e),
291   }
292 }
293 
294 /// Cast `&mut [T]` into `&mut [U]`.
295 ///
296 /// ## Panics
297 ///
298 /// This is [`try_cast_slice_mut`] but will panic on error.
299 #[inline]
cast_slice_mut<A: Pod, B: Pod>(a: &mut [A]) -> &mut [B]300 pub fn cast_slice_mut<A: Pod, B: Pod>(a: &mut [A]) -> &mut [B] {
301   match try_cast_slice_mut(a) {
302     Ok(b) => b,
303     Err(e) => something_went_wrong("cast_slice_mut", e),
304   }
305 }
306 
307 /// As `align_to`, but safe because of the [`Pod`] bound.
308 #[inline]
pod_align_to<T: Pod, U: Pod>(vals: &[T]) -> (&[T], &[U], &[T])309 pub fn pod_align_to<T: Pod, U: Pod>(vals: &[T]) -> (&[T], &[U], &[T]) {
310   unsafe { vals.align_to::<U>() }
311 }
312 
313 /// As `align_to_mut`, but safe because of the [`Pod`] bound.
314 #[inline]
pod_align_to_mut<T: Pod, U: Pod>( vals: &mut [T], ) -> (&mut [T], &mut [U], &mut [T])315 pub fn pod_align_to_mut<T: Pod, U: Pod>(
316   vals: &mut [T],
317 ) -> (&mut [T], &mut [U], &mut [T]) {
318   unsafe { vals.align_to_mut::<U>() }
319 }
320 
321 /// Try to cast `T` into `U`.
322 ///
323 /// Note that for this particular type of cast, alignment isn't a factor. The
324 /// input value is semantically copied into the function and then returned to a
325 /// new memory location which will have whatever the required alignment of the
326 /// output type is.
327 ///
328 /// ## Failure
329 ///
330 /// * If the types don't have the same size this fails.
331 #[inline]
try_cast<A: Pod, B: Pod>(a: A) -> Result<B, PodCastError>332 pub fn try_cast<A: Pod, B: Pod>(a: A) -> Result<B, PodCastError> {
333   if size_of::<A>() == size_of::<B>() {
334     Ok(unsafe { core::mem::transmute_copy(&a) })
335   } else {
336     Err(PodCastError::SizeMismatch)
337   }
338 }
339 
340 /// Try to convert a `&T` into `&U`.
341 ///
342 /// ## Failure
343 ///
344 /// * If the reference isn't aligned in the new type
345 /// * If the source type and target type aren't the same size.
346 #[inline]
try_cast_ref<A: Pod, B: Pod>(a: &A) -> Result<&B, PodCastError>347 pub fn try_cast_ref<A: Pod, B: Pod>(a: &A) -> Result<&B, PodCastError> {
348   // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
349   // after monomorphization.
350   if align_of::<B>() > align_of::<A>()
351     && (a as *const A as usize) % align_of::<B>() != 0
352   {
353     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
354   } else if size_of::<B>() == size_of::<A>() {
355     Ok(unsafe { &*(a as *const A as *const B) })
356   } else {
357     Err(PodCastError::SizeMismatch)
358   }
359 }
360 
361 /// Try to convert a `&mut T` into `&mut U`.
362 ///
363 /// As [`try_cast_ref`], but `mut`.
364 #[inline]
try_cast_mut<A: Pod, B: Pod>(a: &mut A) -> Result<&mut B, PodCastError>365 pub fn try_cast_mut<A: Pod, B: Pod>(a: &mut A) -> Result<&mut B, PodCastError> {
366   // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
367   // after monomorphization.
368   if align_of::<B>() > align_of::<A>()
369     && (a as *mut A as usize) % align_of::<B>() != 0
370   {
371     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
372   } else if size_of::<B>() == size_of::<A>() {
373     Ok(unsafe { &mut *(a as *mut A as *mut B) })
374   } else {
375     Err(PodCastError::SizeMismatch)
376   }
377 }
378 
379 /// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
380 ///
381 /// * `input.as_ptr() as usize == output.as_ptr() as usize`
382 /// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
383 ///
384 /// ## Failure
385 ///
386 /// * If the target type has a greater alignment requirement and the input slice
387 ///   isn't aligned.
388 /// * If the target element type is a different size from the current element
389 ///   type, and the output slice wouldn't be a whole number of elements when
390 ///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
391 ///   that's a failure).
392 /// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
393 ///   and a non-ZST.
394 #[inline]
try_cast_slice<A: Pod, B: Pod>(a: &[A]) -> Result<&[B], PodCastError>395 pub fn try_cast_slice<A: Pod, B: Pod>(a: &[A]) -> Result<&[B], PodCastError> {
396   // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
397   // after monomorphization.
398   if align_of::<B>() > align_of::<A>()
399     && (a.as_ptr() as usize) % align_of::<B>() != 0
400   {
401     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
402   } else if size_of::<B>() == size_of::<A>() {
403     Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, a.len()) })
404   } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
405     Err(PodCastError::SizeMismatch)
406   } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
407     let new_len = core::mem::size_of_val(a) / size_of::<B>();
408     Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, new_len) })
409   } else {
410     Err(PodCastError::OutputSliceWouldHaveSlop)
411   }
412 }
413 
414 /// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
415 /// length).
416 ///
417 /// As [`try_cast_slice`], but `&mut`.
418 #[inline]
try_cast_slice_mut<A: Pod, B: Pod>( a: &mut [A], ) -> Result<&mut [B], PodCastError>419 pub fn try_cast_slice_mut<A: Pod, B: Pod>(
420   a: &mut [A],
421 ) -> Result<&mut [B], PodCastError> {
422   // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
423   // after monomorphization.
424   if align_of::<B>() > align_of::<A>()
425     && (a.as_mut_ptr() as usize) % align_of::<B>() != 0
426   {
427     Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
428   } else if size_of::<B>() == size_of::<A>() {
429     Ok(unsafe {
430       core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, a.len())
431     })
432   } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
433     Err(PodCastError::SizeMismatch)
434   } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
435     let new_len = core::mem::size_of_val(a) / size_of::<B>();
436     Ok(unsafe {
437       core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, new_len)
438     })
439   } else {
440     Err(PodCastError::OutputSliceWouldHaveSlop)
441   }
442 }
443