about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorSteven Fackler <sfackler@gmail.com>2013-08-24 02:37:22 -0400
committerSteven Fackler <sfackler@gmail.com>2013-08-24 17:37:56 -0400
commite173a96be0b084070c876111effc0b128a705eb2 (patch)
tree2139df9ec04a9417c8e7e9a0c00c1e47e3abe1c2 /src/libstd
parentc643f1d39c4c878fdb9fa25fb01c513d53afaa11 (diff)
downloadrust-e173a96be0b084070c876111effc0b128a705eb2.tar.gz
rust-e173a96be0b084070c876111effc0b128a705eb2.zip
Add OwnedStr::into_bytes
My primary use case here is sending strings across the wire where the
intermediate storage is a byte array. The new method ends up avoiding a
copy.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/str.rs17
1 files changed, 16 insertions, 1 deletions
diff --git a/src/libstd/str.rs b/src/libstd/str.rs
index c57df213786..bee354a0a5d 100644
--- a/src/libstd/str.rs
+++ b/src/libstd/str.rs
@@ -2108,6 +2108,7 @@ pub trait OwnedStr {
     fn reserve_at_least(&mut self, n: uint);
     fn capacity(&self) -> uint;
     fn truncate(&mut self, len: uint);
+    fn into_bytes(self) -> ~[u8];
 
     /// Work with the mutable byte buffer and length of a slice.
     ///
@@ -2273,6 +2274,13 @@ impl OwnedStr for ~str {
         unsafe { raw::set_len(self, len); }
     }
 
+    /// Consumes the string, returning the underlying byte buffer.
+    ///
+    /// The buffer does not have a null terminator.
+    #[inline]
+    fn into_bytes(self) -> ~[u8] {
+        unsafe { cast::transmute(self) }
+    }
 
     #[inline]
     fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
@@ -2356,7 +2364,7 @@ mod tests {
     use ptr;
     use str::*;
     use vec;
-    use vec::{ImmutableVector, CopyableVector};
+    use vec::{Vector, ImmutableVector, CopyableVector};
     use cmp::{TotalOrd, Less, Equal, Greater};
 
     #[test]
@@ -2525,6 +2533,13 @@ mod tests {
     }
 
     #[test]
+    fn test_into_bytes() {
+        let data = ~"asdf";
+        let buf = data.into_bytes();
+        assert_eq!(bytes!("asdf"), buf.as_slice());
+    }
+
+    #[test]
     fn test_find_str() {
         // byte positions
         assert_eq!("".find_str(""), Some(0u));