about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2013-08-24 05:51:21 -0700
committerbors <bors@rust-lang.org>2013-08-24 05:51:21 -0700
commitc643f1d39c4c878fdb9fa25fb01c513d53afaa11 (patch)
tree1ba8ea546921e58919e92f4ae3351d0746f3d76b
parentdb5615ddd5c315af115bbcca6a9a0d7ac79f6088 (diff)
parent6b4ceff610c4a9063d44e1e422470075c234111d (diff)
downloadrust-c643f1d39c4c878fdb9fa25fb01c513d53afaa11.tar.gz
rust-c643f1d39c4c878fdb9fa25fb01c513d53afaa11.zip
auto merge of #8732 : kballard/rust/str-truncate, r=thestinger
-rw-r--r--src/libstd/str.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/libstd/str.rs b/src/libstd/str.rs
index 610ca93494c..c57df213786 100644
--- a/src/libstd/str.rs
+++ b/src/libstd/str.rs
@@ -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.
     ///
@@ -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) };
@@ -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)]