Skip to content

Commit c643f1d

Browse files
committed
auto merge of #8732 : kballard/rust/str-truncate, r=thestinger
2 parents db5615d + 6b4ceff commit c643f1d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libstd/str.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2107,6 +2107,7 @@ pub trait OwnedStr {
21072107
fn reserve(&mut self, n: uint);
21082108
fn reserve_at_least(&mut self, n: uint);
21092109
fn capacity(&self) -> uint;
2110+
fn truncate(&mut self, len: uint);
21102111
21112112
/// Work with the mutable byte buffer and length of a slice.
21122113
///
@@ -2264,6 +2265,15 @@ impl OwnedStr for ~str {
22642265
}
22652266
}
22662267
2268+
/// Shorten a string to the specified length (which must be <= the current length)
2269+
#[inline]
2270+
fn truncate(&mut self, len: uint) {
2271+
assert!(len <= self.len());
2272+
assert!(self.is_char_boundary(len));
2273+
unsafe { raw::set_len(self, len); }
2274+
}
2275+
2276+
22672277
#[inline]
22682278
fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
22692279
let v: &mut ~[u8] = unsafe { cast::transmute(self) };
@@ -3482,6 +3492,38 @@ mod tests {
34823492
assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
34833493
assert_eq!(5, sum_len([s.as_slice()]));
34843494
}
3495+
3496+
#[test]
3497+
fn test_str_truncate() {
3498+
let mut s = ~"12345";
3499+
s.truncate(5);
3500+
assert_eq!(s.as_slice(), "12345");
3501+
s.truncate(3);
3502+
assert_eq!(s.as_slice(), "123");
3503+
s.truncate(0);
3504+
assert_eq!(s.as_slice(), "");
3505+
3506+
let mut s = ~"12345";
3507+
let p = s.as_imm_buf(|p,_| p);
3508+
s.truncate(3);
3509+
s.push_str("6");
3510+
let p_ = s.as_imm_buf(|p,_| p);
3511+
assert_eq!(p_, p);
3512+
}
3513+
3514+
#[test]
3515+
#[should_fail]
3516+
fn test_str_truncate_invalid_len() {
3517+
let mut s = ~"12345";
3518+
s.truncate(6);
3519+
}
3520+
3521+
#[test]
3522+
#[should_fail]
3523+
fn test_str_truncate_split_codepoint() {
3524+
let mut s = ~"\u00FC"; // ü
3525+
s.truncate(1);
3526+
}
34853527
}
34863528

34873529
#[cfg(test)]

0 commit comments

Comments
 (0)