Skip to content

Add new function str.truncate() #8732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
42 changes: 42 additions & 0 deletions src/libstd/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2107,6 +2107,7 @@ pub trait OwnedStr {
fn reserve(&mut self, n: uint);
fn reserve_at_least(&mut self, n: uint);
fn capacity(&self) -> uint;
fn truncate(&mut self, len: uint);

/// Work with the mutable byte buffer and length of a slice.
///
Expand Down Expand Up @@ -2264,6 +2265,15 @@ impl OwnedStr for ~str {
}
}

/// Shorten a string to the specified length (which must be <= the current length)
#[inline]
fn truncate(&mut self, len: uint) {
assert!(len <= self.len());
assert!(self.is_char_boundary(len));
unsafe { raw::set_len(self, len); }
}


#[inline]
fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
let v: &mut ~[u8] = unsafe { cast::transmute(self) };
Expand Down Expand Up @@ -3482,6 +3492,38 @@ mod tests {
assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
assert_eq!(5, sum_len([s.as_slice()]));
}

#[test]
fn test_str_truncate() {
let mut s = ~"12345";
s.truncate(5);
assert_eq!(s.as_slice(), "12345");
s.truncate(3);
assert_eq!(s.as_slice(), "123");
s.truncate(0);
assert_eq!(s.as_slice(), "");

let mut s = ~"12345";
let p = s.as_imm_buf(|p,_| p);
s.truncate(3);
s.push_str("6");
let p_ = s.as_imm_buf(|p,_| p);
assert_eq!(p_, p);
}

#[test]
#[should_fail]
fn test_str_truncate_invalid_len() {
let mut s = ~"12345";
s.truncate(6);
}

#[test]
#[should_fail]
fn test_str_truncate_split_codepoint() {
let mut s = ~"\u00FC"; // ü
s.truncate(1);
}
}

#[cfg(test)]
Expand Down