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