mirror of
https://github.com/rust-lang/rust.git
synced 2025-02-04 11:04:03 +00:00
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: https://github.com/rust-lang/rust/issues/93743#issuecomment-1579935853 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.
This commit is contained in:
commit
4f4dae055b
@ -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);
|
||||
}
|
||||
|
@ -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
|
||||
///
|
||||
@ -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]
|
||||
|
Loading…
Reference in New Issue
Block a user