Skip to content

Commit 495692b

Browse files
committed
Add str::Utf8Chunk::invalid range hint
1 parent cb40c25 commit 495692b

1 file changed

Lines changed: 7 additions & 0 deletions

File tree

library/core/src/str/lossy.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ impl<'a> Utf8Chunk<'a> {
102102
#[must_use]
103103
#[stable(feature = "utf8_chunks", since = "1.79.0")]
104104
pub fn invalid(&self) -> &'a [u8] {
105+
// SAFETY: The invariant that `self.invalid.len() <= 3` is upheld by
106+
// the implementation of `Utf8Chunks::next()`, which is the only way to
107+
// construct a `Utf8Chunk`.
108+
unsafe { crate::hint::assert_unchecked(self.invalid.len() <= 3) };
105109
self.invalid
106110
}
107111
}
@@ -286,6 +290,9 @@ impl<'a> Iterator for Utf8Chunks<'a> {
286290
// `valid_up_to = i` and `i` only increases.
287291
let (valid, invalid) = unsafe { inspected.split_at_unchecked(valid_up_to) };
288292

293+
// In UTF-8, the longest possible invalid sequence is 3 bytes long.
294+
debug_assert!(invalid.len() <= 3);
295+
289296
Some(Utf8Chunk {
290297
// SAFETY: All bytes up to `valid_up_to` are valid UTF-8.
291298
valid: unsafe { from_utf8_unchecked(valid) },

0 commit comments

Comments
 (0)