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
231// Rust 1.81+
232#[cfg(all(feature = "impl_core_error", not(feature = "extern_crate_std")))]
233impl core::error::Error for CheckedCastError {}
234
235impl From<crate::PodCastError> for CheckedCastError {
236  fn from(err: crate::PodCastError) -> CheckedCastError {
237    CheckedCastError::PodCastError(err)
238  }
239}
240
241/// Re-interprets `&[u8]` as `&T`.
242///
243/// ## Failure
244///
245/// * If the slice isn't aligned for the new type
246/// * If the slice's length isn’t exactly the size of the new type
247/// * If the slice contains an invalid bit pattern for `T`
248#[inline]
249pub fn try_from_bytes<T: CheckedBitPattern>(
250  s: &[u8],
251) -> Result<&T, CheckedCastError> {
252  let pod = crate::try_from_bytes(s)?;
253
254  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
255    Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
256  } else {
257    Err(CheckedCastError::InvalidBitPattern)
258  }
259}
260
261/// Re-interprets `&mut [u8]` as `&mut T`.
262///
263/// ## Failure
264///
265/// * If the slice isn't aligned for the new type
266/// * If the slice's length isn’t exactly the size of the new type
267/// * If the slice contains an invalid bit pattern for `T`
268#[inline]
269pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
270  s: &mut [u8],
271) -> Result<&mut T, CheckedCastError> {
272  let pod = unsafe { internal::try_from_bytes_mut(s) }?;
273
274  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
275    Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
276  } else {
277    Err(CheckedCastError::InvalidBitPattern)
278  }
279}
280
281/// Reads from the bytes as if they were a `T`.
282///
283/// ## Failure
284/// * If the `bytes` length is not equal to `size_of::<T>()`.
285/// * If the slice contains an invalid bit pattern for `T`
286#[inline]
287pub fn try_pod_read_unaligned<T: CheckedBitPattern>(
288  bytes: &[u8],
289) -> Result<T, CheckedCastError> {
290  let pod = crate::try_pod_read_unaligned(bytes)?;
291
292  if <T as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
293    Ok(unsafe { transmute!(pod) })
294  } else {
295    Err(CheckedCastError::InvalidBitPattern)
296  }
297}
298
299/// Try to cast `A` into `B`.
300///
301/// Note that for this particular type of cast, alignment isn't a factor. The
302/// input value is semantically copied into the function and then returned to a
303/// new memory location which will have whatever the required alignment of the
304/// output type is.
305///
306/// ## Failure
307///
308/// * If the types don't have the same size this fails.
309/// * If `a` contains an invalid bit pattern for `B` this fails.
310#[inline]
311pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
312  a: A,
313) -> Result<B, CheckedCastError> {
314  let pod = crate::try_cast(a)?;
315
316  if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
317    Ok(unsafe { transmute!(pod) })
318  } else {
319    Err(CheckedCastError::InvalidBitPattern)
320  }
321}
322
323/// Try to convert a `&A` into `&B`.
324///
325/// ## Failure
326///
327/// * If the reference isn't aligned in the new type
328/// * If the source type and target type aren't the same size.
329/// * If `a` contains an invalid bit pattern for `B` this fails.
330#[inline]
331pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
332  a: &A,
333) -> Result<&B, CheckedCastError> {
334  let pod = crate::try_cast_ref(a)?;
335
336  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
337    Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
338  } else {
339    Err(CheckedCastError::InvalidBitPattern)
340  }
341}
342
343/// Try to convert a `&mut A` into `&mut B`.
344///
345/// As [`try_cast_ref`], but `mut`.
346#[inline]
347pub fn try_cast_mut<
348  A: NoUninit + AnyBitPattern,
349  B: CheckedBitPattern + NoUninit,
350>(
351  a: &mut A,
352) -> Result<&mut B, CheckedCastError> {
353  let pod = unsafe { internal::try_cast_mut(a) }?;
354
355  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
356    Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
357  } else {
358    Err(CheckedCastError::InvalidBitPattern)
359  }
360}
361
362/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
363///
364/// * `input.as_ptr() as usize == output.as_ptr() as usize`
365/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
366///
367/// ## Failure
368///
369/// * If the target type has a greater alignment requirement and the input slice
370///   isn't aligned.
371/// * If the target element type is a different size from the current element
372///   type, and the output slice wouldn't be a whole number of elements when
373///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
374///   that's a failure).
375/// * If any element of the converted slice would contain an invalid bit pattern
376///   for `B` this fails.
377#[inline]
378pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
379  a: &[A],
380) -> Result<&[B], CheckedCastError> {
381  let pod = crate::try_cast_slice(a)?;
382
383  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
384    Ok(unsafe {
385      core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
386    })
387  } else {
388    Err(CheckedCastError::InvalidBitPattern)
389  }
390}
391
392/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
393/// length).
394///
395/// As [`try_cast_slice`], but `&mut`.
396#[inline]
397pub fn try_cast_slice_mut<
398  A: NoUninit + AnyBitPattern,
399  B: CheckedBitPattern + NoUninit,
400>(
401  a: &mut [A],
402) -> Result<&mut [B], CheckedCastError> {
403  let pod = unsafe { internal::try_cast_slice_mut(a) }?;
404
405  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
406    Ok(unsafe {
407      core::slice::from_raw_parts_mut(pod.as_mut_ptr() as *mut B, pod.len())
408    })
409  } else {
410    Err(CheckedCastError::InvalidBitPattern)
411  }
412}
413
414/// Re-interprets `&[u8]` as `&T`.
415///
416/// ## Panics
417///
418/// This is [`try_from_bytes`] but will panic on error.
419#[inline]
420#[cfg_attr(feature = "track_caller", track_caller)]
421pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
422  match try_from_bytes(s) {
423    Ok(t) => t,
424    Err(e) => something_went_wrong("from_bytes", e),
425  }
426}
427
428/// Re-interprets `&mut [u8]` as `&mut T`.
429///
430/// ## Panics
431///
432/// This is [`try_from_bytes_mut`] but will panic on error.
433#[inline]
434#[cfg_attr(feature = "track_caller", track_caller)]
435pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
436  match try_from_bytes_mut(s) {
437    Ok(t) => t,
438    Err(e) => something_went_wrong("from_bytes_mut", e),
439  }
440}
441
442/// Reads the slice into a `T` value.
443///
444/// ## Panics
445/// * This is like [`try_pod_read_unaligned`] but will panic on failure.
446#[inline]
447#[cfg_attr(feature = "track_caller", track_caller)]
448pub fn pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> T {
449  match try_pod_read_unaligned(bytes) {
450    Ok(t) => t,
451    Err(e) => something_went_wrong("pod_read_unaligned", e),
452  }
453}
454
455/// Cast `A` into `B`
456///
457/// ## Panics
458///
459/// * This is like [`try_cast`], but will panic on a size mismatch.
460#[inline]
461#[cfg_attr(feature = "track_caller", track_caller)]
462pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
463  match try_cast(a) {
464    Ok(t) => t,
465    Err(e) => something_went_wrong("cast", e),
466  }
467}
468
469/// Cast `&mut A` into `&mut B`.
470///
471/// ## Panics
472///
473/// This is [`try_cast_mut`] but will panic on error.
474#[inline]
475#[cfg_attr(feature = "track_caller", track_caller)]
476pub fn cast_mut<
477  A: NoUninit + AnyBitPattern,
478  B: NoUninit + CheckedBitPattern,
479>(
480  a: &mut A,
481) -> &mut B {
482  match try_cast_mut(a) {
483    Ok(t) => t,
484    Err(e) => something_went_wrong("cast_mut", e),
485  }
486}
487
488/// Cast `&A` into `&B`.
489///
490/// ## Panics
491///
492/// This is [`try_cast_ref`] but will panic on error.
493#[inline]
494#[cfg_attr(feature = "track_caller", track_caller)]
495pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
496  match try_cast_ref(a) {
497    Ok(t) => t,
498    Err(e) => something_went_wrong("cast_ref", e),
499  }
500}
501
502/// Cast `&[A]` into `&[B]`.
503///
504/// ## Panics
505///
506/// This is [`try_cast_slice`] but will panic on error.
507#[inline]
508#[cfg_attr(feature = "track_caller", track_caller)]
509pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
510  match try_cast_slice(a) {
511    Ok(t) => t,
512    Err(e) => something_went_wrong("cast_slice", e),
513  }
514}
515
516/// Cast `&mut [A]` into `&mut [B]`.
517///
518/// ## Panics
519///
520/// This is [`try_cast_slice_mut`] but will panic on error.
521#[inline]
522#[cfg_attr(feature = "track_caller", track_caller)]
523pub fn cast_slice_mut<
524  A: NoUninit + AnyBitPattern,
525  B: NoUninit + CheckedBitPattern,
526>(
527  a: &mut [A],
528) -> &mut [B] {
529  match try_cast_slice_mut(a) {
530    Ok(t) => t,
531    Err(e) => something_went_wrong("cast_slice_mut", e),
532  }
533}