Skip to main content

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