Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions library/alloc/src/wtf8/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,14 +342,18 @@ impl Wtf8Buf {

/// Shortens a 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` is not a code point boundary.
/// Panics if `new_len` does not lie on a code point boundary.
#[inline]
pub fn truncate(&mut self, new_len: usize) {
assert!(self.is_code_point_boundary(new_len));
self.bytes.truncate(new_len)
if new_len <= self.len() {
assert!(self.is_code_point_boundary(new_len));
self.bytes.truncate(new_len)
}
}

/// Consumes the WTF-8 string and tries to convert it to a vec of bytes.
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/wtf8/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,10 +308,10 @@ fn wtf8buf_truncate_fail_code_point_boundary() {
}

#[test]
#[should_panic]
fn wtf8buf_truncate_fail_longer() {
fn wtf8buf_truncate_invalid_len() {
let mut string = Wtf8Buf::from_str("aé");
string.truncate(4);
assert_eq!(string, Wtf8Buf::from_str("aé"));
}

#[test]
Expand Down
12 changes: 9 additions & 3 deletions library/std/src/ffi/os_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,15 +576,21 @@ impl OsString {

/// Truncate the `OsString` to the specified length.
///
/// If `new_len` is greater than the string's current length, this has no
/// effect.
///
/// # Panics
///
/// Panics if `len` does not lie on a valid `OsStr` boundary
/// (as described in [`OsStr::slice_encoded_bytes`]).
#[inline]
#[unstable(feature = "os_string_truncate", issue = "133262")]
pub fn truncate(&mut self, len: usize) {
self.as_os_str().inner.check_public_boundary(len);
// SAFETY: The length was just checked to be at a valid boundary.
unsafe { self.inner.truncate_unchecked(len) };
if len <= self.len() {
self.as_os_str().inner.check_public_boundary(len);
// SAFETY: The length was just checked to be at a valid boundary.
unsafe { self.inner.truncate_unchecked(len) };
}
}

/// Provides plumbing to `Vec::extend_from_slice` without giving full
Expand Down
Loading