mirror of
https://github.com/rust-lang/rust.git
synced 2025-01-25 06:03:16 +00:00
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.
This commit is contained in:
parent
c643f1d39c
commit
e173a96be0
@ -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]
|
||||
@ -2524,6 +2532,13 @@ mod tests {
|
||||
assert_eq!("华", data.as_slice());
|
||||
}
|
||||
|
||||
#[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
|
||||
|
Loading…
Reference in New Issue
Block a user