Skip to content

Commit

Permalink
Add methods to move ByteStrings underlying bytes
Browse files Browse the repository at this point in the history
Add methods to move the underlying Vec<u8> for ByteString.
  • Loading branch information
dlrobertson committed Feb 18, 2016
1 parent 184c7db commit d23774d
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
13 changes: 13 additions & 0 deletions components/script/dom/bindings/str.rs
Expand Up @@ -7,6 +7,7 @@
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops;
use std::str;
use std::str::FromStr;
Expand All @@ -28,6 +29,12 @@ impl ByteString {
str::from_utf8(&vec).ok()
}

/// Returns ownership of the underlying Vec<u8> and copies an empty
/// vec in its place
pub fn bytes(&mut self) -> Vec<u8> {
mem::replace(&mut self.0, Vec::new())
}

/// Returns the length.
pub fn len(&self) -> usize {
let ByteString(ref vector) = *self;
Expand Down Expand Up @@ -117,6 +124,12 @@ impl ByteString {
}
}

impl Into<Vec<u8>> for ByteString {
fn into(self) -> Vec<u8> {
self.0
}
}

impl Hash for ByteString {
fn hash<H: Hasher>(&self, state: &mut H) {
let ByteString(ref vec) = *self;
Expand Down
2 changes: 1 addition & 1 deletion components/script/dom/xmlhttprequest.rs
Expand Up @@ -435,7 +435,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
None => {}
}

headers.set_raw(name_str.to_owned(), vec![value.to_vec()]);
headers.set_raw(name_str.to_owned(), vec![value.into()]);
Ok(())
}

Expand Down
17 changes: 17 additions & 0 deletions tests/unit/script/dom/bindings.rs
@@ -0,0 +1,17 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use script::dom::bindings::str::ByteString;

#[test]
fn test_byte_string_move() {
let mut byte_str = ByteString::new(vec![0x73, 0x65, 0x72, 0x76, 0x6f]);
let mut byte_vec = byte_str.bytes();

assert_eq!(byte_vec, "servo".as_bytes());
assert_eq!(*byte_str, []);

byte_vec = byte_str.into();
assert_eq!(byte_vec, Vec::new());
}
1 change: 1 addition & 0 deletions tests/unit/script/lib.rs
Expand Up @@ -9,5 +9,6 @@ extern crate util;
#[cfg(all(test, target_pointer_width = "64"))] mod size_of;
#[cfg(test)] mod textinput;
#[cfg(test)] mod dom {
mod bindings;
mod blob;
}

0 comments on commit d23774d

Please sign in to comment.