Skip to content

Commit

Permalink
Auto merge of rust-lang#112387 - clarfonthey:non-panicking-ceil-char-…
Browse files Browse the repository at this point in the history
…boundary, r=m-ou-se

Don't panic in ceil_char_boundary

Implementing the alternative mentioned in this comment: rust-lang#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.
  • Loading branch information
bors committed Aug 15, 2023
2 parents c1699a7 + 2f75dd4 commit 4f4dae0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 9 deletions.
7 changes: 2 additions & 5 deletions library/alloc/tests/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2438,10 +2438,7 @@ fn ceil_char_boundary() {
check_many("🇯🇵", 0..=0, 0);
check_many("🇯🇵", 1..=4, 4);
check_many("🇯🇵", 5..=8, 8);
}

#[test]
#[should_panic]
fn ceil_char_boundary_above_len_panic() {
let _ = "x".ceil_char_boundary(2);
// above len
check_many("hello", 5..=10, 5);
}
7 changes: 3 additions & 4 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,14 +267,13 @@ impl str {

/// Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.
///
/// If `index` is greater than the length of the string, this returns the length of the string.
///
/// This method is the natural complement to [`floor_char_boundary`]. See that method
/// for more details.
///
/// [`floor_char_boundary`]: str::floor_char_boundary
///
/// # Panics
///
/// Panics if `index > self.len()`.
///
/// # Examples
///
Expand All @@ -292,7 +291,7 @@ impl str {
#[inline]
pub fn ceil_char_boundary(&self, index: usize) -> usize {
if index > self.len() {
slice_error_fail(self, index, index)
self.len()
} else {
let upper_bound = Ord::min(index + 4, self.len());
self.as_bytes()[index..upper_bound]
Expand Down

0 comments on commit 4f4dae0

Please sign in to comment.