Coverage Report

Created: 2026-08-13 08:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bytemuck-1.25.2/src/checked.rs
Line
Count
Source
1
//! Checked versions of the casting functions exposed in crate root
2
//! that support [`CheckedBitPattern`] types.
3
4
use 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
130
pub 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
143
unsafe impl<T: AnyBitPattern> CheckedBitPattern for T {
144
  type Bits = T;
145
146
  #[inline(always)]
147
0
  fn is_valid_bit_pattern(_bits: &T) -> bool {
148
0
    true
149
0
  }
150
}
151
152
unsafe impl CheckedBitPattern for char {
153
  type Bits = u32;
154
155
  #[inline]
156
0
  fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
157
0
    core::char::from_u32(*bits).is_some()
158
0
  }
159
}
160
161
unsafe impl CheckedBitPattern for bool {
162
  type Bits = u8;
163
164
  #[inline]
165
0
  fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
166
    // DO NOT use the `matches!` macro, it isn't 1.34 compatible.
167
0
    match *bits {
168
0
      0 | 1 => true,
169
0
      _ => false,
170
    }
171
0
  }
172
}
173
174
// Rust 1.70.0 documents that NonZero[int] has the same layout as [int].
175
macro_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
0
        fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
183
0
          *bits != 0
184
0
        }
Unexecuted instantiation: <core::num::nonzero::NonZero<u8> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<i8> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<u16> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<i16> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<u32> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<i32> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<u64> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<i64> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<i128> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<u128> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<usize> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
Unexecuted instantiation: <core::num::nonzero::NonZero<isize> as bytemuck::checked::CheckedBitPattern>::is_valid_bit_pattern
185
      }
186
    )*
187
  };
188
}
189
impl_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)]
207
pub 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"))]
222
impl core::fmt::Display for CheckedCastError {
223
0
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
224
0
    write!(f, "{:?}", self)
225
0
  }
226
}
227
#[cfg(feature = "extern_crate_std")]
228
#[cfg_attr(feature = "nightly_docs", doc(cfg(feature = "extern_crate_std")))]
229
impl 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
))]
237
impl core::error::Error for CheckedCastError {}
238
239
impl From<crate::PodCastError> for CheckedCastError {
240
0
  fn from(err: crate::PodCastError) -> CheckedCastError {
241
0
    CheckedCastError::PodCastError(err)
242
0
  }
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]
253
0
pub fn try_from_bytes<T: CheckedBitPattern>(
254
0
  s: &[u8],
255
0
) -> Result<&T, CheckedCastError> {
256
0
  let pod = crate::try_from_bytes(s)?;
257
258
0
  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
259
0
    Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
260
  } else {
261
0
    Err(CheckedCastError::InvalidBitPattern)
262
  }
263
0
}
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]
273
0
pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
274
0
  s: &mut [u8],
275
0
) -> Result<&mut T, CheckedCastError> {
276
0
  let pod = unsafe { internal::try_from_bytes_mut(s) }?;
277
278
0
  if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
279
0
    Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
280
  } else {
281
0
    Err(CheckedCastError::InvalidBitPattern)
282
  }
283
0
}
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]
291
0
pub fn try_pod_read_unaligned<T: CheckedBitPattern>(
292
0
  bytes: &[u8],
293
0
) -> Result<T, CheckedCastError> {
294
0
  let pod = crate::try_pod_read_unaligned(bytes)?;
295
296
0
  if <T as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
297
0
    Ok(unsafe { transmute!(pod) })
298
  } else {
299
0
    Err(CheckedCastError::InvalidBitPattern)
300
  }
301
0
}
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]
315
0
pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
316
0
  a: A,
317
0
) -> Result<B, CheckedCastError> {
318
0
  let pod = crate::try_cast(a)?;
319
320
0
  if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
321
0
    Ok(unsafe { transmute!(pod) })
322
  } else {
323
0
    Err(CheckedCastError::InvalidBitPattern)
324
  }
325
0
}
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]
335
0
pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
336
0
  a: &A,
337
0
) -> Result<&B, CheckedCastError> {
338
0
  let pod = crate::try_cast_ref(a)?;
339
340
0
  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
341
0
    Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
342
  } else {
343
0
    Err(CheckedCastError::InvalidBitPattern)
344
  }
345
0
}
346
347
/// Try to convert a `&mut A` into `&mut B`.
348
///
349
/// As [`try_cast_ref`], but `mut`.
350
#[inline]
351
0
pub fn try_cast_mut<
352
0
  A: NoUninit + AnyBitPattern,
353
0
  B: CheckedBitPattern + NoUninit,
354
0
>(
355
0
  a: &mut A,
356
0
) -> Result<&mut B, CheckedCastError> {
357
0
  let pod = unsafe { internal::try_cast_mut(a) }?;
358
359
0
  if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
360
0
    Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
361
  } else {
362
0
    Err(CheckedCastError::InvalidBitPattern)
363
  }
364
0
}
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]
382
0
pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
383
0
  a: &[A],
384
0
) -> Result<&[B], CheckedCastError> {
385
0
  let pod = crate::try_cast_slice(a)?;
386
387
0
  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
388
0
    Ok(unsafe {
389
0
      core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
390
0
    })
391
  } else {
392
0
    Err(CheckedCastError::InvalidBitPattern)
393
  }
394
0
}
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]
401
0
pub fn try_cast_slice_mut<
402
0
  A: NoUninit + AnyBitPattern,
403
0
  B: CheckedBitPattern + NoUninit,
404
0
>(
405
0
  a: &mut [A],
406
0
) -> Result<&mut [B], CheckedCastError> {
407
0
  let pod = unsafe { internal::try_cast_slice_mut(a) }?;
408
409
0
  if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
410
0
    Ok(unsafe {
411
0
      core::slice::from_raw_parts_mut(pod.as_mut_ptr() as *mut B, pod.len())
412
0
    })
413
  } else {
414
0
    Err(CheckedCastError::InvalidBitPattern)
415
  }
416
0
}
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)]
425
0
pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
426
0
  match try_from_bytes(s) {
427
0
    Ok(t) => t,
428
0
    Err(e) => something_went_wrong("from_bytes", e),
429
  }
430
0
}
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)]
439
0
pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
440
0
  match try_from_bytes_mut(s) {
441
0
    Ok(t) => t,
442
0
    Err(e) => something_went_wrong("from_bytes_mut", e),
443
  }
444
0
}
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)]
452
0
pub fn pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> T {
453
0
  match try_pod_read_unaligned(bytes) {
454
0
    Ok(t) => t,
455
0
    Err(e) => something_went_wrong("pod_read_unaligned", e),
456
  }
457
0
}
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)]
466
0
pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
467
0
  match try_cast(a) {
468
0
    Ok(t) => t,
469
0
    Err(e) => something_went_wrong("cast", e),
470
  }
471
0
}
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)]
480
0
pub fn cast_mut<
481
0
  A: NoUninit + AnyBitPattern,
482
0
  B: NoUninit + CheckedBitPattern,
483
0
>(
484
0
  a: &mut A,
485
0
) -> &mut B {
486
0
  match try_cast_mut(a) {
487
0
    Ok(t) => t,
488
0
    Err(e) => something_went_wrong("cast_mut", e),
489
  }
490
0
}
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)]
499
0
pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
500
0
  match try_cast_ref(a) {
501
0
    Ok(t) => t,
502
0
    Err(e) => something_went_wrong("cast_ref", e),
503
  }
504
0
}
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)]
513
0
pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
514
0
  match try_cast_slice(a) {
515
0
    Ok(t) => t,
516
0
    Err(e) => something_went_wrong("cast_slice", e),
517
  }
518
0
}
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)]
527
0
pub fn cast_slice_mut<
528
0
  A: NoUninit + AnyBitPattern,
529
0
  B: NoUninit + CheckedBitPattern,
530
0
>(
531
0
  a: &mut [A],
532
0
) -> &mut [B] {
533
0
  match try_cast_slice_mut(a) {
534
0
    Ok(t) => t,
535
0
    Err(e) => something_went_wrong("cast_slice_mut", e),
536
  }
537
0
}