]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #32977 - alexcrichton:ignore-panics, r=brson
authorbors <bors@rust-lang.org>
Sun, 17 Apr 2016 06:06:29 +0000 (23:06 -0700)
committerbors <bors@rust-lang.org>
Sun, 17 Apr 2016 06:06:29 +0000 (23:06 -0700)
std: Change String::truncate to panic less

The `Vec::truncate` method does not panic if the length argument is greater than
the vector's current length, but `String::truncate` will indeed panic. This
semantic difference can be a bit jarring (e.g. #32717), and after some
discussion the libs team concluded that although this can technically be a
breaking change it is almost undoubtedly not so in practice.

This commit changes the semantics of `String::truncate` to be a noop if
`new_len` is greater than the length of the current string.

Closes #32717

src/libcollections/string.rs
src/libcollectionstest/string.rs

index 2226116585fcb072550d4fa6ce90faf43d8a5180..306fad2328b628854c3efe740a57a5f090ce18b3 100644 (file)
@@ -992,10 +992,12 @@ pub fn as_bytes(&self) -> &[u8] {
 
     /// Shortens this `String` to the specified length.
     ///
+    /// If `new_len` is greater than the string's current length, this has no
+    /// effect.
+    ///
     /// # Panics
     ///
-    /// Panics if `new_len` > current length, or if `new_len` does not lie on a
-    /// [`char`] boundary.
+    /// Panics if `new_len` does not lie on a [`char`] boundary.
     ///
     /// [`char`]: ../../std/primitive.char.html
     ///
@@ -1013,8 +1015,10 @@ pub fn as_bytes(&self) -> &[u8] {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn truncate(&mut self, new_len: usize) {
-        assert!(self.is_char_boundary(new_len));
-        self.vec.truncate(new_len)
+        if new_len <= self.len() {
+            assert!(self.is_char_boundary(new_len));
+            self.vec.truncate(new_len)
+        }
     }
 
     /// Removes the last character from the string buffer and returns it.
index d8e01f3800caf6bebacc148266547cfbca138ca7..d71529023f4f7636862cc037cef2e03e8c2310b2 100644 (file)
@@ -248,10 +248,10 @@ fn test_str_truncate() {
 }
 
 #[test]
-#[should_panic]
 fn test_str_truncate_invalid_len() {
     let mut s = String::from("12345");
     s.truncate(6);
+    assert_eq!(s, "12345");
 }
 
 #[test]