Skip to content

Commit a506461

Browse files
committed
Document unsafety in core::slice::memchr
Contributes to rust-lang#66219
1 parent efbaa41 commit a506461

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

library/core/src/slice/memchr.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
// Original implementation taken from rust-memchr.
22
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
33

4-
// ignore-tidy-undocumented-unsafe
5-
64
use crate::cmp;
75
use crate::mem;
86

@@ -72,6 +70,8 @@ fn memchr_general_case(x: u8, text: &[u8]) -> Option<usize> {
7270
// search the body of the text
7371
let repeated_x = repeat_byte(x);
7472
while offset <= len - 2 * USIZE_BYTES {
73+
// SAFETY: the while's predicate guarantees a distance of at least 2 * usize_bytes
74+
// between the offset and the end of the slice.
7575
unsafe {
7676
let u = *(ptr.add(offset) as *const usize);
7777
let v = *(ptr.add(offset + USIZE_BYTES) as *const usize);
@@ -105,6 +105,8 @@ pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
105105
let (min_aligned_offset, max_aligned_offset) = {
106106
// We call this just to obtain the length of the prefix and suffix.
107107
// In the middle we always process two chunks at once.
108+
// SAFETY: transmuting `[u8]` to `[usize]` is safe except for size differences
109+
// which are handled by `align_to`.
108110
let (prefix, _, suffix) = unsafe { text.align_to::<(Chunk, Chunk)>() };
109111
(prefix.len(), len - suffix.len())
110112
};
@@ -121,6 +123,8 @@ pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
121123
let chunk_bytes = mem::size_of::<Chunk>();
122124

123125
while offset > min_aligned_offset {
126+
// SAFETY: offset starts at len - suffix.len(), as long as it is greater than
127+
// min_aligned_offset (prefix.len()) the remaining distance is at least 2 * chunk_bytes.
124128
unsafe {
125129
let u = *(ptr.offset(offset as isize - 2 * chunk_bytes as isize) as *const Chunk);
126130
let v = *(ptr.offset(offset as isize - chunk_bytes as isize) as *const Chunk);

0 commit comments

Comments
 (0)