diff options
| author | Alex Crichton <alex@alexcrichton.com> | 2016-04-14 16:56:59 -0700 |
|---|---|---|
| committer | Alex Crichton <alex@alexcrichton.com> | 2016-04-15 10:13:43 -0700 |
| commit | ae79ce3f030db27aa7d35d1b22307fb4eba14f36 (patch) | |
| tree | e35bca3694409c208d2b1e7709583851fbabceef /src/libcollections/string.rs | |
| parent | 073a09fd63c9b4ec3bb4709986a2517ca4c3cdf1 (diff) | |
| download | rust-ae79ce3f030db27aa7d35d1b22307fb4eba14f36.tar.gz rust-ae79ce3f030db27aa7d35d1b22307fb4eba14f36.zip | |
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
Diffstat (limited to 'src/libcollections/string.rs')
| -rw-r--r-- | src/libcollections/string.rs | 12 |
1 files changed, 8 insertions, 4 deletions
diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 2226116585f..306fad2328b 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -992,10 +992,12 @@ impl String { /// 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 @@ impl String { #[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. |
