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 if size_of::<T>() == 0 {
55 &[]
56 } else {
57 match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
58 Ok(s: &[u8]) => s,
59 Err(_) => unreachable!(),
60 }
61 }
62}
63
64/// Re-interprets `&mut T` as `&mut [u8]`.
65///
66/// Any ZST becomes an empty slice, and in that case the pointer value of that
67/// empty slice might not match the pointer value of the input reference.
68#[inline]
69pub(crate) unsafe fn bytes_of_mut<T: Copy>(t: &mut T) -> &mut [u8] {
70 if size_of::<T>() == 0 {
71 &mut []
72 } else {
73 match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
74 Ok(s: &mut [u8]) => s,
75 Err(_) => unreachable!(),
76 }
77 }
78}
79
80/// Re-interprets `&[u8]` as `&T`.
81///
82/// ## Panics
83///
84/// This is [`try_from_bytes`] but will panic on error.
85#[inline]
86pub(crate) unsafe fn from_bytes<T: Copy>(s: &[u8]) -> &T {
87 match try_from_bytes(s) {
88 Ok(t: &T) => t,
89 Err(e: PodCastError) => something_went_wrong(_src:"from_bytes", _err:e),
90 }
91}
92
93/// Re-interprets `&mut [u8]` as `&mut T`.
94///
95/// ## Panics
96///
97/// This is [`try_from_bytes_mut`] but will panic on error.
98#[inline]
99pub(crate) unsafe fn from_bytes_mut<T: Copy>(s: &mut [u8]) -> &mut T {
100 match try_from_bytes_mut(s) {
101 Ok(t: &mut T) => t,
102 Err(e: PodCastError) => something_went_wrong(_src:"from_bytes_mut", _err:e),
103 }
104}
105
106/// Reads from the bytes as if they were a `T`.
107///
108/// ## Failure
109/// * If the `bytes` length is not equal to `size_of::<T>()`.
110#[inline]
111pub(crate) unsafe fn try_pod_read_unaligned<T: Copy>(
112 bytes: &[u8],
113) -> Result<T, PodCastError> {
114 if bytes.len() != size_of::<T>() {
115 Err(PodCastError::SizeMismatch)
116 } else {
117 Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
118 }
119}
120
121/// Reads the slice into a `T` value.
122///
123/// ## Panics
124/// * This is like `try_pod_read_unaligned` but will panic on failure.
125#[inline]
126pub(crate) unsafe fn pod_read_unaligned<T: Copy>(bytes: &[u8]) -> T {
127 match try_pod_read_unaligned(bytes) {
128 Ok(t: T) => t,
129 Err(e: PodCastError) => something_went_wrong(_src:"pod_read_unaligned", _err:e),
130 }
131}
132
133/// Checks if `ptr` is aligned to an `align` memory boundary.
134///
135/// ## Panics
136/// * If `align` is not a power of two. This includes when `align` is zero.
137#[inline]
138pub(crate) fn is_aligned_to(ptr: *const (), align: usize) -> bool {
139 #[cfg(feature = "align_offset")]
140 {
141 // This is in a way better than `ptr as usize % align == 0`,
142 // because casting a pointer to an integer has the side effect that it
143 // exposes the pointer's provenance, which may theoretically inhibit
144 // some compiler optimizations.
145 ptr.align_offset(align) == 0
146 }
147 #[cfg(not(feature = "align_offset"))]
148 {
149 ((ptr as usize) % align) == 0
150 }
151}
152
153/// Re-interprets `&[u8]` as `&T`.
154///
155/// ## Failure
156///
157/// * If the slice isn't aligned for the new type
158/// * If the slice's length isn’t exactly the size of the new type
159#[inline]
160pub(crate) unsafe fn try_from_bytes<T: Copy>(
161 s: &[u8],
162) -> Result<&T, PodCastError> {
163 if s.len() != size_of::<T>() {
164 Err(PodCastError::SizeMismatch)
165 } else if !is_aligned_to(s.as_ptr() as *const (), align:align_of::<T>()) {
166 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
167 } else {
168 Ok(unsafe { &*(s.as_ptr() as *const T) })
169 }
170}
171
172/// Re-interprets `&mut [u8]` as `&mut T`.
173///
174/// ## Failure
175///
176/// * If the slice isn't aligned for the new type
177/// * If the slice's length isn’t exactly the size of the new type
178#[inline]
179pub(crate) unsafe fn try_from_bytes_mut<T: Copy>(
180 s: &mut [u8],
181) -> Result<&mut T, PodCastError> {
182 if s.len() != size_of::<T>() {
183 Err(PodCastError::SizeMismatch)
184 } else if !is_aligned_to(s.as_ptr() as *const (), align:align_of::<T>()) {
185 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
186 } else {
187 Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
188 }
189}
190
191/// Cast `T` into `U`
192///
193/// ## Panics
194///
195/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
196#[inline]
197pub(crate) unsafe fn cast<A: Copy, B: Copy>(a: A) -> B {
198 if size_of::<A>() == size_of::<B>() {
199 unsafe { transmute!(a) }
200 } else {
201 something_went_wrong(_src:"cast", _err:PodCastError::SizeMismatch)
202 }
203}
204
205/// Cast `&mut T` into `&mut U`.
206///
207/// ## Panics
208///
209/// This is [`try_cast_mut`] but will panic on error.
210#[inline]
211pub(crate) unsafe fn cast_mut<A: Copy, B: Copy>(a: &mut A) -> &mut B {
212 if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
213 // Plz mr compiler, just notice that we can't ever hit Err in this case.
214 match try_cast_mut(a) {
215 Ok(b: &mut B) => b,
216 Err(_) => unreachable!(),
217 }
218 } else {
219 match try_cast_mut(a) {
220 Ok(b: &mut B) => b,
221 Err(e: PodCastError) => something_went_wrong(_src:"cast_mut", _err:e),
222 }
223 }
224}
225
226/// Cast `&T` into `&U`.
227///
228/// ## Panics
229///
230/// This is [`try_cast_ref`] but will panic on error.
231#[inline]
232pub(crate) unsafe fn cast_ref<A: Copy, B: Copy>(a: &A) -> &B {
233 if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
234 // Plz mr compiler, just notice that we can't ever hit Err in this case.
235 match try_cast_ref(a) {
236 Ok(b: &B) => b,
237 Err(_) => unreachable!(),
238 }
239 } else {
240 match try_cast_ref(a) {
241 Ok(b: &B) => b,
242 Err(e: PodCastError) => something_went_wrong(_src:"cast_ref", _err:e),
243 }
244 }
245}
246
247/// Cast `&[A]` into `&[B]`.
248///
249/// ## Panics
250///
251/// This is [`try_cast_slice`] but will panic on error.
252#[inline]
253pub(crate) unsafe fn cast_slice<A: Copy, B: Copy>(a: &[A]) -> &[B] {
254 match try_cast_slice(a) {
255 Ok(b: &[B]) => b,
256 Err(e: PodCastError) => something_went_wrong(_src:"cast_slice", _err:e),
257 }
258}
259
260/// Cast `&mut [T]` into `&mut [U]`.
261///
262/// ## Panics
263///
264/// This is [`try_cast_slice_mut`] but will panic on error.
265#[inline]
266pub(crate) unsafe fn cast_slice_mut<A: Copy, B: Copy>(a: &mut [A]) -> &mut [B] {
267 match try_cast_slice_mut(a) {
268 Ok(b: &mut [B]) => b,
269 Err(e: PodCastError) => something_went_wrong(_src:"cast_slice_mut", _err:e),
270 }
271}
272
273/// Try to cast `T` into `U`.
274///
275/// Note that for this particular type of cast, alignment isn't a factor. The
276/// input value is semantically copied into the function and then returned to a
277/// new memory location which will have whatever the required alignment of the
278/// output type is.
279///
280/// ## Failure
281///
282/// * If the types don't have the same size this fails.
283#[inline]
284pub(crate) unsafe fn try_cast<A: Copy, B: Copy>(
285 a: A,
286) -> Result<B, PodCastError> {
287 if size_of::<A>() == size_of::<B>() {
288 Ok(unsafe { transmute!(a) })
289 } else {
290 Err(PodCastError::SizeMismatch)
291 }
292}
293
294/// Try to convert a `&T` into `&U`.
295///
296/// ## Failure
297///
298/// * If the reference isn't aligned in the new type
299/// * If the source type and target type aren't the same size.
300#[inline]
301pub(crate) unsafe fn try_cast_ref<A: Copy, B: Copy>(
302 a: &A,
303) -> Result<&B, PodCastError> {
304 // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
305 // after monomorphization.
306 if align_of::<B>() > align_of::<A>()
307 && !is_aligned_to(ptr:a as *const A as *const (), align:align_of::<B>())
308 {
309 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
310 } else if size_of::<B>() == size_of::<A>() {
311 Ok(unsafe { &*(a as *const A as *const B) })
312 } else {
313 Err(PodCastError::SizeMismatch)
314 }
315}
316
317/// Try to convert a `&mut T` into `&mut U`.
318///
319/// As [`try_cast_ref`], but `mut`.
320#[inline]
321pub(crate) unsafe fn try_cast_mut<A: Copy, B: Copy>(
322 a: &mut A,
323) -> Result<&mut B, PodCastError> {
324 // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
325 // after monomorphization.
326 if align_of::<B>() > align_of::<A>()
327 && !is_aligned_to(ptr:a as *const A as *const (), align:align_of::<B>())
328 {
329 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
330 } else if size_of::<B>() == size_of::<A>() {
331 Ok(unsafe { &mut *(a as *mut A as *mut B) })
332 } else {
333 Err(PodCastError::SizeMismatch)
334 }
335}
336
337/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
338///
339/// * `input.as_ptr() as usize == output.as_ptr() as usize`
340/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
341///
342/// ## Failure
343///
344/// * If the target type has a greater alignment requirement and the input slice
345/// isn't aligned.
346/// * If the target element type is a different size from the current element
347/// type, and the output slice wouldn't be a whole number of elements when
348/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
349/// that's a failure).
350/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
351/// and a non-ZST.
352#[inline]
353pub(crate) unsafe fn try_cast_slice<A: Copy, B: Copy>(
354 a: &[A],
355) -> Result<&[B], PodCastError> {
356 // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
357 // after monomorphization.
358 if align_of::<B>() > align_of::<A>()
359 && !is_aligned_to(a.as_ptr() as *const (), align:align_of::<B>())
360 {
361 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
362 } else if size_of::<B>() == size_of::<A>() {
363 Ok(unsafe { core::slice::from_raw_parts(data:a.as_ptr() as *const B, a.len()) })
364 } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
365 Err(PodCastError::SizeMismatch)
366 } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
367 let new_len: usize = core::mem::size_of_val(a) / size_of::<B>();
368 Ok(unsafe { core::slice::from_raw_parts(data:a.as_ptr() as *const B, new_len) })
369 } else {
370 Err(PodCastError::OutputSliceWouldHaveSlop)
371 }
372}
373
374/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
375/// length).
376///
377/// As [`try_cast_slice`], but `&mut`.
378#[inline]
379pub(crate) unsafe fn try_cast_slice_mut<A: Copy, B: Copy>(
380 a: &mut [A],
381) -> Result<&mut [B], PodCastError> {
382 // Note(Lokathor): everything with `align_of` and `size_of` will optimize away
383 // after monomorphization.
384 if align_of::<B>() > align_of::<A>()
385 && !is_aligned_to(a.as_ptr() as *const (), align:align_of::<B>())
386 {
387 Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
388 } else if size_of::<B>() == size_of::<A>() {
389 Ok(unsafe {
390 core::slice::from_raw_parts_mut(data:a.as_mut_ptr() as *mut B, a.len())
391 })
392 } else if size_of::<A>() == 0 || size_of::<B>() == 0 {
393 Err(PodCastError::SizeMismatch)
394 } else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
395 let new_len: usize = core::mem::size_of_val(a) / size_of::<B>();
396 Ok(unsafe {
397 core::slice::from_raw_parts_mut(data:a.as_mut_ptr() as *mut B, new_len)
398 })
399 } else {
400 Err(PodCastError::OutputSliceWouldHaveSlop)
401 }
402}
403