@@ -2107,6 +2107,7 @@ pub trait OwnedStr {
2107
2107
fn reserve(&mut self, n: uint);
2108
2108
fn reserve_at_least(&mut self, n: uint);
2109
2109
fn capacity(&self) -> uint;
2110
+ fn truncate(&mut self, len: uint);
2110
2111
2111
2112
/// Work with the mutable byte buffer and length of a slice.
2112
2113
///
@@ -2264,6 +2265,15 @@ impl OwnedStr for ~str {
2264
2265
}
2265
2266
}
2266
2267
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
+
2267
2277
#[inline]
2268
2278
fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
2269
2279
let v: &mut ~[u8] = unsafe { cast::transmute(self) };
@@ -3482,6 +3492,38 @@ mod tests {
3482
3492
assert_eq!(5, sum_len([~" 01 ", ~" 2 ", ~" 34 ", ~" "]));
3483
3493
assert_eq!(5, sum_len([s.as_slice()]));
3484
3494
}
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
+ }
3485
3527
}
3486
3528
3487
3529
#[ cfg( test) ]
0 commit comments