bytemuck/
checked.rs

1//! Checked versions of the casting functions exposed in crate root
2//! that support [`CheckedBitPattern`] types.
3
4use crate::{
5  internal::{self, something_went_wrong},
6  AnyBitPattern, NoUninit,
7};
8
9/// A marker trait that allows types that have some invalid bit patterns to be
10/// used in places that otherwise require [`AnyBitPattern`] or [`Pod`] types by
11/// performing a runtime check on a perticular set of bits. This is particularly
12/// useful for types like fieldless ('C-style') enums, [`char`], bool, and
13/// structs containing them.
14///
15/// To do this, we define a `Bits` type which is a type with equivalent layout
16/// to `Self` other than the invalid bit patterns which disallow `Self` from
17/// being [`AnyBitPattern`]. This `Bits` type must itself implement
18/// [`AnyBitPattern`]. Then, we implement a function that checks whether a
19/// certain instance of the `Bits` is also a valid bit pattern of `Self`. If
20/// this check passes, then we can allow casting from the `Bits` to `Self` (and
21/// therefore, any type which is able to be cast to `Bits` is also able to be
22/// cast to `Self`).
23///
24/// [`AnyBitPattern`] is a subset of [`CheckedBitPattern`], meaning that any `T:
25/// AnyBitPattern` is also [`CheckedBitPattern`]. This means you can also use
26/// any [`AnyBitPattern`] type in the checked versions of casting functions in
27/// this module. If it's possible, prefer implementing [`AnyBitPattern`] for
28/// your type directly instead of [`CheckedBitPattern`] as it gives greater
29/// flexibility.
30///
31/// # Derive
32///
33/// A `#[derive(CheckedBitPattern)]` macro is provided under the `derive`
34/// feature flag which will automatically validate the requirements of this
35/// trait and implement the trait for you for both enums and structs. This is
36/// the recommended method for implementing the trait, however it's also
37/// possible to do manually.
38///
39/// # Example
40///
41/// If manually implementing the trait, we can do something like so:
42///
43/// ```rust
44/// use bytemuck::{CheckedBitPattern, NoUninit};
45///
46/// #[repr(u32)]
47/// #[derive(Copy, Clone)]
48/// enum MyEnum {
49///     Variant0 = 0,
50///     Variant1 = 1,
51///     Variant2 = 2,
52/// }
53///
54/// unsafe impl CheckedBitPattern for MyEnum {
55///     type Bits = u32;
56///
57///     fn is_valid_bit_pattern(bits: &u32) -> bool {
58///         match *bits {
59///             0 | 1 | 2 => true,
60///             _ => false,
61///         }
62///     }
63/// }
64///
65/// // It is often useful to also implement `NoUninit` on our `CheckedBitPattern` types.
66/// // This will allow us to do casting of mutable references (and mutable slices).
67/// // It is not always possible to do so, but in this case we have no padding so it is.
68/// unsafe impl NoUninit for MyEnum {}
69/// ```
70///
71/// We can now use relevant casting functions. For example,
72///
73/// ```rust
74/// # use bytemuck::{CheckedBitPattern, NoUninit};
75/// # #[repr(u32)]
76/// # #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77/// # enum MyEnum {
78/// #     Variant0 = 0,
79/// #     Variant1 = 1,
80/// #     Variant2 = 2,
81/// # }
82/// # unsafe impl NoUninit for MyEnum {}
83/// # unsafe impl CheckedBitPattern for MyEnum {
84/// #     type Bits = u32;
85/// #     fn is_valid_bit_pattern(bits: &u32) -> bool {
86/// #         match *bits {
87/// #             0 | 1 | 2 => true,
88/// #             _ => false,
89/// #         }
90/// #     }
91/// # }
92/// use bytemuck::{bytes_of, bytes_of_mut};
93/// use bytemuck::checked;
94///
95/// let bytes = bytes_of(&2u32);
96/// let result = checked::try_from_bytes::<MyEnum>(bytes);
97/// assert_eq!(result, Ok(&MyEnum::Variant2));
98///
99/// // Fails for invalid discriminant
100/// let bytes = bytes_of(&100u32);
101/// let result = checked::try_from_bytes::<MyEnum>(bytes);
102/// assert!(result.is_err());
103///
104/// // Since we implemented NoUninit, we can also cast mutably from an original type
105/// // that is `NoUninit + AnyBitPattern`:
106/// let mut my_u32 = 2u32;
107/// {
108///   let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32);
109///   assert_eq!(as_enum_mut, &mut MyEnum::Variant2);
110///   *as_enum_mut = MyEnum::Variant0;
111/// }
112/// assert_eq!(my_u32, 0u32);
113/// ```
114///
115/// # Safety
116///
117/// * `Self` *must* have the same layout as the specified `Bits` except for the
118///   possible invalid bit patterns being checked during
119///   [`is_valid_bit_pattern`].
120/// * This almost certainly means your type must be `#[repr(C)]` or a similar
121///   specified repr, but if you think you know better, you probably don't. If
122///   you still think you know better, be careful and have fun. And don't mess
123///   it up (I mean it).
124/// * If [`is_valid_bit_pattern`] returns true, then the bit pattern contained
125///   in `bits` must also be valid for an instance of `Self`.
126/// * Probably more, don't mess it up (I mean it 2.0)
127///
128/// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
129/// [`Pod`]: crate::Pod
130pub unsafe trait CheckedBitPattern: Copy {
131  /// `Self` *must* have the same layout as the specified `Bits` except for
132  /// the possible invalid bit patterns being checked during
133  /// [`is_valid_bit_pattern`].
134  ///
135  /// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
136  type Bits: AnyBitPattern;
137
138  /// If this function returns true, then it must be valid to reinterpret `bits`
139  /// as `&Self`.
140  fn is_valid_bit_pattern(bits: &Self::Bits) -> bool;
141}
142
143unsafe impl<T: AnyBitPattern> CheckedBitPattern for T {
144  type Bits = T;
145
146  #[inline(always)]
147  fn is_valid_bit_pattern(_bits: &T) -> bool {
148    true
149  }
150}
151
152unsafe impl CheckedBitPattern for char {
153  type Bits = u32;
154
155  #[inline]
156  fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
157    core::char::from_u32(*bits).is_some()
158  }
159}
160
161unsafe impl CheckedBitPattern for bool {
162  type Bits = u8;
163
164  #[inline]
165  fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
166    // DO NOT use the `matches!` macro, it isn't 1.34 compatible.
167    match *bits {
168      0 | 1 => true,
169      _ => false,
170    }
171  }
172}
173
174// Rust 1.70.0 documents that NonZero[int] has the same layout as [int].
175macro_rules! impl_checked_for_nonzero {
176  ($($nonzero:ty: $primitive:ty),* $(,)?) => {
177    $(
178      unsafe impl CheckedBitPattern for $nonzero {
179        type Bits = $primitive;
180
181        #[inline]
182        fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
183          *bits != 0
184        }
185      }
186    )*
187  };
188}
189impl_checked_for_nonzero! {
190  core::num::NonZeroU8: u8,
191  core::num::NonZeroI8: i8,
192  core::num::NonZeroU16: u16,
193  core::num::NonZeroI16: i16,
194  core::num::NonZeroU32: u32,
195  core::num::NonZeroI32: i32,
196  core::num::NonZeroU64: u64,
197  core::num::NonZeroI64: i64,
198  core::num::NonZeroI128: i128,
199  core::num::NonZeroU128: u128,
200  core::num::NonZeroUsize: usize,
201  core::num::NonZeroIsize: isize,
202}
203
204/// The things that can go wrong when casting between [`CheckedBitPattern`] data
205/// forms.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub enum CheckedCastError {
208  /// An error occurred during a true-[`Pod`] cast
209  ///
210  /// [`Pod`]: crate::Pod
211  PodCastError(crate::PodCastError),
212  /// When casting to a [`CheckedBitPattern`] type, it is possible that the
213  /// original data contains an invalid bit pattern. If so, the cast will
214  /// fail and this error will be returned. Will never happen on casts
215  /// between [`Pod`] types.
216  ///
217  /// [`Pod`]: crate::Pod
218  InvalidBitPattern,
219}
220
221#[cfg(not(target_arch = "spirv"))]
222impl core::fmt::Display for CheckedCastError {
223  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
224    write!(f, "{:?}", self)
225  }
226}
227#[cfg(feature = "extern_crate_std")]
228#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_std")))]
229impl std::error::Error for CheckedCastError {}
230
231impl From<crate::PodCastError> for CheckedCastError {
232  fn from(err: crate::PodCastError) -> CheckedCastError {
233    CheckedCastError::PodCastError(err)
234  }
235}
236
237/// Re-interprets `&[u8]` as `&T`.
238///
239/// ## Failure
240///
241/// * If the slice isn't aligned for the new type
242/// * If the slice's length isn’t exactly the size of the new type
243/// * If the slice contains an invalid bit pattern for `T`
244#[inline]
245pub fn try_from_bytes<T: CheckedBitPattern>(
246  s: &[u8],
247) -> Result<&T, CheckedCastError> {
248  let pod = crate::try_from_bytes(s)?;
249
250  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
251    Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
252  } else {
253    Err(CheckedCastError::InvalidBitPattern)
254  }
255}
256
257/// Re-interprets `&mut [u8]` as `&mut T`.
258///
259/// ## Failure
260///
261/// * If the slice isn't aligned for the new type
262/// * If the slice's length isn’t exactly the size of the new type
263/// * If the slice contains an invalid bit pattern for `T`
264#[inline]
265pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
266  s: &mut [u8],
267) -> Result<&mut T, CheckedCastError> {
268  let pod = unsafe { internal::try_from_bytes_mut(s) }?;
269
270  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
271    Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
272  } else {
273    Err(CheckedCastError::InvalidBitPattern)
274  }
275}
276
277/// Reads from the bytes as if they were a `T`.
278///
279/// ## Failure
280/// * If the `bytes` length is not equal to `size_of::<T>()`.
281/// * If the slice contains an invalid bit pattern for `T`
282#[inline]
283pub fn try_pod_read_unaligned<T: CheckedBitPattern>(
284  bytes: &[u8],
285) -> Result<T, CheckedCastError> {
286  let pod = crate::try_pod_read_unaligned(bytes)?;
287
288  if <T as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
289    Ok(unsafe { transmute!(pod) })
290  } else {
291    Err(CheckedCastError::InvalidBitPattern)
292  }
293}
294
295/// Try to cast `A` into `B`.
296///
297/// Note that for this particular type of cast, alignment isn't a factor. The
298/// input value is semantically copied into the function and then returned to a
299/// new memory location which will have whatever the required alignment of the
300/// output type is.
301///
302/// ## Failure
303///
304/// * If the types don't have the same size this fails.
305/// * If `a` contains an invalid bit pattern for `B` this fails.
306#[inline]
307pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
308  a: A,
309) -> Result<B, CheckedCastError> {
310  let pod = crate::try_cast(a)?;
311
312  if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
313    Ok(unsafe { transmute!(pod) })
314  } else {
315    Err(CheckedCastError::InvalidBitPattern)
316  }
317}
318
319/// Try to convert a `&A` into `&B`.
320///
321/// ## Failure
322///
323/// * If the reference isn't aligned in the new type
324/// * If the source type and target type aren't the same size.
325/// * If `a` contains an invalid bit pattern for `B` this fails.
326#[inline]
327pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
328  a: &A,
329) -> Result<&B, CheckedCastError> {
330  let pod = crate::try_cast_ref(a)?;
331
332  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
333    Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
334  } else {
335    Err(CheckedCastError::InvalidBitPattern)
336  }
337}
338
339/// Try to convert a `&mut A` into `&mut B`.
340///
341/// As [`try_cast_ref`], but `mut`.
342#[inline]
343pub fn try_cast_mut<
344  A: NoUninit + AnyBitPattern,
345  B: CheckedBitPattern + NoUninit,
346>(
347  a: &mut A,
348) -> Result<&mut B, CheckedCastError> {
349  let pod = unsafe { internal::try_cast_mut(a) }?;
350
351  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
352    Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
353  } else {
354    Err(CheckedCastError::InvalidBitPattern)
355  }
356}
357
358/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
359///
360/// * `input.as_ptr() as usize == output.as_ptr() as usize`
361/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
362///
363/// ## Failure
364///
365/// * If the target type has a greater alignment requirement and the input slice
366///   isn't aligned.
367/// * If the target element type is a different size from the current element
368///   type, and the output slice wouldn't be a whole number of elements when
369///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
370///   that's a failure).
371/// * If any element of the converted slice would contain an invalid bit pattern
372///   for `B` this fails.
373#[inline]
374pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
375  a: &[A],
376) -> Result<&[B], CheckedCastError> {
377  let pod = crate::try_cast_slice(a)?;
378
379  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
380    Ok(unsafe {
381      core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
382    })
383  } else {
384    Err(CheckedCastError::InvalidBitPattern)
385  }
386}
387
388/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
389/// length).
390///
391/// As [`try_cast_slice`], but `&mut`.
392#[inline]
393pub fn try_cast_slice_mut<
394  A: NoUninit + AnyBitPattern,
395  B: CheckedBitPattern + NoUninit,
396>(
397  a: &mut [A],
398) -> Result<&mut [B], CheckedCastError> {
399  let pod = unsafe { internal::try_cast_slice_mut(a) }?;
400
401  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
402    Ok(unsafe {
403      core::slice::from_raw_parts_mut(pod.as_mut_ptr() as *mut B, pod.len())
404    })
405  } else {
406    Err(CheckedCastError::InvalidBitPattern)
407  }
408}
409
410/// Re-interprets `&[u8]` as `&T`.
411///
412/// ## Panics
413///
414/// This is [`try_from_bytes`] but will panic on error.
415#[inline]
416#[cfg_attr(feature = "track_caller", track_caller)]
417pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
418  match try_from_bytes(s) {
419    Ok(t) => t,
420    Err(e) => something_went_wrong("from_bytes", e),
421  }
422}
423
424/// Re-interprets `&mut [u8]` as `&mut T`.
425///
426/// ## Panics
427///
428/// This is [`try_from_bytes_mut`] but will panic on error.
429#[inline]
430#[cfg_attr(feature = "track_caller", track_caller)]
431pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
432  match try_from_bytes_mut(s) {
433    Ok(t) => t,
434    Err(e) => something_went_wrong("from_bytes_mut", e),
435  }
436}
437
438/// Reads the slice into a `T` value.
439///
440/// ## Panics
441/// * This is like `try_pod_read_unaligned` but will panic on failure.
442#[inline]
443#[cfg_attr(feature = "track_caller", track_caller)]
444pub fn pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> T {
445  match try_pod_read_unaligned(bytes) {
446    Ok(t) => t,
447    Err(e) => something_went_wrong("pod_read_unaligned", e),
448  }
449}
450
451/// Cast `A` into `B`
452///
453/// ## Panics
454///
455/// * This is like [`try_cast`], but will panic on a size mismatch.
456#[inline]
457#[cfg_attr(feature = "track_caller", track_caller)]
458pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
459  match try_cast(a) {
460    Ok(t) => t,
461    Err(e) => something_went_wrong("cast", e),
462  }
463}
464
465/// Cast `&mut A` into `&mut B`.
466///
467/// ## Panics
468///
469/// This is [`try_cast_mut`] but will panic on error.
470#[inline]
471#[cfg_attr(feature = "track_caller", track_caller)]
472pub fn cast_mut<
473  A: NoUninit + AnyBitPattern,
474  B: NoUninit + CheckedBitPattern,
475>(
476  a: &mut A,
477) -> &mut B {
478  match try_cast_mut(a) {
479    Ok(t) => t,
480    Err(e) => something_went_wrong("cast_mut", e),
481  }
482}
483
484/// Cast `&A` into `&B`.
485///
486/// ## Panics
487///
488/// This is [`try_cast_ref`] but will panic on error.
489#[inline]
490#[cfg_attr(feature = "track_caller", track_caller)]
491pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
492  match try_cast_ref(a) {
493    Ok(t) => t,
494    Err(e) => something_went_wrong("cast_ref", e),
495  }
496}
497
498/// Cast `&[A]` into `&[B]`.
499///
500/// ## Panics
501///
502/// This is [`try_cast_slice`] but will panic on error.
503#[inline]
504#[cfg_attr(feature = "track_caller", track_caller)]
505pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
506  match try_cast_slice(a) {
507    Ok(t) => t,
508    Err(e) => something_went_wrong("cast_slice", e),
509  }
510}
511
512/// Cast `&mut [A]` into `&mut [B]`.
513///
514/// ## Panics
515///
516/// This is [`try_cast_slice_mut`] but will panic on error.
517#[inline]
518#[cfg_attr(feature = "track_caller", track_caller)]
519pub fn cast_slice_mut<
520  A: NoUninit + AnyBitPattern,
521  B: NoUninit + CheckedBitPattern,
522>(
523  a: &mut [A],
524) -> &mut [B] {
525  match try_cast_slice_mut(a) {
526    Ok(t) => t,
527    Err(e) => something_went_wrong("cast_slice_mut", e),
528  }
529}