Skip to content

Commit 3d2ebbd

Browse files
committed
Auto merge of #112387 - clarfonthey:non-panicking-ceil-char-boundary, r=m-ou-se
Don't panic in ceil_char_boundary Implementing the alternative mentioned in this comment: rust-lang/rust#93743 (comment) Since `floor_char_boundary` will always work (rounding down to the length of the string is possible), it feels best for `ceil_char_boundary` to not panic either. However, the semantics of "rounding up" past the length of the string aren't very great, which is why the method originally panicked in these cases. Taking into account how people are using this method, it feels best to simply return the end of the string in these cases, so that the result is still a valid char boundary.
2 parents 9a23403 + fc1273f commit 3d2ebbd

File tree

2 files changed

+5
-9
lines changed

2 files changed

+5
-9
lines changed

alloc/tests/str.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -2438,10 +2438,7 @@ fn ceil_char_boundary() {
24382438
check_many("🇯🇵", 0..=0, 0);
24392439
check_many("🇯🇵", 1..=4, 4);
24402440
check_many("🇯🇵", 5..=8, 8);
2441-
}
24422441

2443-
#[test]
2444-
#[should_panic]
2445-
fn ceil_char_boundary_above_len_panic() {
2446-
let _ = "x".ceil_char_boundary(2);
2442+
// above len
2443+
check_many("hello", 5..=10, 5);
24472444
}

core/src/str/mod.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -267,14 +267,13 @@ impl str {
267267

268268
/// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
269269
///
270+
/// If `index` is greater than the length of the string, this returns the length of the string.
271+
///
270272
/// This method is the natural complement to [`floor_char_boundary`]. See that method
271273
/// for more details.
272274
///
273275
/// [`floor_char_boundary`]: str::floor_char_boundary
274276
///
275-
/// # Panics
276-
///
277-
/// Panics if `index > self.len()`.
278277
///
279278
/// # Examples
280279
///
@@ -292,7 +291,7 @@ impl str {
292291
#[inline]
293292
pub fn ceil_char_boundary(&self, index: usize) -> usize {
294293
if index > self.len() {
295-
slice_error_fail(self, index, index)
294+
self.len()
296295
} else {
297296
let upper_bound = Ord::min(index + 4, self.len());
298297
self.as_bytes()[index..upper_bound]

0 commit comments

Comments
 (0)