Skip to content

Commit afbcb48

Browse files
committed
use align_to to reduce unsafety
1 parent 52c26f6 commit afbcb48

1 file changed

Lines changed: 4 additions & 30 deletions

File tree

zlib-rs/src/adler32/generic.rs

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -116,34 +116,8 @@ pub(crate) fn adler32_len_64(mut adler: u32, buf: &[u8], mut sum2: u32) -> u32 {
116116

117117
// FIXME use the method on slices once available.
118118
fn slice_as_chunks<T, const N: usize>(slice: &[T]) -> (&[[T; N]], &[T]) {
119-
assert!(N != 0, "chunk size must be non-zero");
120-
let len_rounded_down = slice.len() / N * N;
121-
// SAFETY: The rounded-down value is always the same or smaller than the
122-
// original length, and thus must be in-bounds of the slice.
123-
let (multiple_of_n, remainder) = unsafe { slice_split_at_unchecked(slice, len_rounded_down) };
124-
// SAFETY: We already panicked for zero, and ensured by construction
125-
// that the length of the subslice is a multiple of N.
126-
let array_slice = unsafe { slice_as_chunks_unchecked(multiple_of_n) };
127-
(array_slice, remainder)
128-
}
129-
130-
unsafe fn slice_as_chunks_unchecked<T, const N: usize>(slice: &[T]) -> &[[T; N]] {
131-
// SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
132-
let new_len = slice.len() / N;
133-
// SAFETY: We cast a slice of `new_len * N` elements into
134-
// a slice of `new_len` many `N` elements chunks.
135-
unsafe { core::slice::from_raw_parts(slice.as_ptr().cast(), new_len) }
136-
}
137-
138-
pub unsafe fn slice_split_at_unchecked<T>(slice: &[T], mid: usize) -> (&[T], &[T]) {
139-
let len = slice.len();
140-
let ptr = slice.as_ptr();
141-
142-
// SAFETY: Caller has to check that `0 <= mid <= self.len()`
143-
unsafe {
144-
(
145-
core::slice::from_raw_parts(ptr, mid),
146-
core::slice::from_raw_parts(ptr.add(mid), len - mid),
147-
)
148-
}
119+
// SAFETY: T can be trivially transmuted to T.
120+
let (before, middle, after) = unsafe { slice.align_to() };
121+
debug_assert!(before.is_empty());
122+
(middle, after)
149123
}

0 commit comments

Comments
 (0)