diff options
| author | okaneco <47607823+okaneco@users.noreply.github.com> | 2025-03-29 14:47:09 -0400 |
|---|---|---|
| committer | okaneco <47607823+okaneco@users.noreply.github.com> | 2025-03-30 12:45:04 -0400 |
| commit | 59ca7679c7db634465b5f021060f143567824ac4 (patch) | |
| tree | 95313defc87e5dccc7fc04f74a90829b57b369a2 /tests/codegen | |
| parent | 45b40a75966b36d3588f173441896fddad01cd80 (diff) | |
| download | rust-59ca7679c7db634465b5f021060f143567824ac4.tar.gz rust-59ca7679c7db634465b5f021060f143567824ac4.zip | |
slice: Remove some uses of unsafe in first/last chunk methods
Remove unsafe `split_at_unchecked` and `split_at_mut_unchecked` in some slice `split_first_chunk`/`split_last_chunk` methods. Replace those calls with the safe `split_at` and `split_at_checked` where applicable. Add codegen tests to check for no panics when calculating the last chunk index using `checked_sub` and `split_at`
Diffstat (limited to 'tests/codegen')
| -rw-r--r-- | tests/codegen/slice-split-at.rs | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/tests/codegen/slice-split-at.rs b/tests/codegen/slice-split-at.rs new file mode 100644 index 00000000000..07018cf9c91 --- /dev/null +++ b/tests/codegen/slice-split-at.rs @@ -0,0 +1,24 @@ +//@ compile-flags: -Copt-level=3 +#![crate_type = "lib"] + +// Check that no panic is generated in `split_at` when calculating the index for +// the tail chunk using `checked_sub`. +// +// Tests written for refactored implementations of: +// `<[T]>::{split_last_chunk, split_last_chunk_mut, last_chunk, last_chunk_mut}` + +// CHECK-LABEL: @split_at_last_chunk +#[no_mangle] +pub fn split_at_last_chunk(s: &[u8], chunk_size: usize) -> Option<(&[u8], &[u8])> { + // CHECK-NOT: panic + let Some(index) = s.len().checked_sub(chunk_size) else { return None }; + Some(s.split_at(index)) +} + +// CHECK-LABEL: @split_at_mut_last_chunk +#[no_mangle] +pub fn split_at_mut_last_chunk(s: &mut [u8], chunk_size: usize) -> Option<(&mut [u8], &mut [u8])> { + // CHECK-NOT: panic + let Some(index) = s.len().checked_sub(chunk_size) else { return None }; + Some(s.split_at_mut(index)) +} |
