about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2023-08-15 13:49:24 +0000
committerbors <bors@rust-lang.org>2023-08-15 13:49:24 +0000
commit4f4dae055b470c889968b02964a28477f9daff62 (patch)
treede40140336f8655255eab3ccecedfbf222455693
parentc1699a79a603faa8b522a4b51553b6781913a50e (diff)
parent2f75dd4e193fc0626dab44b6d76bc2b377fd1f3d (diff)
downloadrust-4f4dae055b470c889968b02964a28477f9daff62.tar.gz
rust-4f4dae055b470c889968b02964a28477f9daff62.zip
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.
-rw-r--r--library/alloc/tests/str.rs7
-rw-r--r--library/core/src/str/mod.rs7
2 files changed, 5 insertions, 9 deletions
diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs
index 8a4b4ac4e8d..cb59a9d4ab2 100644
--- a/library/alloc/tests/str.rs
+++ b/library/alloc/tests/str.rs
@@ -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);
 }
diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs
index 71c03f7bfc5..e5f34952c7d 100644
--- a/library/core/src/str/mod.rs
+++ b/library/core/src/str/mod.rs
@@ -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]