std: unify the str -> [u8] functions as 3 methods: .as_bytes() and .as_bytes_with_null[_consume]().

The first acts on &str and is not nul-terminated, the last two act on strings
that are always null terminated (&'static str, ~str and @str).
This commit is contained in:
Huon Wilson 2013-06-11 13:10:37 +10:00
parent ba4a4778cc
commit efc71a8bdb
44 changed files with 255 additions and 218 deletions

View File

@ -12,7 +12,6 @@
use core::prelude::*;
use core::str;
use core::vec;
/// A trait for converting a value to base64 encoding.
@ -111,7 +110,7 @@ impl<'self> ToBase64 for &'self str {
*
*/
fn to_base64(&self) -> ~str {
str::to_bytes(*self).to_base64()
self.as_bytes().to_base64()
}
}
@ -224,7 +223,7 @@ impl<'self> FromBase64 for &'self str {
* ~~~
*/
fn from_base64(&self) -> ~[u8] {
str::to_bytes(*self).from_base64()
self.as_bytes().from_base64()
}
}
@ -245,12 +244,12 @@ mod tests {
#[test]
fn test_from_base64() {
assert_eq!("".from_base64(), str::to_bytes(""));
assert_eq!("Zg==".from_base64(), str::to_bytes("f"));
assert_eq!("Zm8=".from_base64(), str::to_bytes("fo"));
assert_eq!("Zm9v".from_base64(), str::to_bytes("foo"));
assert_eq!("Zm9vYg==".from_base64(), str::to_bytes("foob"));
assert_eq!("Zm9vYmE=".from_base64(), str::to_bytes("fooba"))
assert_eq!("Zm9vYmFy".from_base64(), str::to_bytes("foobar"));
assert_eq!("".from_base64(), "".as_bytes().to_owned());
assert_eq!("Zg==".from_base64(), "f".as_bytes().to_owned());
assert_eq!("Zm8=".from_base64(), "fo".as_bytes().to_owned());
assert_eq!("Zm9v".from_base64(), "foo".as_bytes().to_owned());
assert_eq!("Zm9vYg==".from_base64(), "foob".as_bytes().to_owned());
assert_eq!("Zm9vYmE=".from_base64(), "fooba".as_bytes().to_owned());
assert_eq!("Zm9vYmFy".from_base64(), "foobar".as_bytes().to_owned());
}
}

View File

@ -607,7 +607,6 @@ pub mod writer {
use core::cast;
use core::io;
use core::str;
// ebml writing
pub struct Encoder {
@ -725,7 +724,7 @@ pub mod writer {
}
pub fn wr_tagged_str(&mut self, tag_id: uint, v: &str) {
str::byte_slice(v, |b| self.wr_tagged_bytes(tag_id, b));
self.wr_tagged_bytes(tag_id, v.as_bytes());
}
pub fn wr_bytes(&mut self, b: &[u8]) {
@ -735,7 +734,7 @@ pub mod writer {
pub fn wr_str(&mut self, s: &str) {
debug!("Write str: %?", s);
self.writer.write(str::to_bytes(s));
self.writer.write(s.as_bytes());
}
}

View File

@ -487,7 +487,7 @@ mod test {
let mut buf : ~[u8] = vec::from_elem(6, 0u8);
let count = fi.read(buf, 10);
assert_eq!(count, 6);
assert_eq!(buf, "0\n1\n2\n".to_bytes());
assert_eq!(buf, "0\n1\n2\n".as_bytes().to_owned());
assert!(fi.eof())
assert_eq!(fi.state().line_num, 3);
}

View File

@ -10,7 +10,6 @@
use core::prelude::*;
use core::str;
use core::uint;
use core::vec;
@ -129,7 +128,7 @@ pub fn md4_str(msg: &[u8]) -> ~str {
/// Calculates the md4 hash of a string, returning the hex-encoded version of
/// the hash
pub fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) }
pub fn md4_text(msg: &str) -> ~str { md4_str(msg.as_bytes()) }
#[test]
fn test_md4() {

View File

@ -1636,7 +1636,7 @@ mod test {
assert_eq!(net::ip::get_port(&sock.get_peer_addr()), 8887);
// Fulfill the protocol the test server expects
let resp_bytes = str::to_bytes("ping");
let resp_bytes = "ping".as_bytes().to_owned();
tcp_write_single(&sock, resp_bytes);
debug!("message sent");
sock.read(0u);
@ -1756,9 +1756,7 @@ mod test {
buf_write(sock_buf, expected_req);
// so contrived!
let actual_resp = do str::as_bytes(&expected_resp.to_str()) |resp_buf| {
buf_read(sock_buf, resp_buf.len())
};
let actual_resp = buf_read(sock_buf, expected_resp.as_bytes().len());
let actual_req = server_result_po.recv();
debug!("REQ: expected: '%s' actual: '%s'",
@ -1810,11 +1808,10 @@ mod test {
fn buf_write<W:io::Writer>(w: &W, val: &str) {
debug!("BUF_WRITE: val len %?", val.len());
do str::byte_slice(val) |b_slice| {
debug!("BUF_WRITE: b_slice len %?",
b_slice.len());
w.write(b_slice)
}
let b_slice = val.as_bytes();
debug!("BUF_WRITE: b_slice len %?",
b_slice.len());
w.write(b_slice)
}
fn buf_read<R:io::Reader>(r: &R, len: uint) -> ~str {
@ -1877,7 +1874,8 @@ mod test {
server_ch.send(
str::from_bytes(data));
debug!("SERVER: before write");
tcp_write_single(&sock, str::to_bytes(resp_cell2.take()));
let s = resp_cell2.take();
tcp_write_single(&sock, s.as_bytes().to_owned());
debug!("SERVER: after write.. die");
kill_ch.send(None);
}
@ -1949,7 +1947,7 @@ mod test {
}
else {
let sock = result::unwrap(connect_result);
let resp_bytes = str::to_bytes(resp);
let resp_bytes = resp.as_bytes().to_owned();
tcp_write_single(&sock, resp_bytes);
let read_result = sock.read(0u);
if read_result.is_err() {

View File

@ -1060,7 +1060,7 @@ mod tests {
/*
assert_eq!(decode_form_urlencoded([]).len(), 0);
let s = str::to_bytes("a=1&foo+bar=abc&foo+bar=12+%3D+34");
let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes();
let form = decode_form_urlencoded(s);
assert_eq!(form.len(), 2);
assert_eq!(form.get_ref(&~"a"), &~[~"1"]);

View File

@ -534,7 +534,7 @@ impl FromStrRadix for BigUint {
pub fn from_str_radix(s: &str, radix: uint)
-> Option<BigUint> {
BigUint::parse_bytes(str::to_bytes(s), radix)
BigUint::parse_bytes(s.as_bytes(), radix)
}
}
@ -1090,7 +1090,7 @@ impl FromStrRadix for BigInt {
fn from_str_radix(s: &str, radix: uint)
-> Option<BigInt> {
BigInt::parse_bytes(str::to_bytes(s), radix)
BigInt::parse_bytes(s.as_bytes(), radix)
}
}

View File

@ -25,7 +25,6 @@
use core::prelude::*;
use core::iterator::IteratorUtil;
use core::str;
use core::uint;
use core::vec;
@ -246,8 +245,7 @@ pub fn sha1() -> @Sha1 {
}
fn input(&mut self, msg: &const [u8]) { add_input(self, msg); }
fn input_str(&mut self, msg: &str) {
let bs = str::to_bytes(msg);
add_input(self, bs);
add_input(self, msg.as_bytes());
}
fn result(&mut self) -> ~[u8] { return mk_result(self); }
fn result_str(&mut self) -> ~str {

View File

@ -13,7 +13,6 @@
use core::prelude::*;
use core::iterator::*;
use core::vec;
use core::f64;
use core::cmp;
use core::num;

View File

@ -85,11 +85,14 @@ pub fn expand(cap: &[u8], params: &mut [Param], sta: &mut [Param], dyn: &mut [Pa
_ => return Err(~"a non-char was used with %c")
},
's' => match stack.pop() {
String(s) => output.push_all(s.to_bytes()),
String(s) => output.push_all(s.as_bytes()),
_ => return Err(~"a non-str was used with %s")
},
'd' => match stack.pop() {
Number(x) => output.push_all(x.to_str().to_bytes()),
Number(x) => {
let s = x.to_str();
output.push_all(s.as_bytes())
}
_ => return Err(~"a non-number was used with %d")
},
'p' => state = PushParam,

View File

@ -769,10 +769,10 @@ mod test_treemap {
fn u8_map() {
let mut m = TreeMap::new();
let k1 = str::to_bytes("foo");
let k2 = str::to_bytes("bar");
let v1 = str::to_bytes("baz");
let v2 = str::to_bytes("foobar");
let k1 = "foo".as_bytes();
let k2 = "bar".as_bytes();
let v1 = "baz".as_bytes();
let v2 = "foobar".as_bytes();
m.insert(copy k1, copy v1);
m.insert(copy k2, copy v2);

View File

@ -1368,7 +1368,7 @@ mod test {
// In C, this would be a malloc'd or stack-allocated
// struct that we'd cast to a void* and store as the
// data field in our uv_connect_t struct
let req_str_bytes = str::to_bytes(req_str);
let req_str_bytes = req_str.as_bytes();
let req_msg_ptr: *u8 = vec::raw::to_ptr(req_str_bytes);
debug!("req_msg ptr: %u", req_msg_ptr as uint);
let req_msg = ~[
@ -1626,7 +1626,7 @@ mod test {
let server_write_req = write_t();
let server_write_req_ptr: *uv_write_t = &server_write_req;
let resp_str_bytes = str::to_bytes(server_resp_msg);
let resp_str_bytes = server_resp_msg.as_bytes();
let resp_msg_ptr: *u8 = vec::raw::to_ptr(resp_str_bytes);
debug!("resp_msg ptr: %u", resp_msg_ptr as uint);
let resp_msg = ~[

View File

@ -50,8 +50,7 @@ pub enum output_type {
}
fn write_string<W:Writer>(writer: &mut W, string: &str) {
let buffer = str::as_bytes_slice(string);
writer.write(buffer);
writer.write(string.as_bytes());
}
pub fn llvm_err(sess: Session, msg: ~str) -> ! {

View File

@ -202,7 +202,8 @@ fn encode_type_param_bounds(ebml_w: &mut writer::Encoder,
fn encode_variant_id(ebml_w: &mut writer::Encoder, vid: def_id) {
ebml_w.start_tag(tag_items_data_item_variant);
ebml_w.writer.write(str::to_bytes(def_to_str(vid)));
let s = def_to_str(vid);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
}
@ -271,7 +272,7 @@ fn encode_symbol(ecx: @EncodeContext,
match ecx.item_symbols.find(&id) {
Some(x) => {
debug!("encode_symbol(id=%?, str=%s)", id, *x);
ebml_w.writer.write(str::to_bytes(*x));
ebml_w.writer.write(x.as_bytes());
}
None => {
ecx.diag.handler().bug(
@ -285,7 +286,7 @@ fn encode_discriminant(ecx: @EncodeContext,
ebml_w: &mut writer::Encoder,
id: node_id) {
ebml_w.start_tag(tag_items_data_item_symbol);
ebml_w.writer.write(str::to_bytes(*ecx.discrim_symbols.get_copy(&id)));
ebml_w.writer.write(ecx.discrim_symbols.get_copy(&id).as_bytes());
ebml_w.end_tag();
}
@ -293,13 +294,15 @@ fn encode_disr_val(_: @EncodeContext,
ebml_w: &mut writer::Encoder,
disr_val: int) {
ebml_w.start_tag(tag_disr_val);
ebml_w.writer.write(str::to_bytes(int::to_str(disr_val)));
let s = int::to_str(disr_val);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
}
fn encode_parent_item(ebml_w: &mut writer::Encoder, id: def_id) {
ebml_w.start_tag(tag_items_data_parent_item);
ebml_w.writer.write(str::to_bytes(def_to_str(id)));
let s = def_to_str(id);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
}
@ -954,7 +957,8 @@ fn encode_info_for_item(ecx: @EncodeContext,
for methods.each |m| {
ebml_w.start_tag(tag_item_impl_method);
let method_def_id = local_def(m.id);
ebml_w.writer.write(str::to_bytes(def_to_str(method_def_id)));
let s = def_to_str(method_def_id);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
}
for opt_trait.iter().advance |ast_trait_ref| {
@ -1218,7 +1222,7 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) {
meta_word(name) => {
ebml_w.start_tag(tag_meta_item_word);
ebml_w.start_tag(tag_meta_item_name);
ebml_w.writer.write(str::to_bytes(*name));
ebml_w.writer.write(name.as_bytes());
ebml_w.end_tag();
ebml_w.end_tag();
}
@ -1227,10 +1231,10 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) {
lit_str(value) => {
ebml_w.start_tag(tag_meta_item_name_value);
ebml_w.start_tag(tag_meta_item_name);
ebml_w.writer.write(str::to_bytes(*name));
ebml_w.writer.write(name.as_bytes());
ebml_w.end_tag();
ebml_w.start_tag(tag_meta_item_value);
ebml_w.writer.write(str::to_bytes(*value));
ebml_w.writer.write(value.as_bytes());
ebml_w.end_tag();
ebml_w.end_tag();
}
@ -1240,7 +1244,7 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) {
meta_list(name, ref items) => {
ebml_w.start_tag(tag_meta_item_list);
ebml_w.start_tag(tag_meta_item_name);
ebml_w.writer.write(str::to_bytes(*name));
ebml_w.writer.write(name.as_bytes());
ebml_w.end_tag();
for items.each |inner_item| {
encode_meta_item(ebml_w, *inner_item);
@ -1398,20 +1402,21 @@ fn encode_crate_dep(ecx: @EncodeContext,
dep: decoder::crate_dep) {
ebml_w.start_tag(tag_crate_dep);
ebml_w.start_tag(tag_crate_dep_name);
ebml_w.writer.write(str::to_bytes(*ecx.tcx.sess.str_of(dep.name)));
let s = ecx.tcx.sess.str_of(dep.name);
ebml_w.writer.write(s.as_bytes());
ebml_w.end_tag();
ebml_w.start_tag(tag_crate_dep_vers);
ebml_w.writer.write(str::to_bytes(*dep.vers));
ebml_w.writer.write(dep.vers.as_bytes());
ebml_w.end_tag();
ebml_w.start_tag(tag_crate_dep_hash);
ebml_w.writer.write(str::to_bytes(*dep.hash));
ebml_w.writer.write(dep.hash.as_bytes());
ebml_w.end_tag();
ebml_w.end_tag();
}
fn encode_hash(ebml_w: &mut writer::Encoder, hash: &str) {
ebml_w.start_tag(tag_crate_hash);
ebml_w.writer.write(str::to_bytes(hash));
ebml_w.writer.write(hash.as_bytes());
ebml_w.end_tag();
}

View File

@ -13,7 +13,6 @@ use core::prelude::*;
use core::option;
use core::os;
use core::result;
use core::str;
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should

View File

@ -48,7 +48,6 @@ use core::iterator::IteratorUtil;
use core::container::Map;
use core::libc::c_ulonglong;
use core::option::{Option, Some, None};
use core::vec;
use lib::llvm::{ValueRef, TypeRef, True, IntEQ, IntNE};
use middle::trans::_match;

View File

@ -262,7 +262,7 @@ mod test {
.. default_config(&Path("test"))
};
let mock_process_output: ~fn(&str, &[~str]) -> ProcessOutput = |_, _| {
ProcessOutput { status: 0, output: "pandoc 1.8.2.1".to_bytes(), error: ~[] }
ProcessOutput { status: 0, output: "pandoc 1.8.2.1".as_bytes().to_owned(), error: ~[] }
};
let result = maybe_find_pandoc(&config, None, mock_process_output);
assert!(result == result::Ok(Some(~"pandoc")));

View File

@ -44,8 +44,7 @@ pub fn normalize(p_: RemotePath) -> LocalPath {
}
pub fn write<W: Writer>(writer: &mut W, string: &str) {
let buffer = str::as_bytes_slice(string);
writer.write(buffer);
writer.write(string.as_bytes());
}
pub fn hash(data: ~str) -> ~str {

View File

@ -1091,7 +1091,7 @@ pub fn with_bytes_reader<T>(bytes: &[u8], f: &fn(@Reader) -> T) -> T {
}
pub fn with_str_reader<T>(s: &str, f: &fn(@Reader) -> T) -> T {
str::byte_slice(s, |bytes| with_bytes_reader(bytes, f))
with_bytes_reader(s.as_bytes(), f)
}
// Writing
@ -1462,7 +1462,7 @@ impl<T:Writer> WriterUtil for T {
self.write_str(str::from_char(ch));
}
}
fn write_str(&self, s: &str) { str::byte_slice(s, |v| self.write(v)) }
fn write_str(&self, s: &str) { self.write(s.as_bytes()) }
fn write_line(&self, s: &str) {
self.write_str(s);
self.write_str(&"\n");

View File

@ -793,27 +793,27 @@ mod tests {
#[test]
fn test_parse_bytes() {
use str::to_bytes;
assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123 as $T));
assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9 as $T));
assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83 as $T));
assert_eq!(i32::parse_bytes(to_bytes("123"), 16u), Some(291 as i32));
assert_eq!(i32::parse_bytes(to_bytes("ffff"), 16u), Some(65535 as i32));
assert_eq!(i32::parse_bytes(to_bytes("FFFF"), 16u), Some(65535 as i32));
assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35 as $T));
assert_eq!(parse_bytes(to_bytes("Z"), 36u), Some(35 as $T));
use str::StrSlice;
assert_eq!(parse_bytes("123".as_bytes(), 10u), Some(123 as $T));
assert_eq!(parse_bytes("1001".as_bytes(), 2u), Some(9 as $T));
assert_eq!(parse_bytes("123".as_bytes(), 8u), Some(83 as $T));
assert_eq!(i32::parse_bytes("123".as_bytes(), 16u), Some(291 as i32));
assert_eq!(i32::parse_bytes("ffff".as_bytes(), 16u), Some(65535 as i32));
assert_eq!(i32::parse_bytes("FFFF".as_bytes(), 16u), Some(65535 as i32));
assert_eq!(parse_bytes("z".as_bytes(), 36u), Some(35 as $T));
assert_eq!(parse_bytes("Z".as_bytes(), 36u), Some(35 as $T));
assert_eq!(parse_bytes(to_bytes("-123"), 10u), Some(-123 as $T));
assert_eq!(parse_bytes(to_bytes("-1001"), 2u), Some(-9 as $T));
assert_eq!(parse_bytes(to_bytes("-123"), 8u), Some(-83 as $T));
assert_eq!(i32::parse_bytes(to_bytes("-123"), 16u), Some(-291 as i32));
assert_eq!(i32::parse_bytes(to_bytes("-ffff"), 16u), Some(-65535 as i32));
assert_eq!(i32::parse_bytes(to_bytes("-FFFF"), 16u), Some(-65535 as i32));
assert_eq!(parse_bytes(to_bytes("-z"), 36u), Some(-35 as $T));
assert_eq!(parse_bytes(to_bytes("-Z"), 36u), Some(-35 as $T));
assert_eq!(parse_bytes("-123".as_bytes(), 10u), Some(-123 as $T));
assert_eq!(parse_bytes("-1001".as_bytes(), 2u), Some(-9 as $T));
assert_eq!(parse_bytes("-123".as_bytes(), 8u), Some(-83 as $T));
assert_eq!(i32::parse_bytes("-123".as_bytes(), 16u), Some(-291 as i32));
assert_eq!(i32::parse_bytes("-ffff".as_bytes(), 16u), Some(-65535 as i32));
assert_eq!(i32::parse_bytes("-FFFF".as_bytes(), 16u), Some(-65535 as i32));
assert_eq!(parse_bytes("-z".as_bytes(), 36u), Some(-35 as $T));
assert_eq!(parse_bytes("-Z".as_bytes(), 36u), Some(-35 as $T));
assert!(parse_bytes(to_bytes("Z"), 35u).is_none());
assert!(parse_bytes(to_bytes("-9"), 2u).is_none());
assert!(parse_bytes("Z".as_bytes(), 35u).is_none());
assert!(parse_bytes("-9".as_bytes(), 2u).is_none());
}
#[test]

View File

@ -16,6 +16,7 @@ use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use char;
use str;
use str::{StrSlice};
use kinds::Copy;
use vec;
use vec::{CopyableVector, ImmutableVector};
@ -189,18 +190,18 @@ pub fn to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Copy+
let _1: T = One::one();
if is_NaN(num) {
return (str::to_bytes("NaN"), true);
return ("NaN".as_bytes().to_owned(), true);
}
else if is_inf(num){
return match sign {
SignAll => (str::to_bytes("+inf"), true),
_ => (str::to_bytes("inf"), true)
SignAll => ("+inf".as_bytes().to_owned(), true),
_ => ("inf".as_bytes().to_owned(), true)
}
}
else if is_neg_inf(num) {
return match sign {
SignNone => (str::to_bytes("inf"), true),
_ => (str::to_bytes("-inf"), true),
SignNone => ("inf".as_bytes().to_owned(), true),
_ => ("-inf".as_bytes().to_owned(), true),
}
}
@ -638,7 +639,7 @@ pub fn from_str_common<T:NumCast+Zero+One+Eq+Ord+Copy+Div<T,T>+Mul<T,T>+
special: bool, exponent: ExponentFormat, empty_zero: bool,
ignore_underscores: bool
) -> Option<T> {
from_str_bytes_common(str::to_bytes(buf), radix, negative,
from_str_bytes_common(buf.as_bytes(), radix, negative,
fractional, special, exponent, empty_zero,
ignore_underscores)
}

View File

@ -538,16 +538,16 @@ mod tests {
#[test]
pub fn test_parse_bytes() {
use str::to_bytes;
assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123u as $T));
assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9u as $T));
assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83u as $T));
assert_eq!(u16::parse_bytes(to_bytes("123"), 16u), Some(291u as u16));
assert_eq!(u16::parse_bytes(to_bytes("ffff"), 16u), Some(65535u as u16));
assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35u as $T));
use str::StrSlice;
assert_eq!(parse_bytes("123".as_bytes(), 10u), Some(123u as $T));
assert_eq!(parse_bytes("1001".as_bytes(), 2u), Some(9u as $T));
assert_eq!(parse_bytes("123".as_bytes(), 8u), Some(83u as $T));
assert_eq!(u16::parse_bytes("123".as_bytes(), 16u), Some(291u as u16));
assert_eq!(u16::parse_bytes("ffff".as_bytes(), 16u), Some(65535u as u16));
assert_eq!(parse_bytes("z".as_bytes(), 36u), Some(35u as $T));
assert!(parse_bytes(to_bytes("Z"), 10u).is_none());
assert!(parse_bytes(to_bytes("_"), 2u).is_none());
assert!(parse_bytes("Z".as_bytes(), 10u).is_none());
assert!(parse_bytes("_".as_bytes(), 2u).is_none());
}
#[test]

View File

@ -1448,9 +1448,9 @@ mod tests {
use rand::RngUtil;
use rand;
use run;
use str;
use str::StrSlice;
use vec;
use vec::CopyableVector;
use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};
@ -1684,7 +1684,7 @@ mod tests {
};
assert!((ostream as uint != 0u));
let s = ~"hello";
let mut buf = str::to_bytes(s) + [0 as u8];
let mut buf = s.as_bytes_with_null().to_owned();
do vec::as_mut_buf(buf) |b, _len| {
assert!((libc::fwrite(b as *c_void, 1u as size_t,
(s.len() + 1u) as size_t, ostream)

View File

@ -947,7 +947,6 @@ pub mod windows {
mod tests {
use option::{None, Some};
use path::{PosixPath, WindowsPath, windows};
use str;
#[test]
fn test_double_slash_collapsing() {

View File

@ -64,7 +64,7 @@ pub use path::PosixPath;
pub use path::WindowsPath;
pub use ptr::RawPtr;
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr};
pub use str::{StrVector, StrSlice, OwnedStr, StrUtil};
pub use str::{StrVector, StrSlice, OwnedStr, StrUtil, NullTerminatedStr};
pub use from_str::{FromStr};
pub use to_bytes::IterBytes;
pub use to_str::{ToStr, ToStrConsume};

View File

@ -75,5 +75,5 @@ fn super_simple_smoke_test_lets_go_read_some_files_and_have_a_good_time() {
let message = "it's alright. have a good time";
let filename = &Path("test.txt");
let mut outstream = FileStream::open(filename, Create, Read).unwrap();
outstream.write(message.to_bytes());
outstream.write(message.as_bytes());
}

View File

@ -108,7 +108,7 @@ mod test {
let mem_writer = MemWriter::new();
let mut deflate_writer = DeflateWriter::new(mem_writer);
let in_msg = "test";
let in_bytes = in_msg.to_bytes();
let in_bytes = in_msg.as_bytes();
deflate_writer.write(in_bytes);
deflate_writer.flush();
let buf = deflate_writer.inner().inner();

View File

@ -741,8 +741,7 @@ fn with_envp<T>(env: Option<&[(~str, ~str)]>, cb: &fn(*mut c_void) -> T) -> T {
let mut blk = ~[];
for es.each |&(k, v)| {
let kv = fmt!("%s=%s", k, v);
blk.push_all(str::as_bytes_slice(kv));
blk.push(0);
blk.push_all(kv.as_bytes_consume_with_nul());
}
blk.push(0);
vec::as_imm_buf(blk, |p, _len|

View File

@ -304,40 +304,6 @@ impl<'self> StrVector for &'self [&'self str] {
}
}
/*
Section: Transforming strings
*/
/**
* Converts a string to a unique vector of bytes
*
* The result vector is not null-terminated.
*/
pub fn to_bytes(s: &str) -> ~[u8] {
unsafe {
let mut v: ~[u8] = ::cast::transmute(s.to_owned());
vec::raw::set_len(&mut v, s.len());
v
}
}
/// Work with the string as a byte slice, not including trailing null.
#[inline(always)]
pub fn byte_slice<T>(s: &str, f: &fn(v: &[u8]) -> T) -> T {
do as_buf(s) |p,n| {
unsafe { vec::raw::buf_as_slice(p, n-1u, f) }
}
}
/// Work with the string as a byte slice, not including trailing null, without
/// a callback.
#[inline(always)]
pub fn byte_slice_no_callback<'a>(s: &'a str) -> &'a [u8] {
unsafe {
cast::transmute(s)
}
}
/// Something that can be used to compare against a character
pub trait CharEq {
/// Determine if the splitter should split at the given character
@ -1081,39 +1047,6 @@ static tag_five_b: uint = 248u;
static max_five_b: uint = 67108864u;
static tag_six_b: uint = 252u;
/**
* Work with the byte buffer of a string.
*
* Allows for unsafe manipulation of strings, which is useful for foreign
* interop.
*
* # Example
*
* ~~~ {.rust}
* let i = str::as_bytes("Hello World") { |bytes| bytes.len() };
* ~~~
*/
#[inline]
pub fn as_bytes<T>(s: &const ~str, f: &fn(&~[u8]) -> T) -> T {
unsafe {
let v: *~[u8] = cast::transmute(copy s);
f(&*v)
}
}
/**
* Work with the byte buffer of a string as a byte slice.
*
* The byte slice does not include the null terminator.
*/
pub fn as_bytes_slice<'a>(s: &'a str) -> &'a [u8] {
unsafe {
let (ptr, len): (*u8, uint) = ::cast::transmute(s);
let outgoing_tuple: (*u8, uint) = (ptr, len - 1);
return ::cast::transmute(outgoing_tuple);
}
}
/**
* A dummy trait to hold all the utility methods that we implement on strings.
*/
@ -1216,11 +1149,10 @@ pub fn subslice_offset(outer: &str, inner: &str) -> uint {
* reallocating
*/
pub fn capacity(s: &const ~str) -> uint {
do as_bytes(s) |buf| {
let vcap = vec::capacity(buf);
assert!(vcap > 0u);
vcap - 1u
}
let buf: &const ~[u8] = unsafe { cast::transmute(s) };
let vcap = vec::capacity(buf);
assert!(vcap > 0u);
vcap - 1u
}
/// Escape each char in `s` with char::escape_default.
@ -1482,7 +1414,7 @@ pub trait StrSlice<'self> {
fn char_at(&self, i: uint) -> char;
fn char_range_at_reverse(&self, start: uint) -> CharRange;
fn char_at_reverse(&self, i: uint) -> char;
fn to_bytes(&self) -> ~[u8];
fn as_bytes(&self) -> &'self [u8];
fn find<C: CharEq>(&self, search: C) -> Option<uint>;
fn rfind<C: CharEq>(&self, search: C) -> Option<uint>;
@ -1545,12 +1477,12 @@ impl<'self> StrSlice<'self> for &'self str {
/// An iterator over the bytes of `self`
#[inline]
fn bytes_iter(&self) -> StrBytesIterator<'self> {
StrBytesIterator { it: as_bytes_slice(*self).iter() }
StrBytesIterator { it: self.as_bytes().iter() }
}
/// An iterator over the bytes of `self`, in reverse order
#[inline]
fn bytes_rev_iter(&self) -> StrBytesRevIterator<'self> {
StrBytesRevIterator { it: as_bytes_slice(*self).rev_iter() }
StrBytesRevIterator { it: self.as_bytes().rev_iter() }
}
/// An iterator over substrings of `self`, separated by characters
@ -1936,7 +1868,18 @@ impl<'self> StrSlice<'self> for &'self str {
self.char_range_at_reverse(i).ch
}
fn to_bytes(&self) -> ~[u8] { to_bytes(*self) }
/**
* Work with the byte buffer of a string as a byte slice.
*
* The byte slice does not include the null terminator.
*/
fn as_bytes(&self) -> &'self [u8] {
unsafe {
let (ptr, len): (*u8, uint) = ::cast::transmute(*self);
let outgoing_tuple: (*u8, uint) = (ptr, len - 1);
::cast::transmute(outgoing_tuple)
}
}
/**
* Returns the byte index of the first character of `self` that matches `search`
@ -2051,6 +1994,50 @@ impl<'self> StrSlice<'self> for &'self str {
}
#[allow(missing_doc)]
pub trait NullTerminatedStr {
fn as_bytes_with_null<'a>(&'a self) -> &'a [u8];
}
impl NullTerminatedStr for ~str {
/**
* Work with the byte buffer of a string as a byte slice.
*
* The byte slice does include the null terminator.
*/
#[inline]
fn as_bytes_with_null<'a>(&'a self) -> &'a [u8] {
let ptr: &'a ~[u8] = unsafe { ::cast::transmute(self) };
let slice: &'a [u8] = *ptr;
slice
}
}
impl NullTerminatedStr for @str {
/**
* Work with the byte buffer of a string as a byte slice.
*
* The byte slice does include the null terminator.
*/
#[inline]
fn as_bytes_with_null<'a>(&'a self) -> &'a [u8] {
let ptr: &'a ~[u8] = unsafe { ::cast::transmute(self) };
let slice: &'a [u8] = *ptr;
slice
}
}
// static strings are the only slices guaranteed to a nul-terminator
impl NullTerminatedStr for &'static str {
/**
* Work with the byte buffer of a string as a byte slice.
*
* The byte slice does include the null terminator.
*/
#[inline]
fn as_bytes_with_null(&self) -> &'static [u8] {
unsafe { ::cast::transmute(*self) }
}
}
#[allow(missing_doc)]
pub trait OwnedStr {
fn push_str_no_overallocate(&mut self, rhs: &str);
@ -2062,6 +2049,8 @@ pub trait OwnedStr {
fn append(&self, rhs: &str) -> ~str; // FIXME #4850: this should consume self.
fn reserve(&mut self, n: uint);
fn reserve_at_least(&mut self, n: uint);
fn as_bytes_with_null_consume(self) -> ~[u8];
}
impl OwnedStr for ~str {
@ -2251,6 +2240,13 @@ impl OwnedStr for ~str {
fn reserve_at_least(&mut self, n: uint) {
self.reserve(uint::next_power_of_two(n + 1u) - 1u)
}
/// Convert to a vector of bytes. This does not allocate a new
/// string, and includes the null terminator.
#[inline]
fn as_bytes_with_null_consume(self) -> ~[u8] {
unsafe { ::cast::transmute(self) }
}
}
impl Clone for ~str {
@ -2336,7 +2332,7 @@ mod tests {
use ptr;
use str::*;
use vec;
use vec::ImmutableVector;
use vec::{ImmutableVector, CopyableVector};
use cmp::{TotalOrd, Less, Equal, Greater};
#[test]
@ -2952,12 +2948,70 @@ mod tests {
}
}
#[test]
fn test_as_bytes() {
// no null
let v = [
224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
109
];
assert_eq!("".as_bytes(), &[]);
assert_eq!("abc".as_bytes(), &['a' as u8, 'b' as u8, 'c' as u8]);
assert_eq!("ศไทย中华Việt Nam".as_bytes(), v);
}
#[test]
fn test_as_bytes_with_null() {
// has null
let v = [
224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
109, 0
];
assert_eq!("".as_bytes_with_null(), &[0]);
assert_eq!("abc".as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]);
assert_eq!("ศไทย中华Việt Nam".as_bytes_with_null(), v);
let s1 = @"";
let s2 = @"abc";
let s3 = @"ศไทย中华Việt Nam";
assert_eq!(s1.as_bytes_with_null(), &[0]);
assert_eq!(s2.as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]);
assert_eq!(s3.as_bytes_with_null(), v);
let s1 = ~"";
let s2 = ~"abc";
let s3 = ~"ศไทย中华Việt Nam";
assert_eq!(s1.as_bytes_with_null(), &[0]);
assert_eq!(s2.as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]);
assert_eq!(s3.as_bytes_with_null(), v);
}
#[test]
fn test_as_bytes_with_null_consume() {
let s = ~"ศไทย中华Việt Nam";
let v = ~[
224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
109, 0
];
assert_eq!((~"").as_bytes_with_null_consume(), ~[0]);
assert_eq!((~"abc").as_bytes_with_null_consume(),
~['a' as u8, 'b' as u8, 'c' as u8, 0]);
assert_eq!(s.as_bytes_with_null_consume(), v);
}
#[test]
#[ignore(cfg(windows))]
#[should_fail]
fn test_as_bytes_fail() {
// Don't double free
as_bytes::<()>(&~"", |_bytes| fail!() );
// Don't double free. (I'm not sure if this exercises the
// original problem code path anymore.)
let s = ~"";
let _bytes = s.as_bytes_with_null();
fail!();
}
#[test]
@ -3032,7 +3086,7 @@ mod tests {
fn vec_str_conversions() {
let s1: ~str = ~"All mimsy were the borogoves";
let v: ~[u8] = to_bytes(s1);
let v: ~[u8] = s1.as_bytes().to_owned();
let s2: ~str = from_bytes(v);
let mut i: uint = 0u;
let n1: uint = s1.len();

View File

@ -18,7 +18,7 @@ use io;
use io::Writer;
use option::{None, Option, Some};
use old_iter::BaseIter;
use str;
use str::StrSlice;
pub type Cb<'self> = &'self fn(buf: &[u8]) -> bool;
@ -239,27 +239,25 @@ impl<A:IterBytes> IterBytes for @[A] {
impl<'self> IterBytes for &'self str {
#[inline(always)]
fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool {
do str::byte_slice(*self) |bytes| {
f(bytes)
}
f(self.as_bytes())
}
}
impl IterBytes for ~str {
#[inline(always)]
fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool {
do str::byte_slice(*self) |bytes| {
f(bytes)
}
// this should possibly include the null terminator, but that
// breaks .find_equiv on hashmaps.
f(self.as_bytes())
}
}
impl IterBytes for @str {
#[inline(always)]
fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool {
do str::byte_slice(*self) |bytes| {
f(bytes)
}
// this should possibly include the null terminator, but that
// breaks .find_equiv on hashmaps.
f(self.as_bytes())
}
}

View File

@ -21,8 +21,6 @@ use ext::base::*;
use parse;
use parse::token;
use core::vec;
enum State {
Asm,
Outputs,

View File

@ -22,7 +22,6 @@ use parse::token;
use parse::token::{ident_to_str, intern, str_to_ident};
use core::hashmap::HashMap;
use core::vec;
// new-style macro! tt code:
//

View File

@ -18,7 +18,6 @@ use print;
use parse::token::{get_ident_interner};
use core::io;
use core::vec;
pub fn expand_syntax_ext(cx: @ExtCtxt,
sp: codemap::span,

View File

@ -19,8 +19,6 @@ use parse::token::*;
use parse::token;
use parse;
use core::vec;
/**
*
* Quasiquoting works via token trees.

View File

@ -18,8 +18,6 @@ use parse::lexer::{new_tt_reader, reader};
use parse::parser::Parser;
use parse::token::keywords;
use core::vec;
pub fn expand_trace_macros(cx: @ExtCtxt,
sp: span,
tt: &[ast::token_tree])

View File

@ -26,7 +26,6 @@ use parse::token::{FAT_ARROW, SEMI, nt_matchers, nt_tt};
use print;
use core::io;
use core::vec;
pub fn add_new_extension(cx: @ExtCtxt,
sp: span,

View File

@ -93,7 +93,7 @@ impl RepeatFasta {
let stdout = self.stdout;
let alu_len = self.alu.len();
let mut buf = vec::from_elem(alu_len + LINE_LEN, 0u8);
let alu: &[u8] = str::byte_slice_no_callback(self.alu);
let alu: &[u8] = self.alu.as_bytes_with_null();
copy_memory(buf, alu, alu_len);
copy_memory(vec::mut_slice(buf, alu_len, buf.len()),

View File

@ -81,7 +81,8 @@ fn sort_and_fmt(mm: &HashMap<~[u8], uint>, total: uint) -> ~str {
fn find(mm: &HashMap<~[u8], uint>, key: ~str) -> uint {
// FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
// to_ascii_consume and to_str_consume to not do a unnecessary copy.
match mm.find(&str::to_bytes(key.to_ascii().to_lower().to_str_ascii())) {
let key = key.to_ascii().to_lower().to_str_ascii();
match mm.find_equiv(&key.as_bytes()) {
option::None => { return 0u; }
option::Some(&num) => { return num; }
}
@ -208,10 +209,10 @@ fn main() {
// process the sequence for k-mers
(_, true) => {
let line_bytes = str::to_bytes(line);
let line_bytes = line.as_bytes();
for sizes.eachi |ii, _sz| {
let mut lb = copy line_bytes;
let mut lb = line_bytes.to_owned();
to_child[ii].send(lb);
}
}

View File

@ -218,8 +218,7 @@ fn read_stdin() -> ~[u8] {
fstat(fileno(stdin), &mut st);
let mut buf = vec::from_elem(st.st_size as uint, 0);
let header = str::byte_slice_no_callback(">THREE");
let header = vec::slice(header, 0, 6);
let header = ">THREE".as_bytes();
{
let mut window: &mut [u8] = buf;

View File

@ -111,8 +111,7 @@ fn main() {
if opts.stress {
stress(2);
} else {
let max = uint::parse_bytes(str::to_bytes(args[1]),
10u).get() as int;
let max = uint::parse_bytes(args[1].as_bytes(), 10u).get() as int;
let num_trials = 10;

View File

@ -26,7 +26,7 @@ mod libc {
fn strlen(str: ~str) -> uint {
unsafe {
// C string is terminated with a zero
let bytes = str::to_bytes(str) + ~[0u8];
let bytes = str.as_bytes_with_null_consume();
return libc::my_strlen(vec::raw::to_ptr(bytes));
}
}

View File

@ -48,7 +48,7 @@ mod map_reduce {
}
let (pp, cc) = stream();
error!("sending find_reducer");
ctrl.send(find_reducer(str::to_bytes(key), cc));
ctrl.send(find_reducer(key.as_bytes().to_owned(), cc));
error!("receiving");
let c = pp.recv();
error!(c);

View File

@ -15,6 +15,6 @@ use std::str;
pub fn main() {
let mut m = HashMap::new();
m.insert(str::to_bytes(~"foo"), str::to_bytes(~"bar"));
m.insert("foo".as_bytes().to_owned(), "bar".as_bytes().to_owned());
error!(m);
}

View File

@ -27,7 +27,7 @@ pub fn main() {
assert!(s.char_at(0u) == 'e');
assert!(s.char_at(1u) == 'é');
assert!((str::is_utf8(str::to_bytes(s))));
assert!((str::is_utf8(s.as_bytes())));
assert!((!str::is_utf8(~[0x80_u8])));
assert!((!str::is_utf8(~[0xc0_u8])));
assert!((!str::is_utf8(~[0xc0_u8, 0x10_u8])));