Skip to content

Commit

Permalink
Auto merge of #32977 - alexcrichton:ignore-panics, r=brson
Browse files Browse the repository at this point in the history
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
  • Loading branch information
bors committed Apr 17, 2016
2 parents 6892277 + ae79ce3 commit b5de94f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
12 changes: 8 additions & 4 deletions src/libcollections/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/libcollectionstest/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit b5de94f

Please sign in to comment.