Skip to content

Commit a7fc367

Browse files
authored
cmov: simplify slice casts (#1381)
We can cast them directly, rather than reconstructing them
1 parent 2fd4892 commit a7fc367

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

cmov/src/slice.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -255,40 +255,42 @@ impl_cmoveq_with_loop!(u16, u32, u64, u128);
255255

256256
/// Performs an unsafe pointer cast from one slice type to the other.
257257
///
258-
/// # Panics
258+
/// # Compile-time panics
259259
/// - If `T` and `U` differ in size
260260
/// - If `T` and `U` differ in alignment
261-
#[allow(unsafe_code)]
262261
unsafe fn cast_slice<T, U>(slice: &[T]) -> &[U] {
263262
const {
264263
assert!(size_of::<T>() == size_of::<U>(), "T/U size differs");
265264
assert!(align_of::<T>() == align_of::<U>(), "T/U alignment differs");
266265
}
267266

268267
// SAFETY:
269-
// - Slices being constructed are of same-sized/aligned types as asserted above.
270-
// - We source the slice length directly from the other valid slice.
271-
// - It's up to the caller to ensure the pointer cast itself is valid.
272-
unsafe { slice::from_raw_parts(slice.as_ptr() as *const U, slice.len()) }
268+
// - Slices are of same-sized/aligned types as asserted above.
269+
// - It's up to the caller to ensure the pointer cast from `T` to `U` itself is valid.
270+
#[allow(trivial_casts, unsafe_code)]
271+
unsafe {
272+
&*((slice as *const [T]) as *const [U])
273+
}
273274
}
274275

275276
/// Performs an unsafe pointer cast from one mutable slice type to the other.
276277
///
277-
/// # Panics
278+
/// # Compile-time panics
278279
/// - If `T` and `U` differ in size
279280
/// - If `T` and `U` differ in alignment
280-
#[allow(unsafe_code)]
281281
unsafe fn cast_slice_mut<T, U>(slice: &mut [T]) -> &mut [U] {
282282
const {
283283
assert!(size_of::<T>() == size_of::<U>(), "T/U size differs");
284284
assert!(align_of::<T>() == align_of::<U>(), "T/U alignment differs");
285285
}
286286

287287
// SAFETY:
288-
// - Slices being constructed are of same-sized/aligned types as asserted above.
289-
// - We source the slice length directly from the other valid slice.
290-
// - It's up to the caller to ensure the pointer cast itself is valid.
291-
unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut U, slice.len()) }
288+
// - Slices are of same-sized/aligned types as asserted above.
289+
// - It's up to the caller to ensure the pointer cast from `T` to `U` itself is valid.
290+
#[allow(trivial_casts, unsafe_code)]
291+
unsafe {
292+
&mut *((slice as *mut [T]) as *mut [U])
293+
}
292294
}
293295

294296
/// Compare the two remainder slices by loading a `Word` then performing `cmovne`.

0 commit comments

Comments
 (0)