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
118/// the 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 match *bits {
167 0 | 1 => true,
168 _ => false,
169 }
170 }
171}
172
173// Rust 1.70.0 documents that NonZero[int] has the same layout as [int].
174macro_rules! impl_checked_for_nonzero {
175 ($($nonzero:ty: $primitive:ty),* $(,)?) => {
176 $(
177 unsafe impl CheckedBitPattern for $nonzero {
178 type Bits = $primitive;
179
180 #[inline]
181 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
182 *bits != 0
183 }
184 }
185 )*
186 };
187}
188impl_checked_for_nonzero! {
189 core::num::NonZeroU8: u8,
190 core::num::NonZeroI8: i8,
191 core::num::NonZeroU16: u16,
192 core::num::NonZeroI16: i16,
193 core::num::NonZeroU32: u32,
194 core::num::NonZeroI32: i32,
195 core::num::NonZeroU64: u64,
196 core::num::NonZeroI64: i64,
197 core::num::NonZeroI128: i128,
198 core::num::NonZeroU128: u128,
199 core::num::NonZeroUsize: usize,
200 core::num::NonZeroIsize: isize,
201}
202
203/// The things that can go wrong when casting between [`CheckedBitPattern`] data
204/// forms.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206pub enum CheckedCastError {
207 /// An error occurred during a true-[`Pod`] cast
208 ///
209 /// [`Pod`]: crate::Pod
210 PodCastError(crate::PodCastError),
211 /// When casting to a [`CheckedBitPattern`] type, it is possible that the
212 /// original data contains an invalid bit pattern. If so, the cast will
213 /// fail and this error will be returned. Will never happen on casts
214 /// between [`Pod`] types.
215 ///
216 /// [`Pod`]: crate::Pod
217 InvalidBitPattern,
218}
219
220#[cfg(not(target_arch = "spirv"))]
221impl core::fmt::Display for CheckedCastError {
222 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
223 write!(f, "{:?}", self)
224 }
225}
226#[cfg(feature = "extern_crate_std")]
227#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_std")))]
228impl std::error::Error for CheckedCastError {}
229
230impl From<crate::PodCastError> for CheckedCastError {
231 fn from(err: crate::PodCastError) -> CheckedCastError {
232 CheckedCastError::PodCastError(err)
233 }
234}
235
236/// Re-interprets `&[u8]` as `&T`.
237///
238/// ## Failure
239///
240/// * If the slice isn't aligned for the new type
241/// * If the slice's length isn’t exactly the size of the new type
242/// * If the slice contains an invalid bit pattern for `T`
243#[inline]
244pub fn try_from_bytes<T: CheckedBitPattern>(
245 s: &[u8],
246) -> Result<&T, CheckedCastError> {
247 let pod = crate::try_from_bytes(s)?;
248
249 if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
250 Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
251 } else {
252 Err(CheckedCastError::InvalidBitPattern)
253 }
254}
255
256/// Re-interprets `&mut [u8]` as `&mut T`.
257///
258/// ## Failure
259///
260/// * If the slice isn't aligned for the new type
261/// * If the slice's length isn’t exactly the size of the new type
262/// * If the slice contains an invalid bit pattern for `T`
263#[inline]
264pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
265 s: &mut [u8],
266) -> Result<&mut T, CheckedCastError> {
267 let pod = unsafe { internal::try_from_bytes_mut(s) }?;
268
269 if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
270 Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
271 } else {
272 Err(CheckedCastError::InvalidBitPattern)
273 }
274}
275
276/// Reads from the bytes as if they were a `T`.
277///
278/// ## Failure
279/// * If the `bytes` length is not equal to `size_of::<T>()`.
280/// * If the slice contains an invalid bit pattern for `T`
281#[inline]
282pub fn try_pod_read_unaligned<T: CheckedBitPattern>(
283 bytes: &[u8],
284) -> Result<T, CheckedCastError> {
285 let pod = crate::try_pod_read_unaligned(bytes)?;
286
287 if <T as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
288 Ok(unsafe { transmute!(pod) })
289 } else {
290 Err(CheckedCastError::InvalidBitPattern)
291 }
292}
293
294/// Try to cast `T` into `U`.
295///
296/// Note that for this particular type of cast, alignment isn't a factor. The
297/// input value is semantically copied into the function and then returned to a
298/// new memory location which will have whatever the required alignment of the
299/// output type is.
300///
301/// ## Failure
302///
303/// * If the types don't have the same size this fails.
304/// * If `a` contains an invalid bit pattern for `B` this fails.
305#[inline]
306pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
307 a: A,
308) -> Result<B, CheckedCastError> {
309 let pod = crate::try_cast(a)?;
310
311 if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
312 Ok(unsafe { transmute!(pod) })
313 } else {
314 Err(CheckedCastError::InvalidBitPattern)
315 }
316}
317
318/// Try to convert a `&T` into `&U`.
319///
320/// ## Failure
321///
322/// * If the reference isn't aligned in the new type
323/// * If the source type and target type aren't the same size.
324/// * If `a` contains an invalid bit pattern for `B` this fails.
325#[inline]
326pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
327 a: &A,
328) -> Result<&B, CheckedCastError> {
329 let pod = crate::try_cast_ref(a)?;
330
331 if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
332 Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
333 } else {
334 Err(CheckedCastError::InvalidBitPattern)
335 }
336}
337
338/// Try to convert a `&mut T` into `&mut U`.
339///
340/// As [`try_cast_ref`], but `mut`.
341#[inline]
342pub fn try_cast_mut<
343 A: NoUninit + AnyBitPattern,
344 B: CheckedBitPattern + NoUninit,
345>(
346 a: &mut A,
347) -> Result<&mut B, CheckedCastError> {
348 let pod = unsafe { internal::try_cast_mut(a) }?;
349
350 if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
351 Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
352 } else {
353 Err(CheckedCastError::InvalidBitPattern)
354 }
355}
356
357/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
358///
359/// * `input.as_ptr() as usize == output.as_ptr() as usize`
360/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
361///
362/// ## Failure
363///
364/// * If the target type has a greater alignment requirement and the input slice
365/// isn't aligned.
366/// * If the target element type is a different size from the current element
367/// type, and the output slice wouldn't be a whole number of elements when
368/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
369/// that's a failure).
370/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
371/// and a non-ZST.
372/// * If any element of the converted slice would contain an invalid bit pattern
373/// for `B` this fails.
374#[inline]
375pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
376 a: &[A],
377) -> Result<&[B], CheckedCastError> {
378 let pod = crate::try_cast_slice(a)?;
379
380 if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
381 Ok(unsafe {
382 core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
383 })
384 } else {
385 Err(CheckedCastError::InvalidBitPattern)
386 }
387}
388
389/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
390/// length).
391///
392/// As [`try_cast_slice`], but `&mut`.
393#[inline]
394pub fn try_cast_slice_mut<
395 A: NoUninit + AnyBitPattern,
396 B: CheckedBitPattern + NoUninit,
397>(
398 a: &mut [A],
399) -> Result<&mut [B], CheckedCastError> {
400 let pod = unsafe { internal::try_cast_slice_mut(a) }?;
401
402 if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
403 Ok(unsafe {
404 core::slice::from_raw_parts_mut(pod.as_mut_ptr() as *mut B, pod.len())
405 })
406 } else {
407 Err(CheckedCastError::InvalidBitPattern)
408 }
409}
410
411/// Re-interprets `&[u8]` as `&T`.
412///
413/// ## Panics
414///
415/// This is [`try_from_bytes`] but will panic on error.
416#[inline]
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]
430pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
431 match try_from_bytes_mut(s) {
432 Ok(t) => t,
433 Err(e) => something_went_wrong("from_bytes_mut", e),
434 }
435}
436
437/// Reads the slice into a `T` value.
438///
439/// ## Panics
440/// * This is like `try_pod_read_unaligned` but will panic on failure.
441#[inline]
442pub fn pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> T {
443 match try_pod_read_unaligned(bytes) {
444 Ok(t) => t,
445 Err(e) => something_went_wrong("pod_read_unaligned", e),
446 }
447}
448
449/// Cast `T` into `U`
450///
451/// ## Panics
452///
453/// * This is like [`try_cast`], but will panic on a size mismatch.
454#[inline]
455pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
456 match try_cast(a) {
457 Ok(t) => t,
458 Err(e) => something_went_wrong("cast", e),
459 }
460}
461
462/// Cast `&mut T` into `&mut U`.
463///
464/// ## Panics
465///
466/// This is [`try_cast_mut`] but will panic on error.
467#[inline]
468pub fn cast_mut<
469 A: NoUninit + AnyBitPattern,
470 B: NoUninit + CheckedBitPattern,
471>(
472 a: &mut A,
473) -> &mut B {
474 match try_cast_mut(a) {
475 Ok(t) => t,
476 Err(e) => something_went_wrong("cast_mut", e),
477 }
478}
479
480/// Cast `&T` into `&U`.
481///
482/// ## Panics
483///
484/// This is [`try_cast_ref`] but will panic on error.
485#[inline]
486pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
487 match try_cast_ref(a) {
488 Ok(t) => t,
489 Err(e) => something_went_wrong("cast_ref", e),
490 }
491}
492
493/// Cast `&[A]` into `&[B]`.
494///
495/// ## Panics
496///
497/// This is [`try_cast_slice`] but will panic on error.
498#[inline]
499pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
500 match try_cast_slice(a) {
501 Ok(t) => t,
502 Err(e) => something_went_wrong("cast_slice", e),
503 }
504}
505
506/// Cast `&mut [T]` into `&mut [U]`.
507///
508/// ## Panics
509///
510/// This is [`try_cast_slice_mut`] but will panic on error.
511#[inline]
512pub fn cast_slice_mut<
513 A: NoUninit + AnyBitPattern,
514 B: NoUninit + CheckedBitPattern,
515>(
516 a: &mut [A],
517) -> &mut [B] {
518 match try_cast_slice_mut(a) {
519 Ok(t) => t,
520 Err(e) => something_went_wrong("cast_slice_mut", e),
521 }
522}