bytemuck/
internal.rs

1//! Internal implementation of casting functions not bound by marker traits
2//! and therefore marked as unsafe. This is used so that we don't need to
3//! duplicate the business logic contained in these functions between the
4//! versions exported in the crate root, `checked`, and `relaxed` modules.
5#![allow(unused_unsafe)]
6
7use crate::PodCastError;
8use core::{marker::*, mem::*};
9
10/*
11
12Note(Lokathor): We've switched all of the `unwrap` to `match` because there is
13apparently a bug: https://github.com/rust-lang/rust/issues/68667
14and it doesn't seem to show up in simple godbolt examples but has been reported
15as having an impact when there's a cast mixed in with other more complicated
16code around it. Rustc/LLVM ends up missing that the `Err` can't ever happen for
17particular type combinations, and then it doesn't fully eliminated the panic
18possibility code branch.
19
20*/
21
22/// Immediately panics.
23#[cfg(not(target_arch = "spirv"))]
24#[cold]
25#[inline(never)]
26pub(crate) fn something_went_wrong<D: core::fmt::Display>(
27  _src: &str, _err: D,
28) -> ! {
29  // Note(Lokathor): Keeping the panic here makes the panic _formatting_ go
30  // here too, which helps assembly readability and also helps keep down
31  // the inline pressure.
32  panic!("{src}>{err}", src = _src, err = _err);
33}
34
35/// Immediately panics.
36#[cfg(target_arch = "spirv")]
37#[cold]
38#[inline(never)]
39pub(crate) fn something_went_wrong<D>(_src: &str, _err: D) -> ! {
40  // Note: On the spirv targets from [rust-gpu](https://github.com/EmbarkStudios/rust-gpu)
41  // panic formatting cannot be used. We we just give a generic error message
42  // The chance that the panicking version of these functions will ever get
43  // called on spir-v targets with invalid inputs is small, but giving a
44  // simple error message is better than no error message at all.
45  panic!("Called a panicing helper from bytemuck which paniced");
46}
47
48/// Re-interprets `&T` as `&[u8]`.
49///
50/// Any ZST becomes an empty slice, and in that case the pointer value of that
51/// empty slice might not match the pointer value of the input reference.
52#[inline(always)]
53pub(crate) unsafe fn bytes_of<T: Copy>(t: &T) -> &[u8] {
54  match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
55    Ok(s) => s,
56    Err(_) => unreachable!(),
57  }
58}
59
60/// Re-interprets `&mut T` as `&mut [u8]`.
61///
62/// Any ZST becomes an empty slice, and in that case the pointer value of that
63/// empty slice might not match the pointer value of the input reference.
64#[inline]
65pub(crate) unsafe fn bytes_of_mut<T: Copy>(t: &mut T) -> &mut [u8] {
66  match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
67    Ok(s) => s,
68    Err(_) => unreachable!(),
69  }
70}
71
72/// Re-interprets `&[u8]` as `&T`.
73///
74/// ## Panics
75///
76/// This is [`try_from_bytes`] but will panic on error.
77#[inline]
78pub(crate) unsafe fn from_bytes<T: Copy>(s: &[u8]) -> &T {
79  match try_from_bytes(s) {
80    Ok(t) => t,
81    Err(e) => something_went_wrong("from_bytes", e),
82  }
83}
84
85/// Re-interprets `&mut [u8]` as `&mut T`.
86///
87/// ## Panics
88///
89/// This is [`try_from_bytes_mut`] but will panic on error.
90#[inline]
91pub(crate) unsafe fn from_bytes_mut<T: Copy>(s: &mut [u8]) -> &mut T {
92  match try_from_bytes_mut(s) {
93    Ok(t) => t,
94    Err(e) => something_went_wrong("from_bytes_mut", e),
95  }
96}
97
98/// Reads from the bytes as if they were a `T`.
99///
100/// ## Failure
101/// * If the `bytes` length is not equal to `size_of::<T>()`.
102#[inline]
103pub(crate) unsafe fn try_pod_read_unaligned<T: Copy>(
104  bytes: &[u8],
105) -> Result<T, PodCastError> {
106  if bytes.len() != size_of::<T>() {
107    Err(PodCastError::SizeMismatch)
108  } else {
109    Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
110  }
111}
112
113/// Reads the slice into a `T` value.
114///
115/// ## Panics
116/// * This is like `try_pod_read_unaligned` but will panic on failure.
117#[inline]
118pub(crate) unsafe fn pod_read_unaligned<T: Copy>(bytes: &[u8]) -> T {
119  match try_pod_read_unaligned(bytes) {
120    Ok(t) => t,
121    Err(e) => something_went_wrong("pod_read_unaligned", e),
122  }
123}
124
125/// Checks if `ptr` is aligned to an `align` memory boundary.
126///
127/// ## Panics
128/// * If `align` is not a power of two. This includes when `align` is zero.
129#[inline]
130pub(crate) fn is_aligned_to(ptr: *const (), align: usize) -> bool {
131  #[cfg(feature = "align_offset")]
132  {
133    // This is in a way better than `ptr as usize % align == 0`,
134    // because casting a pointer to an integer has the side effect that it
135    // exposes the pointer's provenance, which may theoretically inhibit
136    // some compiler optimizations.
137    ptr.align_offset(align) == 0
138  }
139  #[cfg(not(feature = "align_offset"))]
140  {
141    ((ptr as usize) % align) == 0
142  }
143}
144
145/// Re-interprets `&[u8]` as `&T`.
146///
147/// ## Failure
148///
149/// * If the slice isn't aligned for the new type
150/// * If the slice's length isn’t exactly the size of the new type
151#[inline]
152pub(crate) unsafe fn try_from_bytes<T: Copy>(
153  s: &[u8],
154) -> Result<&T, PodCastError> {
155  if s.len() != size_of::<T>() {
156    Err(PodCastError::SizeMismatch)
157  } else if !is_aligned_to(s.as_ptr() as *const (), align_of::<T>()) {
158    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
159  } else {
160    Ok(unsafe { &*(s.as_ptr() as *const T) })
161  }
162}
163
164/// Re-interprets `&mut [u8]` as `&mut T`.
165///
166/// ## Failure
167///
168/// * If the slice isn't aligned for the new type
169/// * If the slice's length isn’t exactly the size of the new type
170#[inline]
171pub(crate) unsafe fn try_from_bytes_mut<T: Copy>(
172  s: &mut [u8],
173) -> Result<&mut T, PodCastError> {
174  if s.len() != size_of::<T>() {
175    Err(PodCastError::SizeMismatch)
176  } else if !is_aligned_to(s.as_ptr() as *const (), align_of::<T>()) {
177    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
178  } else {
179    Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
180  }
181}
182
183/// Cast `T` into `U`
184///
185/// ## Panics
186///
187/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
188#[inline]
189pub(crate) unsafe fn cast<A: Copy, B: Copy>(a: A) -> B {
190  if size_of::<A>() == size_of::<B>() {
191    unsafe { transmute!(a) }
192  } else {
193    something_went_wrong("cast", PodCastError::SizeMismatch)
194  }
195}
196
197/// Cast `&mut T` into `&mut U`.
198///
199/// ## Panics
200///
201/// This is [`try_cast_mut`] but will panic on error.
202#[inline]
203pub(crate) unsafe fn cast_mut<A: Copy, B: Copy>(a: &mut A) -> &mut B {
204  if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
205    // Plz mr compiler, just notice that we can't ever hit Err in this case.
206    match try_cast_mut(a) {
207      Ok(b) => b,
208      Err(_) => unreachable!(),
209    }
210  } else {
211    match try_cast_mut(a) {
212      Ok(b) => b,
213      Err(e) => something_went_wrong("cast_mut", e),
214    }
215  }
216}
217
218/// Cast `&T` into `&U`.
219///
220/// ## Panics
221///
222/// This is [`try_cast_ref`] but will panic on error.
223#[inline]
224pub(crate) unsafe fn cast_ref<A: Copy, B: Copy>(a: &A) -> &B {
225  if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
226    // Plz mr compiler, just notice that we can't ever hit Err in this case.
227    match try_cast_ref(a) {
228      Ok(b) => b,
229      Err(_) => unreachable!(),
230    }
231  } else {
232    match try_cast_ref(a) {
233      Ok(b) => b,
234      Err(e) => something_went_wrong("cast_ref", e),
235    }
236  }
237}
238
239/// Cast `&[A]` into `&[B]`.
240///
241/// ## Panics
242///
243/// This is [`try_cast_slice`] but will panic on error.
244#[inline]
245pub(crate) unsafe fn cast_slice<A: Copy, B: Copy>(a: &[A]) -> &[B] {
246  match try_cast_slice(a) {
247    Ok(b) => b,
248    Err(e) => something_went_wrong("cast_slice", e),
249  }
250}
251
252/// Cast `&mut [T]` into `&mut [U]`.
253///
254/// ## Panics
255///
256/// This is [`try_cast_slice_mut`] but will panic on error.
257#[inline]
258pub(crate) unsafe fn cast_slice_mut<A: Copy, B: Copy>(a: &mut [A]) -> &mut [B] {
259  match try_cast_slice_mut(a) {
260    Ok(b) => b,
261    Err(e) => something_went_wrong("cast_slice_mut", e),
262  }
263}
264
265/// Try to cast `T` into `U`.
266///
267/// Note that for this particular type of cast, alignment isn't a factor. The
268/// input value is semantically copied into the function and then returned to a
269/// new memory location which will have whatever the required alignment of the
270/// output type is.
271///
272/// ## Failure
273///
274/// * If the types don't have the same size this fails.
275#[inline]
276pub(crate) unsafe fn try_cast<A: Copy, B: Copy>(
277  a: A,
278) -> Result<B, PodCastError> {
279  if size_of::<A>() == size_of::<B>() {
280    Ok(unsafe { transmute!(a) })
281  } else {
282    Err(PodCastError::SizeMismatch)
283  }
284}
285
286/// Try to convert a `&T` into `&U`.
287///
288/// ## Failure
289///
290/// * If the reference isn't aligned in the new type
291/// * If the source type and target type aren't the same size.
292#[inline]
293pub(crate) unsafe fn try_cast_ref<A: Copy, B: Copy>(
294  a: &A,
295) -> Result<&B, PodCastError> {
296  // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
297  // after monomorphization.
298  if align_of::<B>() > align_of::<A>()
299    && !is_aligned_to(a as *const A as *const (), align_of::<B>())
300  {
301    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
302  } else if size_of::<B>() == size_of::<A>() {
303    Ok(unsafe { &*(a as *const A as *const B) })
304  } else {
305    Err(PodCastError::SizeMismatch)
306  }
307}
308
309/// Try to convert a `&mut T` into `&mut U`.
310///
311/// As [`try_cast_ref`], but `mut`.
312#[inline]
313pub(crate) unsafe fn try_cast_mut<A: Copy, B: Copy>(
314  a: &mut A,
315) -> Result<&mut B, PodCastError> {
316  // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
317  // after monomorphization.
318  if align_of::<B>() > align_of::<A>()
319    && !is_aligned_to(a as *const A as *const (), align_of::<B>())
320  {
321    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
322  } else if size_of::<B>() == size_of::<A>() {
323    Ok(unsafe { &mut *(a as *mut A as *mut B) })
324  } else {
325    Err(PodCastError::SizeMismatch)
326  }
327}
328
329/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
330///
331/// * `input.as_ptr() as usize == output.as_ptr() as usize`
332/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
333///
334/// ## Failure
335///
336/// * If the target type has a greater alignment requirement and the input slice
337///   isn't aligned.
338/// * If the target element type is a different size from the current element
339///   type, and the output slice wouldn't be a whole number of elements when
340///   accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
341///   that's a failure).
342#[inline]
343pub(crate) unsafe fn try_cast_slice<A: Copy, B: Copy>(
344  a: &[A],
345) -> Result<&[B], PodCastError> {
346  let input_bytes = core::mem::size_of_val::<[A]>(a);
347  // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
348  // after monomorphization.
349  if align_of::<B>() > align_of::<A>()
350    && !is_aligned_to(a.as_ptr() as *const (), align_of::<B>())
351  {
352    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
353  } else if size_of::<B>() == size_of::<A>() {
354    Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, a.len()) })
355  } else if (size_of::<B>() != 0 && input_bytes % size_of::<B>() == 0)
356    || (size_of::<B>() == 0 && input_bytes == 0)
357  {
358    let new_len =
359      if size_of::<B>() != 0 { input_bytes / size_of::<B>() } else { 0 };
360    Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, new_len) })
361  } else {
362    Err(PodCastError::OutputSliceWouldHaveSlop)
363  }
364}
365
366/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
367/// length).
368///
369/// As [`try_cast_slice`], but `&mut`.
370#[inline]
371pub(crate) unsafe fn try_cast_slice_mut<A: Copy, B: Copy>(
372  a: &mut [A],
373) -> Result<&mut [B], PodCastError> {
374  let input_bytes = core::mem::size_of_val::<[A]>(a);
375  // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
376  // after monomorphization.
377  if align_of::<B>() > align_of::<A>()
378    && !is_aligned_to(a.as_ptr() as *const (), align_of::<B>())
379  {
380    Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
381  } else if size_of::<B>() == size_of::<A>() {
382    Ok(unsafe {
383      core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, a.len())
384    })
385  } else if (size_of::<B>() != 0 && input_bytes % size_of::<B>() == 0)
386    || (size_of::<B>() == 0 && input_bytes == 0)
387  {
388    let new_len =
389      if size_of::<B>() != 0 { input_bytes / size_of::<B>() } else { 0 };
390    Ok(unsafe {
391      core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, new_len)
392    })
393  } else {
394    Err(PodCastError::OutputSliceWouldHaveSlop)
395  }
396}