]> git.lizzy.rs Git - rust.git/commitdiff
Add an &str.to_managed method to allow creating non-constant @str values (for issue...
authorGareth Daniel Smith <garethdanielsmith@gmail.com>
Thu, 4 Oct 2012 19:22:53 +0000 (20:22 +0100)
committerNiko Matsakis <niko@alum.mit.edu>
Sat, 13 Oct 2012 12:57:13 +0000 (05:57 -0700)
src/libcore/str.rs

index 677a33d56c0d32459057fb279fbb5e6b1a926dc0..e2e7b15b1d7839920b458048838e863cfa8cf02a 100644 (file)
@@ -1869,6 +1869,11 @@ pub fn reserve_at_least(s: &mut ~str, n: uint) {
     move out
 }
 
+extern mod rustrt {
+    #[rust_stack]
+    pure fn upcall_str_new_shared(cstr: *libc::c_char, len: size_t) -> @str;
+}
+
 /// Unsafe operations
 pub mod raw {
 
@@ -2090,6 +2095,7 @@ pub trait StrSlice {
     pure fn trim_left() -> ~str;
     pure fn trim_right() -> ~str;
     pure fn to_unique() -> ~str;
+    pure fn to_managed() -> @str;
     pure fn char_at(i: uint) -> char;
 }
 
@@ -2213,6 +2219,14 @@ impl &str: StrSlice {
     #[inline]
     pure fn to_unique() -> ~str { self.slice(0, self.len()) }
 
+    #[inline]
+    pure fn to_managed() -> @str {
+        do str::as_buf(self) |p, _len| {
+            rustrt::upcall_str_new_shared(p as *libc::c_char,
+                                          self.len() as size_t)
+        }
+    }
+
     #[inline]
     pure fn char_at(i: uint) -> char { char_at(self, i) }
 }
@@ -3190,4 +3204,10 @@ fn test_escape_default() {
         assert escape_default(~"\U0001d4ea\r") == ~"\\U0001d4ea\\r";
     }
 
+    #[test]
+    fn test_to_managed() {
+        assert (~"abc").to_managed() == @"abc";
+        assert view("abcdef", 1, 5).to_managed() == @"bcde";
+    }
+
 }