auto merge of #7060 : huonw/rust/more-str, r=thestinger

There are now only half-a-dozen or so functions left `std::str` that should be methods.

Highlights:
- `.substr` was removed, since most of the uses of it in the code base were actually incorrect (it had a weird mixing of a byte index and a unicode character count), adding `.slice_chars` if one wants to handle characters, and the normal `.slice` method to handle bytes.
- Code duplication between the two impls for `connect` and `concat` was removed via a new `Str` trait, that is purely designed to allow an explicit -> `&str` conversion (`.as_slice()`)
- Deconfuse the 5 different functions for converting to `[u8]` (3 of which had actually incorrect documentation: implying that they didn't have the null terminator), into 3: `as_bytes` (all strings), `as_bytes_with_null` (`&'static str`, `@str` and `~str`) and `as_bytes_with_null_consume` (`~str`). None of these allocate, unlike the old versions.

(cc @thestinger)
This commit is contained in:
bors
2013-06-11 21:37:43 -07:00
80 changed files with 818 additions and 789 deletions
+1 -1
View File
@@ -1410,7 +1410,7 @@ let new_favorite_crayon_name = favorite_crayon_name.trim();
if favorite_crayon_name.len() > 5 {
// Create a substring
println(favorite_crayon_name.substr(0, 5));
println(favorite_crayon_name.slice_chars(0, 5));
}
~~~
+4 -4
View File
@@ -171,8 +171,8 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
if props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = ~"\r";
actual = str::replace(actual, cr, "");
expected = str::replace(expected, cr, "");
actual = actual.replace(cr, "");
expected = expected.replace(cr, "");
}
compare_source(expected, actual);
@@ -238,7 +238,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) {
// do not optimize debuginfo tests
let mut config = match config.rustcflags {
Some(ref flags) => config {
rustcflags: Some(str::replace(*flags, "-O", "")),
rustcflags: Some(flags.replace("-O", "")),
.. copy *config
},
None => copy *config
@@ -254,7 +254,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) {
}
// write debugger script
let script_str = str::append(cmds, "\nquit\n");
let script_str = cmds.append("\nquit\n");
debug!("script_str = %s", script_str);
dump_output_file(config, testfile, script_str, "debugger.script");
+9 -10
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 @@ fn test_to_base64() {
#[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());
}
}
+2 -3
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 fn wr_tagged_i8(&mut self, tag_id: uint, v: i8) {
}
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 fn wr_bytes(&mut self, b: &[u8]) {
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());
}
}
+1 -1
View File
@@ -487,7 +487,7 @@ fn test_fileinput_read() {
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);
}
+1 -1
View File
@@ -450,7 +450,7 @@ pub fn deserialize_buffer<D: Decoder + FromReader,
T: Decodable<D>>(
buf: &[u8])
-> T {
let buf = vec::to_owned(buf);
let buf = buf.to_owned();
let buf_reader = @BufReader::new(buf);
let reader = buf_reader as @Reader;
let mut deser: D = FromReader::from_reader(reader);
+25 -25
View File
@@ -345,7 +345,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
}
i += 1;
}
return Ok(Matches {opts: vec::to_owned(opts),
return Ok(Matches {opts: opts.to_owned(),
vals: vals,
free: free});
}
@@ -447,7 +447,7 @@ pub fn opt_default(mm: &Matches, nm: &str, def: &str) -> Option<~str> {
let vals = opt_vals(mm, nm);
if vals.is_empty() { return None::<~str>; }
return match vals[0] { Val(ref s) => Some::<~str>(copy *s),
_ => Some::<~str>(str::to_owned(def)) }
_ => Some::<~str>(def.to_owned()) }
}
#[deriving(Eq)]
@@ -487,10 +487,10 @@ pub fn reqopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup { short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
return OptGroup { short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: hint.to_owned(),
desc: desc.to_owned(),
hasarg: Yes,
occur: Req};
}
@@ -500,10 +500,10 @@ pub fn optopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
return OptGroup {short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: hint.to_owned(),
desc: desc.to_owned(),
hasarg: Yes,
occur: Optional};
}
@@ -513,10 +513,10 @@ pub fn optflag(short_name: &str, long_name: &str,
desc: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
return OptGroup {short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: ~"",
desc: str::to_owned(desc),
desc: desc.to_owned(),
hasarg: No,
occur: Optional};
}
@@ -526,10 +526,10 @@ pub fn optflagopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
return OptGroup {short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: hint.to_owned(),
desc: desc.to_owned(),
hasarg: Maybe,
occur: Optional};
}
@@ -542,10 +542,10 @@ pub fn optmulti(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
return OptGroup {short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: hint.to_owned(),
desc: desc.to_owned(),
hasarg: Yes,
occur: Multi};
}
@@ -593,7 +593,7 @@ pub fn getopts(args: &[~str], opts: &[OptGroup]) -> ::getopts::Result {
*/
pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
let desc_sep = ~"\n" + str::repeat(" ", 24);
let desc_sep = ~"\n" + " ".repeat(24);
let rows = vec::map(opts, |optref| {
let OptGroup{short_name: short_name,
@@ -603,7 +603,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
hasarg: hasarg,
_} = copy *optref;
let mut row = str::repeat(" ", 4);
let mut row = " ".repeat(4);
// short option
row += match short_name.len() {
@@ -629,7 +629,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
// here we just need to indent the start of the description
let rowlen = row.len();
row += if rowlen < 24 {
str::repeat(" ", 24 - rowlen)
" ".repeat(24 - rowlen)
} else {
copy desc_sep
};
@@ -654,7 +654,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
row
});
return str::to_owned(brief) +
return brief.to_owned() +
"\n\nOptions:\n" +
rows.connect("\n") +
"\n\n";
+2 -3
View File
@@ -10,7 +10,6 @@
use core::prelude::*;
use core::str;
use core::uint;
use core::vec;
@@ -30,7 +29,7 @@ pub fn md4(msg: &[u8]) -> Quad {
let orig_len: u64 = (msg.len() * 8u) as u64;
// pad message
let mut msg = vec::append(vec::to_owned(msg), [0x80u8]);
let mut msg = vec::append(msg.to_owned(), [0x80u8]);
let mut bitlen = orig_len + 8u64;
while (bitlen + 64u64) % 512u64 > 0u64 {
msg.push(0u8);
@@ -129,7 +128,7 @@ fn app(a: u32, b: u32, c: u32, d: u32, f: &fn(u32)) {
/// 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() {
+9 -11
View File
@@ -1636,7 +1636,7 @@ pub fn impl_gl_tcp_ipv4_get_peer_addr() {
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 @@ pub fn impl_gl_tcp_ipv4_server_client_reader_writer() {
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 @@ pub fn impl_tcp_socket_impl_reader_handles_eof() {
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 @@ fn run_tcp_test_server(server_ip: &str, server_port: uint, resp: ~str,
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 @@ fn run_tcp_test_client(server_ip: &str, server_port: uint, resp: &str,
}
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() {
+1 -1
View File
@@ -1060,7 +1060,7 @@ fn test_decode_form_urlencoded() {
/*
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"]);
+4 -4
View File
@@ -524,7 +524,7 @@ fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> ~str {
let s = uint::to_str_radix(*n as uint, radix);
str::from_chars(vec::from_elem(l - s.len(), '0')) + s
}).concat();
s.trim_left_chars(['0']).to_owned()
s.trim_left_chars(&'0').to_owned()
}
}
}
@@ -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)
}
}
@@ -564,7 +564,7 @@ pub fn from_uint(n: uint) -> BigUint {
/// Creates and initializes an BigUint.
pub fn from_slice(slice: &[BigDigit]) -> BigUint {
return BigUint::new(vec::to_owned(slice));
return BigUint::new(slice.to_owned());
}
/// Creates and initializes an BigUint.
@@ -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)
}
}
+12 -13
View File
@@ -84,9 +84,9 @@ pub fn of_str(str: @~str) -> Rope {
*
* # Return value
*
* A rope representing the same string as `str.substr(byte_offset,
* byte_len)`. Depending on `byte_len`, this rope may be empty, flat
* or complex.
* A rope representing the same string as `str.slice(byte_offset,
* byte_offset + byte_len)`. Depending on `byte_len`, this rope may
* be empty, flat or complex.
*
* # Performance note
*
@@ -564,7 +564,6 @@ pub mod node {
use rope::node;
use core::cast;
use core::str;
use core::uint;
use core::vec;
@@ -588,7 +587,7 @@ pub enum Root {
* * char_len - The number of chars in the leaf.
* * content - Contents of the leaf.
*
* Note that we can have `char_len < str::char_len(content)`, if
* Note that we can have `char_len < content.char_len()`, if
* this leaf is only a subset of the string. Also note that the
* string can be shared between several ropes, e.g. for indexing
* purposes.
@@ -680,7 +679,7 @@ pub fn of_str(str: @~str) -> @Node {
*/
pub fn of_substr(str: @~str, byte_start: uint, byte_len: uint) -> @Node {
return of_substr_unsafer(str, byte_start, byte_len,
str::count_chars(*str, byte_start, byte_len));
str.slice(byte_start, byte_start + byte_len).char_len());
}
/**
@@ -734,7 +733,7 @@ pub fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint,
if i == 0u { first_leaf_char_len }
else { hint_max_leaf_char_len };
let chunk_byte_len =
str::count_bytes(*str, offset, chunk_char_len);
str.slice_from(offset).slice_chars(0, chunk_char_len).len();
nodes[i] = @Leaf(Leaf {
byte_offset: offset,
byte_len: chunk_byte_len,
@@ -938,7 +937,7 @@ pub fn sub_bytes(node: @Node, byte_offset: uint,
match (*node) {
node::Leaf(x) => {
let char_len =
str::count_chars(*x.content, byte_offset, byte_len);
x.content.slice(byte_offset, byte_offset + byte_len).char_len();
return @Leaf(Leaf {
byte_offset: byte_offset,
byte_len: byte_len,
@@ -1002,9 +1001,9 @@ pub fn sub_chars(node: @Node, char_offset: uint,
return node;
}
let byte_offset =
str::count_bytes(*x.content, 0u, char_offset);
x.content.slice_chars(0, char_offset).len();
let byte_len =
str::count_bytes(*x.content, byte_offset, char_len);
x.content.slice_from(byte_offset).slice_chars(0, char_len).len();
return @Leaf(Leaf {
byte_offset: byte_offset,
byte_len: byte_len,
@@ -1312,7 +1311,7 @@ fn of_string1() {
let sample = @~"0123456789ABCDE";
let r = of_str(sample);
assert_eq!(char_len(r), str::char_len(*sample));
assert_eq!(char_len(r), sample.char_len());
assert!(rope_to_string(r) == *sample);
}
@@ -1328,7 +1327,7 @@ fn of_string2() {
}
let sample = @copy *buf;
let r = of_str(sample);
assert!(char_len(r) == str::char_len(*sample));
assert_eq!(char_len(r), sample.char_len());
assert!(rope_to_string(r) == *sample);
let mut string_iter = 0u;
@@ -1374,7 +1373,7 @@ fn iter1() {
}
}
assert_eq!(len, str::char_len(*sample));
assert_eq!(len, sample.char_len());
}
#[test]
+1 -3
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 @@ fn reset(&mut self) {
}
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 {
+1 -2
View File
@@ -13,7 +13,6 @@
use core::prelude::*;
use core::iterator::*;
use core::vec;
use core::f64;
use core::cmp;
use core::num;
@@ -57,7 +56,7 @@ fn mean(self) -> f64 {
fn median(self) -> f64 {
assert!(self.len() != 0);
let mut tmp = vec::to_owned(self);
let mut tmp = self.to_owned();
sort::tim_sort(tmp);
if tmp.len() & 1 == 0 {
let m = tmp.len() / 2;
+5 -2
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,
+4 -4
View File
@@ -12,7 +12,7 @@
/// Does not support hashed database, only filesystem!
use core::prelude::*;
use core::{os};
use core::{os, str};
use core::os::getenv;
use core::io::{file_reader, Reader};
use core::iterator::IteratorUtil;
@@ -27,7 +27,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option<~path> {
let homedir = os::homedir();
let mut dirs_to_search = ~[];
let first_char = term.substr(0, 1);
let first_char = term.char_at(0);
// Find search directory
match getenv("TERMINFO") {
@@ -57,12 +57,12 @@ pub fn get_dbpath_for_term(term: &str) -> Option<~path> {
// Look for the terminal in all of the search directories
for dirs_to_search.each |p| {
let newp = ~p.push_many(&[first_char.to_owned(), term.to_owned()]);
let newp = ~p.push_many(&[str::from_char(first_char), term.to_owned()]);
if os::path_exists(p) && os::path_exists(newp) {
return Some(newp);
}
// on some installations the dir is named after the hex of the char (e.g. OS X)
let newp = ~p.push_many(&[fmt!("%x", first_char[0] as uint), term.to_owned()]);
let newp = ~p.push_many(&[fmt!("%x", first_char as uint), term.to_owned()]);
if os::path_exists(p) && os::path_exists(newp) {
return Some(newp);
}
+1 -1
View File
@@ -1029,7 +1029,7 @@ fn test_strptime() {
fn test(s: &str, format: &str) -> bool {
match strptime(s, format) {
Ok(ref tm) => tm.strftime(format) == str::to_owned(s),
Ok(ref tm) => tm.strftime(format) == s.to_owned(),
Err(e) => fail!(e)
}
}
+4 -4
View File
@@ -769,10 +769,10 @@ fn test_clear() {
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);
+2 -2
View File
@@ -1368,7 +1368,7 @@ fn impl_uv_tcp_request(ip: &str, port: int, req_str: &str,
// 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 @@ fn impl_uv_tcp_server(server_ip: &str,
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 = ~[
+1 -1
View File
@@ -328,7 +328,7 @@ pub fn check_variants_T<T:Copy>(crate: @ast::crate,
if L < 100 {
do under(uint::min(L, 20)) |i| {
error!("Replacing... #%?", uint::to_str(i));
let fname = str::to_owned(filename.to_str());
let fname = filename.to_str();
do under(uint::min(L, 30)) |j| {
let fname = fname.to_str();
error!("With... %?", stringifier(things[j], intr));
+1 -2
View File
@@ -36,7 +36,6 @@ use core::io;
use core::os;
use core::run;
use core::libc::exit;
use core::str;
// For bootstrapping.
mod std {
@@ -225,7 +224,7 @@ fn usage() {
);
for commands.each |command| {
let padding = str::repeat(" ", indent - command.cmd.len());
let padding = " ".repeat(indent - command.cmd.len());
io::println(fmt!(" %s%s%s",
command.cmd, padding, command.usage_line));
}
+2 -3
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) -> ! {
@@ -637,7 +636,7 @@ pub fn symbol_hash(tcx: ty::ctxt,
write_string(symbol_hasher, encoder::encoded_ty(tcx, t));
let mut hash = truncated_hash_result(symbol_hasher);
// Prefix with _ so that it never blends into adjacent digits
str::unshift_char(&mut hash, '_');
hash.unshift_char('_');
// tjc: allocation is unfortunate; need to change core::hash
hash.to_managed()
}
+4 -5
View File
@@ -29,7 +29,6 @@
use core::int;
use core::io;
use core::os;
use core::str;
use core::vec;
use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt};
use extra::getopts::{opt_present};
@@ -96,9 +95,9 @@ pub fn default_configuration(sess: Session, argv0: @~str, input: &input) ->
};
return ~[ // Target bindings.
attr::mk_word_item(@str::to_owned(os::FAMILY)),
attr::mk_word_item(@os::FAMILY.to_owned()),
mk(@~"target_os", @tos),
mk(@~"target_family", @str::to_owned(os::FAMILY)),
mk(@~"target_family", @os::FAMILY.to_owned()),
mk(@~"target_arch", @arch),
mk(@~"target_endian", @end),
mk(@~"target_word_size", @wordsz),
@@ -590,12 +589,12 @@ pub fn build_session_options(binary: @~str,
// 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.
let level_short = level_name.substr(0,1);
let level_short = level_name.slice_chars(0, 1);
let level_short = level_short.to_ascii().to_upper().to_str_ascii();
let flags = vec::append(getopts::opt_strs(matches, level_short),
getopts::opt_strs(matches, level_name));
for flags.each |lint_name| {
let lint_name = str::replace(*lint_name, "-", "_");
let lint_name = lint_name.replace("-", "_");
match lint_dict.find(&lint_name) {
None => {
early_error(demitter, fmt!("unknown %s flag: %s",
+1 -1
View File
@@ -570,7 +570,7 @@ pub fn maybe_get_item_ast(cdata: cmd, tcx: ty::ctxt,
let item_doc = lookup_item(id, cdata.data);
let path = {
let item_path = item_path(item_doc);
vec::to_owned(item_path.init())
item_path.init().to_owned()
};
match decode_inlined_item(cdata, tcx, copy path, item_doc) {
Some(ref ii) => csearch::found((/*bad*/copy *ii)),
+20 -15
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 add_to_index_(item: @item, ebml_w: &writer::Encoder,
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();
}
@@ -1516,7 +1521,7 @@ pub fn encode_metadata(parms: EncodeParams, crate: &crate) -> ~[u8] {
let writer_bytes: &mut ~[u8] = wr.bytes;
vec::to_owned(metadata_encoding_version) +
metadata_encoding_version.to_owned() +
flate::deflate_bytes(*writer_bytes)
}
+2 -3
View File
@@ -13,7 +13,6 @@
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
@@ -81,7 +80,7 @@ fn get_target_lib_file_path(&self, file: &Path) -> Path {
@FileSearchImpl {
sysroot: sysroot,
addl_lib_search_paths: addl_lib_search_paths,
target_triple: str::to_owned(target_triple)
target_triple: target_triple.to_owned()
} as @FileSearch
}
@@ -107,7 +106,7 @@ pub fn search<T:Copy>(filesearch: @FileSearch, pick: pick<T>) -> Option<T> {
pub fn relative_target_lib_path(target_triple: &str) -> Path {
Path(libdir()).push_many([~"rustc",
str::to_owned(target_triple),
target_triple.to_owned(),
libdir()])
}
+1 -1
View File
@@ -80,7 +80,7 @@ fn libname(cx: &Context) -> (~str, ~str) {
os_freebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
};
(str::to_owned(dll_prefix), str::to_owned(dll_suffix))
(dll_prefix.to_owned(), dll_suffix.to_owned())
}
fn find_library_crate_aux(
+11 -11
View File
@@ -495,7 +495,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
match cx.tcx.def_map.find(&pat_id) {
Some(&def_variant(_, id)) => {
if variant(id) == *ctor_id {
Some(vec::to_owned(r.tail()))
Some(r.tail().to_owned())
} else {
None
}
@@ -533,7 +533,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
_ => fail!("type error")
};
if match_ {
Some(vec::to_owned(r.tail()))
Some(r.tail().to_owned())
} else {
None
}
@@ -580,7 +580,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
_ => fail!("type error")
};
if match_ {
Some(vec::to_owned(r.tail()))
Some(r.tail().to_owned())
} else {
None
}
@@ -590,7 +590,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
Some(args) => args,
None => vec::from_elem(arity, wild())
};
Some(vec::append(args, vec::to_owned(r.tail())))
Some(vec::append(args, r.tail().to_owned()))
}
def_variant(_, _) => None,
@@ -602,7 +602,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
Some(args) => new_args = args,
None => new_args = vec::from_elem(arity, wild())
}
Some(vec::append(new_args, vec::to_owned(r.tail())))
Some(vec::append(new_args, r.tail().to_owned()))
}
_ => None
}
@@ -620,7 +620,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
_ => wild()
}
});
Some(vec::append(args, vec::to_owned(r.tail())))
Some(vec::append(args, r.tail().to_owned()))
} else {
None
}
@@ -651,7 +651,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
_ => wild()
}
});
Some(vec::append(args, vec::to_owned(r.tail())))
Some(vec::append(args, r.tail().to_owned()))
}
}
}
@@ -687,14 +687,14 @@ pub fn specialize(cx: @MatchCheckCtxt,
single => true,
_ => fail!("type error")
};
if match_ { Some(vec::to_owned(r.tail())) } else { None }
if match_ { Some(r.tail().to_owned()) } else { None }
}
pat_range(lo, hi) => {
let (c_lo, c_hi) = match *ctor_id {
val(ref v) => ((/*bad*/copy *v), (/*bad*/copy *v)),
range(ref lo, ref hi) =>
((/*bad*/copy *lo), (/*bad*/copy *hi)),
single => return Some(vec::to_owned(r.tail())),
single => return Some(r.tail().to_owned()),
_ => fail!("type error")
};
let v_lo = eval_const_expr(cx.tcx, lo);
@@ -704,7 +704,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
let m2 = compare_const_vals(&c_hi, &v_hi);
match (m1, m2) {
(Some(val1), Some(val2)) if val1 >= 0 && val2 <= 0 => {
Some(vec::to_owned(r.tail()))
Some(r.tail().to_owned())
},
(Some(_), Some(_)) => None,
_ => {
@@ -745,7 +745,7 @@ pub fn specialize(cx: @MatchCheckCtxt,
}
pub fn default(cx: @MatchCheckCtxt, r: &[@pat]) -> Option<~[@pat]> {
if is_wild(cx, r[0]) { Some(vec::to_owned(r.tail())) }
if is_wild(cx, r[0]) { Some(r.tail().to_owned()) }
else { None }
}
+2 -3
View File
@@ -23,7 +23,6 @@
use core::i32;
use core::i64;
use core::i8;
use core::str;
use core::u16;
use core::u32;
use core::u64;
@@ -375,7 +374,7 @@ fn span_lint(&self, lint: lint, span: span, msg: &str) {
fmt!("%s [-%c %s%s]", msg, match level {
warn => 'W', deny => 'D', forbid => 'F',
allow => fail!()
}, str::replace(self.lint_to_str(lint), "_", "-"),
}, self.lint_to_str(lint).replace("_", "-"),
if src == Default { " (default)" } else { "" })
},
Node(src) => {
@@ -842,7 +841,7 @@ fn check_item_non_camel_case_types(cx: &Context, it: @ast::item) {
fn is_camel_case(cx: ty::ctxt, ident: ast::ident) -> bool {
let ident = cx.sess.str_of(ident);
assert!(!ident.is_empty());
let ident = ident.trim_chars(&['_']);
let ident = ident.trim_chars(&'_');
char::is_uppercase(ident.char_at(0)) &&
!ident.contains_char('_')
}
+6 -6
View File
@@ -2678,14 +2678,14 @@ pub fn resolve_module_path(@mut self,
match module_prefix_result {
Failed => {
let mpath = self.idents_to_str(module_path);
match self.idents_to_str(module_path).rfind(':') {
match mpath.rfind(':') {
Some(idx) => {
self.session.span_err(span, fmt!("unresolved import: could not find `%s` \
in `%s`", mpath.substr(idx,
mpath.len() - idx),
// idx - 1 to account for the extra
// colon
mpath.substr(0, idx - 1)));
in `%s`",
// idx +- 1 to account for the colons
// on either side
mpath.slice_from(idx + 1),
mpath.slice_to(idx - 1)));
},
None => (),
};
+1 -2
View File
@@ -48,7 +48,6 @@
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;
@@ -218,7 +217,7 @@ fn mk_struct(cx: @CrateContext, tys: &[ty::t], packed: bool) -> Struct {
size: machine::llsize_of_alloc(cx, llty_rec) /*bad*/as u64,
align: machine::llalign_of_min(cx, llty_rec) /*bad*/as u64,
packed: packed,
fields: vec::to_owned(tys)
fields: tys.to_owned()
}
}
+1 -1
View File
@@ -114,7 +114,7 @@ impl get_insn_ctxt for @CrateContext {
fn insn_ctxt(&self, s: &str) -> icx_popper {
debug!("new insn_ctxt: %s", s);
if self.sess.count_llvm_insns() {
self.stats.llvm_insn_ctxt.push(str::to_owned(s));
self.stats.llvm_insn_ctxt.push(s.to_owned());
}
icx_popper(*self)
}
+2 -2
View File
@@ -885,9 +885,9 @@ pub fn add_comment(bcx: block, text: &str) {
unsafe {
let ccx = bcx.ccx();
if ccx.sess.asm_comments() {
let sanitized = str::replace(text, "$", "");
let sanitized = text.replace("$", "");
let comment_text = ~"# " +
str::replace(sanitized, "\n", "\n\t# ");
sanitized.replace("\n", "\n\t# ");
let asm = str::as_c_str(comment_text, |c| {
str::as_c_str("", |e| {
count_insn(bcx, "inlineasm");
+1 -1
View File
@@ -1704,5 +1704,5 @@ fn trans_assign_op(bcx: block,
}
fn shorten(x: ~str) -> ~str {
if x.len() > 60 { x.substr(0, 60).to_owned() } else { x }
if x.char_len() > 60 { x.slice_chars(0, 60).to_owned() } else { x }
}
+1 -1
View File
@@ -3898,7 +3898,7 @@ pub fn item_path(cx: ctxt, id: ast::def_id) -> ast_map::path {
}
ast_map::node_variant(ref variant, _, path) => {
vec::append_one(vec::to_owned(vec::init(*path)),
vec::append_one(path.init().to_owned(),
ast_map::path_name((*variant).node.name))
}
+1 -1
View File
@@ -209,7 +209,7 @@ Available lint options:
io::println(fmt!(" %s %7.7s %s\n",
padded(max_key, "----"), "-------", "-------"));
for lint_dict.each |k, v| {
let k = str::replace(*k, "_", "-");
let k = k.replace("_", "-");
io::println(fmt!(" %s %7.7s %s",
padded(max_key, k),
match v.default {
-1
View File
@@ -17,7 +17,6 @@
use core::prelude::*;
use core::str;
use syntax::ast;
use syntax::attr;
+1 -1
View File
@@ -262,7 +262,7 @@ fn should_find_pandoc() {
.. 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")));
+4 -4
View File
@@ -108,7 +108,7 @@ fn first_sentence(s: ~str) -> Option<~str> {
let paras = paragraphs(s);
if !paras.is_empty() {
let first_para = paras.head();
Some(str::replace(first_sentence_(*first_para), "\n", " "))
Some(first_sentence_(*first_para).replace("\n", " "))
} else {
None
}
@@ -131,13 +131,13 @@ fn first_sentence_(s: &str) -> ~str {
});
match idx {
Some(idx) if idx > 2u => {
str::to_owned(s.slice(0, idx - 1))
s.slice_to(idx - 1).to_owned()
}
_ => {
if s.ends_with(".") {
str::to_owned(s)
s.to_owned()
} else {
str::to_owned(s)
s.to_owned()
}
}
}
+1 -3
View File
@@ -13,14 +13,12 @@
use pass::Pass;
use text_pass;
use core::str;
pub fn mk_pass() -> Pass {
text_pass::mk_pass(~"escape", escape)
}
fn escape(s: &str) -> ~str {
str::replace(s, "\\", "\\\\")
s.replace("\\", "\\\\")
}
#[test]
+18 -20
View File
@@ -22,8 +22,6 @@
use markdown_writer;
use pass::Pass;
use core::str;
pub fn mk_pass(config: config::Config) -> Pass {
Pass {
name: ~"markdown_index",
@@ -128,24 +126,24 @@ pub fn pandoc_header_id(header: &str) -> ~str {
return header;
fn remove_formatting(s: &str) -> ~str {
str::replace(s, "`", "")
s.replace("`", "")
}
fn remove_punctuation(s: &str) -> ~str {
let s = str::replace(s, "<", "");
let s = str::replace(s, ">", "");
let s = str::replace(s, "[", "");
let s = str::replace(s, "]", "");
let s = str::replace(s, "(", "");
let s = str::replace(s, ")", "");
let s = str::replace(s, "@~", "");
let s = str::replace(s, "~", "");
let s = str::replace(s, "/", "");
let s = str::replace(s, ":", "");
let s = str::replace(s, "&", "");
let s = str::replace(s, "^", "");
let s = str::replace(s, ",", "");
let s = str::replace(s, "'", "");
let s = str::replace(s, "+", "");
let s = s.replace("<", "");
let s = s.replace(">", "");
let s = s.replace("[", "");
let s = s.replace("]", "");
let s = s.replace("(", "");
let s = s.replace(")", "");
let s = s.replace("@~", "");
let s = s.replace("~", "");
let s = s.replace("/", "");
let s = s.replace(":", "");
let s = s.replace("&", "");
let s = s.replace("^", "");
let s = s.replace(",", "");
let s = s.replace("'", "");
let s = s.replace("+", "");
return s;
}
fn replace_with_hyphens(s: &str) -> ~str {
@@ -153,8 +151,8 @@ fn replace_with_hyphens(s: &str) -> ~str {
// XXX: Hacky implementation here that only covers
// one or two spaces.
let s = s.trim();
let s = str::replace(s, " ", "-");
let s = str::replace(s, " ", "-");
let s = s.replace(" ", "-");
let s = s.replace(" ", "-");
return s;
}
// FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
+1 -1
View File
@@ -114,7 +114,7 @@ fn make_title(page: doc::Page) -> ~str {
}
};
let title = markdown_pass::header_text(item);
let title = str::replace(title, "`", "");
let title = title.replace("`", "");
return title;
}
+3 -2
View File
@@ -284,7 +284,7 @@ fn run_cmd(repl: &mut Repl, _in: @io::Reader, _out: @io::Writer,
for args.each |arg| {
let (crate, filename) =
if arg.ends_with(".rs") || arg.ends_with(".rc") {
(arg.substr(0, arg.len() - 3).to_owned(), copy *arg)
(arg.slice_to(arg.len() - 3).to_owned(), copy *arg)
} else {
(copy *arg, arg + ".rs")
};
@@ -342,7 +342,8 @@ pub fn run_line(repl: &mut Repl, in: @io::Reader, out: @io::Writer, line: ~str,
// FIXME #5898: conflicts with Cell.take(), so can't be at the top level
use core::iterator::IteratorUtil;
let full = line.substr(1, line.len() - 1);
// drop the : and the \n (one byte each)
let full = line.slice(1, line.len() - 1);
let split: ~[~str] = full.word_iter().transform(|s| s.to_owned()).collect();
let len = split.len();
+3 -4
View File
@@ -12,7 +12,7 @@
use core::path::Path;
use core::option::Some;
use core::{hash, str};
use core::hash;
use core::rt::io::Writer;
use core::hash::Streaming;
@@ -32,7 +32,7 @@ pub fn normalize(p_: RemotePath) -> LocalPath {
match p.filestem() {
None => LocalPath(p),
Some(st) => {
let replaced = str::replace(st, "-", "_");
let replaced = st.replace("-", "_");
if replaced != st {
LocalPath(p.with_filestem(replaced))
}
@@ -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 {
+1 -1
View File
@@ -183,7 +183,7 @@ pub fn find_crates(&mut self) {
if self.libs.is_empty() && self.mains.is_empty()
&& self.tests.is_empty() && self.benchs.is_empty() {
note(~"Couldn't infer any crates to build.\n\
note("Couldn't infer any crates to build.\n\
Try naming a crate `main.rs`, `lib.rs`, \
`test.rs`, or `bench.rs`.");
cond.raise(copy self.id);
+17
View File
@@ -866,6 +866,23 @@ fn test_expand() {
assert_eq!(m.len(), i);
assert!(!m.is_empty());
}
#[test]
fn test_find_equiv() {
let mut m = HashMap::new();
let (foo, bar, baz) = (1,2,3);
m.insert(~"foo", foo);
m.insert(~"bar", bar);
m.insert(~"baz", baz);
assert_eq!(m.find_equiv(&("foo")), Some(&foo));
assert_eq!(m.find_equiv(&("bar")), Some(&bar));
assert_eq!(m.find_equiv(&("baz")), Some(&baz));
assert_eq!(m.find_equiv(&("qux")), None);
}
}
#[cfg(test)]
+3 -3
View File
@@ -761,7 +761,7 @@ fn each_line(&self, it: &fn(s: &str) -> bool) -> bool {
fn read_lines(&self) -> ~[~str] {
do vec::build |push| {
for self.each_line |line| {
push(str::to_owned(line));
push(line.to_owned());
}
}
}
@@ -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 @@ fn write_char(&self, ch: char) {
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");
+19 -19
View File
@@ -793,27 +793,27 @@ fn test_from_str() {
#[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]
+7 -6
View File
@@ -16,6 +16,7 @@
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)
}
+9 -9
View File
@@ -538,16 +538,16 @@ pub fn test_from_str() {
#[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]
+2 -2
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 @@ fn copy_file_ok() {
};
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)
+6 -7
View File
@@ -515,7 +515,7 @@ fn with_filename(&self, f: &str) -> PosixPath {
fn with_filestem(&self, s: &str) -> PosixPath {
match self.filetype() {
None => self.with_filename(s),
Some(ref t) => self.with_filename(str::to_owned(s) + *t),
Some(ref t) => self.with_filename(s.to_owned() + *t),
}
}
@@ -657,7 +657,7 @@ fn from_str(s: &str) -> WindowsPath {
(None, None) => {
host = None;
device = None;
rest = str::to_owned(s);
rest = s.to_owned();
}
}
@@ -729,7 +729,7 @@ fn with_filename(&self, f: &str) -> WindowsPath {
fn with_filestem(&self, s: &str) -> WindowsPath {
match self.filetype() {
None => self.with_filename(s),
Some(ref t) => self.with_filename(str::to_owned(s) + *t),
Some(ref t) => self.with_filename(s.to_owned() + *t),
}
}
@@ -947,7 +947,6 @@ pub fn extract_drive_prefix(s: &str) -> Option<(~str,~str)> {
mod tests {
use option::{None, Some};
use path::{PosixPath, WindowsPath, windows};
use str;
#[test]
fn test_double_slash_collapsing() {
@@ -984,7 +983,7 @@ fn test_filetype_foo() {
fn test_posix_paths() {
fn t(wp: &PosixPath, s: &str) {
let ss = wp.to_str();
let sss = str::to_owned(s);
let sss = s.to_owned();
if (ss != sss) {
debug!("got %s", ss);
debug!("expected %s", sss);
@@ -1042,7 +1041,7 @@ fn t(wp: &PosixPath, s: &str) {
fn test_normalize() {
fn t(wp: &PosixPath, s: &str) {
let ss = wp.to_str();
let sss = str::to_owned(s);
let sss = s.to_owned();
if (ss != sss) {
debug!("got %s", ss);
debug!("expected %s", sss);
@@ -1105,7 +1104,7 @@ fn test_extract_drive_prefixes() {
fn test_windows_paths() {
fn t(wp: &WindowsPath, s: &str) {
let ss = wp.to_str();
let sss = str::to_owned(s);
let sss = s.to_owned();
if (ss != sss) {
debug!("got %s", ss);
debug!("expected %s", sss);
+1 -1
View File
@@ -64,7 +64,7 @@
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};
+1 -1
View File
@@ -577,7 +577,7 @@ fn weighted_vec<T:Copy>(&mut self, v: &[Weighted<T>]) -> ~[T] {
/// Shuffle a vec
fn shuffle<T:Copy>(&mut self, values: &[T]) -> ~[T] {
let mut m = vec::to_owned(values);
let mut m = values.to_owned();
self.shuffle_mut(m);
m
}
+1 -1
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());
}
+1 -1
View File
@@ -108,7 +108,7 @@ fn smoke_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();
+1 -2
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_with_null_consume());
}
blk.push(0);
vec::as_imm_buf(blk, |p, _len|
+524 -478
View File
@@ -26,7 +26,7 @@
use cmp::{TotalOrd, Ordering, Less, Equal, Greater};
use container::Container;
use iter::Times;
use iterator::{Iterator, IteratorUtil, FilterIterator};
use iterator::{Iterator, IteratorUtil, FilterIterator, AdditiveIterator};
use libc;
use option::{None, Option, Some};
use old_iter::{BaseIter, EqIter};
@@ -107,23 +107,17 @@ pub fn from_bytes_slice<'a>(vector: &'a [u8]) -> &'a str {
}
}
/// Copy a slice into a new unique str
#[inline(always)]
pub fn to_owned(s: &str) -> ~str {
unsafe { raw::slice_bytes_owned(s, 0, s.len()) }
}
impl ToStr for ~str {
#[inline(always)]
fn to_str(&self) -> ~str { to_owned(*self) }
fn to_str(&self) -> ~str { self.to_owned() }
}
impl<'self> ToStr for &'self str {
#[inline(always)]
fn to_str(&self) -> ~str { to_owned(*self) }
fn to_str(&self) -> ~str { self.to_owned() }
}
impl ToStr for @str {
#[inline(always)]
fn to_str(&self) -> ~str { to_owned(*self) }
fn to_str(&self) -> ~str { self.to_owned() }
}
/**
@@ -160,29 +154,19 @@ pub fn push_str(lhs: &mut ~str, rhs: &str) {
lhs.push_str(rhs)
}
/// Concatenate two strings together
#[inline(always)]
pub fn append(lhs: ~str, rhs: &str) -> ~str {
let mut v = lhs;
v.push_str_no_overallocate(rhs);
v
}
#[allow(missing_doc)]
pub trait StrVector {
pub fn concat(&self) -> ~str;
pub fn connect(&self, sep: &str) -> ~str;
}
impl<'self> StrVector for &'self [~str] {
impl<'self, S: Str> StrVector for &'self [S] {
/// Concatenate a vector of strings.
pub fn concat(&self) -> ~str {
if self.is_empty() { return ~""; }
let mut len = 0;
for self.each |ss| {
len += ss.len();
}
let len = self.iter().transform(|s| s.as_slice().len()).sum();
let mut s = ~"";
s.reserve(len);
@@ -190,8 +174,8 @@ pub fn concat(&self) -> ~str {
unsafe {
do as_buf(s) |buf, _| {
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.each |ss| {
do as_buf(*ss) |ssbuf, sslen| {
for self.iter().advance |ss| {
do as_buf(ss.as_slice()) |ssbuf, sslen| {
let sslen = sslen - 1;
ptr::copy_memory(buf, ssbuf, sslen);
buf = buf.offset(sslen);
@@ -211,10 +195,8 @@ pub fn connect(&self, sep: &str) -> ~str {
if sep.is_empty() { return self.concat(); }
// this is wrong without the guarantee that `self` is non-empty
let mut len = sep.len() * (self.len() - 1);
for self.each |ss| {
len += ss.len();
}
let len = sep.len() * (self.len() - 1)
+ self.iter().transform(|s| s.as_slice().len()).sum();
let mut s = ~"";
let mut first = true;
@@ -225,8 +207,8 @@ pub fn connect(&self, sep: &str) -> ~str {
do as_buf(sep) |sepbuf, seplen| {
let seplen = seplen - 1;
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.each |ss| {
do as_buf(*ss) |ssbuf, sslen| {
for self.iter().advance |ss| {
do as_buf(ss.as_slice()) |ssbuf, sslen| {
let sslen = sslen - 1;
if first {
first = false;
@@ -246,192 +228,6 @@ pub fn connect(&self, sep: &str) -> ~str {
}
}
impl<'self> StrVector for &'self [&'self str] {
/// Concatenate a vector of strings.
pub fn concat(&self) -> ~str {
if self.is_empty() { return ~""; }
let mut len = 0;
for self.each |ss| {
len += ss.len();
}
let mut s = ~"";
s.reserve(len);
unsafe {
do as_buf(s) |buf, _| {
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.each |ss| {
do as_buf(*ss) |ssbuf, sslen| {
let sslen = sslen - 1;
ptr::copy_memory(buf, ssbuf, sslen);
buf = buf.offset(sslen);
}
}
}
raw::set_len(&mut s, len);
}
s
}
/// Concatenate a vector of strings, placing a given separator between each.
pub fn connect(&self, sep: &str) -> ~str {
if self.is_empty() { return ~""; }
// concat is faster
if sep.is_empty() { return self.concat(); }
// this is wrong without the guarantee that `self` is non-empty
let mut len = sep.len() * (self.len() - 1);
for self.each |ss| {
len += ss.len();
}
let mut s = ~"";
let mut first = true;
s.reserve(len);
unsafe {
do as_buf(s) |buf, _| {
do as_buf(sep) |sepbuf, seplen| {
let seplen = seplen - 1;
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.each |ss| {
do as_buf(*ss) |ssbuf, sslen| {
let sslen = sslen - 1;
if first {
first = false;
} else {
ptr::copy_memory(buf, sepbuf, seplen);
buf = buf.offset(seplen);
}
ptr::copy_memory(buf, ssbuf, sslen);
buf = buf.offset(sslen);
}
}
}
}
raw::set_len(&mut s, len);
}
s
}
}
/// Given a string, make a new string with repeated copies of it
pub fn repeat(ss: &str, nn: uint) -> ~str {
do as_buf(ss) |buf, len| {
let mut ret = ~"";
// ignore the NULL terminator
let len = len - 1;
ret.reserve(nn * len);
unsafe {
do as_buf(ret) |rbuf, _len| {
let mut rbuf = ::cast::transmute_mut_unsafe(rbuf);
for nn.times {
ptr::copy_memory(rbuf, buf, len);
rbuf = rbuf.offset(len);
}
}
raw::set_len(&mut ret, nn * len);
}
ret
}
}
/*
Section: Adding to and removing from a string
*/
/**
* Remove the final character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
pub fn pop_char(s: &mut ~str) -> char {
let end = s.len();
assert!(end > 0u);
let CharRange {ch, next} = s.char_range_at_reverse(end);
unsafe { raw::set_len(s, next); }
return ch;
}
/**
* Remove the first character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
pub fn shift_char(s: &mut ~str) -> char {
let CharRange {ch, next} = s.char_range_at(0u);
*s = unsafe { raw::slice_bytes_owned(*s, next, s.len()) };
return ch;
}
/**
* Removes the first character from a string slice and returns it. This does
* not allocate a new string; instead, it mutates a slice to point one
* character beyond the character that was shifted.
*
* # Failure
*
* If the string does not contain any characters
*/
#[inline]
pub fn slice_shift_char<'a>(s: &'a str) -> (char, &'a str) {
let CharRange {ch, next} = s.char_range_at(0u);
let next_s = unsafe { raw::slice_bytes(s, next, s.len()) };
return (ch, next_s);
}
/// Prepend a char to a string
pub fn unshift_char(s: &mut ~str, ch: char) {
// This could be more efficient.
let mut new_str = ~"";
new_str.push_char(ch);
new_str.push_str(*s);
*s = new_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(to_owned(s));
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
@@ -459,6 +255,17 @@ fn matches(&self, c: char) -> bool { (*self)(c) }
fn only_ascii(&self) -> bool { false }
}
impl<'self, C: CharEq> CharEq for &'self [C] {
#[inline(always)]
fn matches(&self, c: char) -> bool {
self.iter().any_(|m| m.matches(c))
}
fn only_ascii(&self) -> bool {
self.iter().all(|m| m.only_ascii())
}
}
/// An iterator over the substrings of a string, separated by `sep`.
pub struct StrCharSplitIterator<'self,Sep> {
@@ -709,30 +516,6 @@ enum LengthLimit {
return cont;
}
/**
* Replace all occurrences of one string with another
*
* # Arguments
*
* * s - The string containing substrings to replace
* * from - The string to replace
* * to - The replacement string
*
* # Return value
*
* The original string with all occurances of `from` replaced with `to`
*/
pub fn replace(s: &str, from: &str, to: &str) -> ~str {
let mut (result, last_end) = (~"", 0);
for s.matches_index_iter(from).advance |(start, end)| {
result.push_str(unsafe{raw::slice_bytes(s, last_end, start)});
result.push_str(to);
last_end = end;
}
result.push_str(unsafe{raw::slice_bytes(s, last_end, s.len())});
result
}
/*
Section: Comparing strings
*/
@@ -976,15 +759,6 @@ fn match_at<'a,'b>(haystack: &'a str, needle: &'b str, at: uint) -> bool {
return true;
}
/*
Section: String properties
*/
/// Returns the number of characters that a string holds
#[inline(always)]
pub fn char_len(s: &str) -> uint { count_chars(s, 0u, s.len()) }
/*
Section: Misc
*/
@@ -1102,46 +876,6 @@ pub fn with_capacity(capacity: uint) -> ~str {
buf
}
/**
* As char_len but for a slice of a string
*
* # Arguments
*
* * s - A valid string
* * start - The position inside `s` where to start counting in bytes
* * end - The position where to stop counting
*
* # Return value
*
* The number of Unicode characters in `s` between the given indices.
*/
pub fn count_chars(s: &str, start: uint, end: uint) -> uint {
assert!(s.is_char_boundary(start));
assert!(s.is_char_boundary(end));
let mut (i, len) = (start, 0u);
while i < end {
let next = s.char_range_at(i).next;
len += 1u;
i = next;
}
return len;
}
/// Counts the number of bytes taken by the first `n` chars in `s`
/// starting from `start`.
pub fn count_bytes<'b>(s: &'b str, start: uint, n: uint) -> uint {
assert!(s.is_char_boundary(start));
let mut (end, cnt) = (start, n);
let l = s.len();
while cnt > 0u {
assert!(end < l);
let next = s.char_range_at(end).next;
cnt -= 1u;
end = next;
}
end - start
}
/// Given a first byte, determine how many bytes are in this UTF-8 character
pub fn utf8_char_width(b: u8) -> uint {
let byte: uint = b as uint;
@@ -1175,39 +909,6 @@ pub struct CharRange {
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.
*/
@@ -1237,7 +938,7 @@ fn as_c_str<T>(self, f: &fn(*libc::c_char) -> T) -> T {
// NB: len includes the trailing null.
assert!(len > 0);
if unsafe { *(ptr::offset(buf,len-1)) != 0 } {
to_owned(self).as_c_str(f)
self.to_owned().as_c_str(f)
} else {
f(buf as *libc::c_char)
}
@@ -1304,39 +1005,6 @@ pub fn subslice_offset(outer: &str, inner: &str) -> uint {
}
}
/**
* Returns the number of single-byte characters the string can hold without
* reallocating
*/
pub fn capacity(s: &const ~str) -> uint {
do as_bytes(s) |buf| {
let vcap = vec::capacity(buf);
assert!(vcap > 0u);
vcap - 1u
}
}
/// Escape each char in `s` with char::escape_default.
pub fn escape_default(s: &str) -> ~str {
let mut out: ~str = ~"";
out.reserve_at_least(s.len());
for s.iter().advance |c| {
out.push_str(char::escape_default(c));
}
out
}
/// Escape each char in `s` with char::escape_unicode.
pub fn escape_unicode(s: &str) -> ~str {
let mut out: ~str = ~"";
out.reserve_at_least(s.len());
for s.iter().advance |c| {
out.push_str(char::escape_unicode(c));
}
out
}
/// Unsafe operations
pub mod raw {
use cast;
@@ -1521,12 +1189,12 @@ fn test_from_buf_len() {
#[cfg(not(test))]
pub mod traits {
use ops::Add;
use str::append;
impl<'self> Add<&'self str,~str> for ~str {
#[inline(always)]
fn add(&self, rhs: & &'self str) -> ~str {
append(copy *self, (*rhs))
let mut s = self.to_owned();
s.push_str(*rhs);
s
}
}
}
@@ -1534,6 +1202,29 @@ fn add(&self, rhs: & &'self str) -> ~str {
#[cfg(test)]
pub mod traits {}
/// Any string that can be represented as a slice
pub trait Str {
/// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a str;
}
impl<'self> Str for &'self str {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a str { *self }
}
impl<'self> Str for ~str {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a str {
let s: &'a str = *self; s
}
}
impl<'self> Str for @str {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a str {
let s: &'a str = *self; s
}
}
#[allow(missing_doc)]
pub trait StrSlice<'self> {
fn contains<'a>(&self, needle: &'a str) -> bool;
@@ -1556,19 +1247,23 @@ fn split_options_iter<Sep: CharEq>(&self, sep: Sep, count: uint, allow_trailing_
fn is_alphanumeric(&self) -> bool;
fn len(&self) -> uint;
fn char_len(&self) -> uint;
fn slice(&self, begin: uint, end: uint) -> &'self str;
fn slice_from(&self, begin: uint) -> &'self str;
fn slice_to(&self, end: uint) -> &'self str;
fn slice_chars(&self, begin: uint, end: uint) -> &'self str;
fn starts_with(&self, needle: &str) -> bool;
fn substr(&self, begin: uint, n: uint) -> &'self str;
fn escape_default(&self) -> ~str;
fn escape_unicode(&self) -> ~str;
fn trim(&self) -> &'self str;
fn trim_left(&self) -> &'self str;
fn trim_right(&self) -> &'self str;
fn trim_chars(&self, chars_to_trim: &[char]) -> &'self str;
fn trim_left_chars(&self, chars_to_trim: &[char]) -> &'self str;
fn trim_right_chars(&self, chars_to_trim: &[char]) -> &'self str;
fn trim_chars<C: CharEq>(&self, to_trim: &C) -> &'self str;
fn trim_left_chars<C: CharEq>(&self, to_trim: &C) -> &'self str;
fn trim_right_chars<C: CharEq>(&self, to_trim: &C) -> &'self str;
fn replace(&self, from: &str, to: &str) -> ~str;
fn to_owned(&self) -> ~str;
fn to_managed(&self) -> @str;
fn is_char_boundary(&self, index: uint) -> bool;
@@ -1576,11 +1271,15 @@ fn split_options_iter<Sep: CharEq>(&self, sep: Sep, count: uint, allow_trailing_
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>;
fn find_str(&self, &str) -> Option<uint>;
fn repeat(&self, nn: uint) -> ~str;
fn slice_shift_char(&self) -> (char, &'self str);
}
/// Extension methods for strings
@@ -1635,12 +1334,12 @@ fn rev_iter(&self) -> StrCharRevIterator<'self> {
/// 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
@@ -1753,7 +1452,8 @@ fn len(&self) -> uint {
}
/// Returns the number of characters that a string holds
#[inline]
fn char_len(&self) -> uint { char_len(*self) }
fn char_len(&self) -> uint { self.iter().count() }
/**
* Returns a slice of the given string from the byte range
* [`begin`..`end`)
@@ -1784,6 +1484,32 @@ fn slice_from(&self, begin: uint) -> &'self str {
fn slice_to(&self, end: uint) -> &'self str {
self.slice(0, end)
}
/// Returns a slice of the string from the char range
/// [`begin`..`end`).
///
/// Fails if `begin` > `end` or the either `begin` or `end` are
/// beyond the last character of the string.
fn slice_chars(&self, begin: uint, end: uint) -> &'self str {
assert!(begin <= end);
// not sure how to use the iterators for this nicely.
let mut (position, count) = (0, 0);
let l = self.len();
while count < begin && position < l {
position = self.char_range_at(position).next;
count += 1;
}
if count < begin { fail!("Attempted to begin slice_chars beyond end of string") }
let start_byte = position;
while count < end && position < l {
position = self.char_range_at(position).next;
count += 1;
}
if count < end { fail!("Attempted to end slice_chars beyond end of string") }
self.slice(start_byte, position)
}
/// Returns true if `needle` is a prefix of the string.
fn starts_with<'a>(&self, needle: &'a str) -> bool {
let (self_len, needle_len) = (self.len(), needle.len());
@@ -1792,29 +1518,32 @@ fn starts_with<'a>(&self, needle: &'a str) -> bool {
else { match_at(*self, needle, 0u) }
}
/// Returns true if `needle` is a suffix of the string.
pub fn ends_with(&self, needle: &str) -> bool {
fn ends_with(&self, needle: &str) -> bool {
let (self_len, needle_len) = (self.len(), needle.len());
if needle_len == 0u { true }
else if needle_len > self_len { false }
else { match_at(*self, needle, self_len - needle_len) }
}
/**
* Take a substring of another.
*
* Returns a string containing `n` characters starting at byte offset
* `begin`.
*/
#[inline]
fn substr(&self, begin: uint, n: uint) -> &'self str {
self.slice(begin, begin + count_bytes(*self, begin, n))
}
/// Escape each char in `s` with char::escape_default.
#[inline]
fn escape_default(&self) -> ~str { escape_default(*self) }
fn escape_default(&self) -> ~str {
let mut out: ~str = ~"";
out.reserve_at_least(self.len());
for self.iter().advance |c| {
out.push_str(char::escape_default(c));
}
out
}
/// Escape each char in `s` with char::escape_unicode.
#[inline]
fn escape_unicode(&self) -> ~str { escape_unicode(*self) }
fn escape_unicode(&self) -> ~str {
let mut out: ~str = ~"";
out.reserve_at_least(self.len());
for self.iter().advance |c| {
out.push_str(char::escape_unicode(c));
}
out
}
/// Returns a string with leading and trailing whitespace removed
#[inline]
@@ -1824,49 +1553,51 @@ fn trim(&self) -> &'self str {
/// Returns a string with leading whitespace removed
#[inline]
fn trim_left(&self) -> &'self str {
match self.find(|c| !char::is_whitespace(c)) {
None => "",
Some(first) => unsafe { raw::slice_bytes(*self, first, self.len()) }
}
self.trim_left_chars(&char::is_whitespace)
}
/// Returns a string with trailing whitespace removed
#[inline]
fn trim_right(&self) -> &'self str {
match self.rfind(|c| !char::is_whitespace(c)) {
None => "",
Some(last) => {
let next = self.char_range_at(last).next;
unsafe { raw::slice_bytes(*self, 0u, next) }
}
}
self.trim_right_chars(&char::is_whitespace)
}
/**
* Returns a string with leading and trailing `chars_to_trim` removed.
* Returns a string with characters that match `to_trim` removed.
*
* # Arguments
*
* * chars_to_trim - A vector of chars
* * to_trim - a character matcher
*
* # Example
*
* ~~~
* assert_eq!("11foo1bar11".trim_chars(&'1'), "foo1bar")
* assert_eq!("12foo1bar12".trim_chars(& &['1', '2']), "foo1bar")
* assert_eq!("123foo1bar123".trim_chars(&|c: char| c.is_digit()), "foo1bar")
* ~~~
*/
#[inline]
fn trim_chars(&self, chars_to_trim: &[char]) -> &'self str {
self.trim_left_chars(chars_to_trim).trim_right_chars(chars_to_trim)
fn trim_chars<C: CharEq>(&self, to_trim: &C) -> &'self str {
self.trim_left_chars(to_trim).trim_right_chars(to_trim)
}
/**
* Returns a string with leading `chars_to_trim` removed.
*
* # Arguments
*
* * s - A string
* * chars_to_trim - A vector of chars
* * to_trim - a character matcher
*
* # Example
*
* ~~~
* assert_eq!("11foo1bar11".trim_left_chars(&'1'), "foo1bar11")
* assert_eq!("12foo1bar12".trim_left_chars(& &['1', '2']), "foo1bar12")
* assert_eq!("123foo1bar123".trim_left_chars(&|c: char| c.is_digit()), "foo1bar123")
* ~~~
*/
#[inline]
fn trim_left_chars(&self, chars_to_trim: &[char]) -> &'self str {
if chars_to_trim.is_empty() { return *self; }
match self.find(|c| !chars_to_trim.contains(&c)) {
fn trim_left_chars<C: CharEq>(&self, to_trim: &C) -> &'self str {
match self.find(|c: char| !to_trim.matches(c)) {
None => "",
Some(first) => unsafe { raw::slice_bytes(*self, first, self.len()) }
}
@@ -1876,15 +1607,19 @@ fn trim_left_chars(&self, chars_to_trim: &[char]) -> &'self str {
*
* # Arguments
*
* * s - A string
* * chars_to_trim - A vector of chars
* * to_trim - a character matcher
*
* # Example
*
* ~~~
* assert_eq!("11foo1bar11".trim_right_chars(&'1'), "11foo1bar")
* assert_eq!("12foo1bar12".trim_right_chars(& &['1', '2']), "12foo1bar")
* assert_eq!("123foo1bar123".trim_right_chars(&|c: char| c.is_digit()), "123foo1bar")
* ~~~
*/
#[inline]
fn trim_right_chars(&self, chars_to_trim: &[char]) -> &'self str {
if chars_to_trim.is_empty() { return *self; }
match self.rfind(|c| !chars_to_trim.contains(&c)) {
fn trim_right_chars<C: CharEq>(&self, to_trim: &C) -> &'self str {
match self.rfind(|c: char| !to_trim.matches(c)) {
None => "",
Some(last) => {
let next = self.char_range_at(last).next;
@@ -1893,10 +1628,36 @@ fn trim_right_chars(&self, chars_to_trim: &[char]) -> &'self str {
}
}
/**
* Replace all occurrences of one string with another
*
* # Arguments
*
* * from - The string to replace
* * to - The replacement string
*
* # Return value
*
* The original string with all occurances of `from` replaced with `to`
*/
pub fn replace(&self, from: &str, to: &str) -> ~str {
let mut (result, last_end) = (~"", 0);
for self.matches_index_iter(from).advance |(start, end)| {
result.push_str(unsafe{raw::slice_bytes(*self, last_end, start)});
result.push_str(to);
last_end = end;
}
result.push_str(unsafe{raw::slice_bytes(*self, last_end, self.len())});
result
}
/// Copy a slice into a new unique str
#[inline]
fn to_owned(&self) -> ~str { to_owned(*self) }
fn to_owned(&self) -> ~str {
unsafe { raw::slice_bytes_owned(*self, 0, self.len()) }
}
/// Copy a slice into a new @str
#[inline]
fn to_managed(&self) -> @str {
let v = at_vec::from_fn(self.len() + 1, |i| {
@@ -2023,7 +1784,18 @@ fn char_at_reverse(&self, i: uint) -> char {
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`
@@ -2094,6 +1866,92 @@ fn find_str(&self, needle: &str) -> Option<uint> {
.map_consume(|(start, _end)| start)
}
}
/// Given a string, make a new string with repeated copies of it.
fn repeat(&self, nn: uint) -> ~str {
do as_buf(*self) |buf, len| {
let mut ret = ~"";
// ignore the NULL terminator
let len = len - 1;
ret.reserve(nn * len);
unsafe {
do as_buf(ret) |rbuf, _len| {
let mut rbuf = ::cast::transmute_mut_unsafe(rbuf);
for nn.times {
ptr::copy_memory(rbuf, buf, len);
rbuf = rbuf.offset(len);
}
}
raw::set_len(&mut ret, nn * len);
}
ret
}
}
/**
* Retrieves the first character from a string slice and returns
* it. This does not allocate a new string; instead, it returns a
* slice that point one character beyond the character that was
* shifted.
*
* # Failure
*
* If the string does not contain any characters
*/
#[inline]
fn slice_shift_char(&self) -> (char, &'self str) {
let CharRange {ch, next} = self.char_range_at(0u);
let next_s = unsafe { raw::slice_bytes(*self, next, self.len()) };
return (ch, next_s);
}
}
#[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)]
@@ -2101,8 +1959,15 @@ pub trait OwnedStr {
fn push_str_no_overallocate(&mut self, rhs: &str);
fn push_str(&mut self, rhs: &str);
fn push_char(&mut self, c: char);
fn pop_char(&mut self) -> char;
fn shift_char(&mut self) -> char;
fn unshift_char(&mut self, ch: char);
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 capacity(&self) -> uint;
fn as_bytes_with_null_consume(self) -> ~[u8];
}
impl OwnedStr for ~str {
@@ -2198,6 +2063,51 @@ fn push_char(&mut self, c: char) {
raw::set_len(self, new_len);
}
}
/**
* Remove the final character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
fn pop_char(&mut self) -> char {
let end = self.len();
assert!(end > 0u);
let CharRange {ch, next} = self.char_range_at_reverse(end);
unsafe { raw::set_len(self, next); }
return ch;
}
/**
* Remove the first character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
fn shift_char(&mut self) -> char {
let CharRange {ch, next} = self.char_range_at(0u);
*self = unsafe { raw::slice_bytes_owned(*self, next, self.len()) };
return ch;
}
/// Prepend a char to a string
fn unshift_char(&mut self, ch: char) {
// This could be more efficient.
let mut new_str = ~"";
new_str.push_char(ch);
new_str.push_str(*self);
*self = new_str;
}
/// Concatenate two strings together.
#[inline]
fn append(&self, rhs: &str) -> ~str {
// FIXME #4850: this should consume self, but that causes segfaults
let mut v = self.clone();
v.push_str_no_overallocate(rhs);
v
}
/**
* Reserves capacity for exactly `n` bytes in the given string, not including
@@ -2247,12 +2157,30 @@ pub fn reserve(&mut self, n: uint) {
fn reserve_at_least(&mut self, n: uint) {
self.reserve(uint::next_power_of_two(n + 1u) - 1u)
}
/**
* Returns the number of single-byte characters the string can hold without
* reallocating
*/
fn capacity(&self) -> uint {
let buf: &const ~[u8] = unsafe { cast::transmute(self) };
let vcap = vec::capacity(buf);
assert!(vcap > 0u);
vcap - 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 {
#[inline(always)]
fn clone(&self) -> ~str {
to_owned(*self)
self.to_owned()
}
}
@@ -2332,7 +2260,7 @@ mod tests {
use ptr;
use str::*;
use vec;
use vec::ImmutableVector;
use vec::{ImmutableVector, CopyableVector};
use cmp::{TotalOrd, Less, Equal, Greater};
#[test]
@@ -2367,14 +2295,14 @@ fn test_len() {
assert_eq!("\u2620".len(), 3u);
assert_eq!("\U0001d11e".len(), 4u);
assert_eq!(char_len(""), 0u);
assert_eq!(char_len("hello world"), 11u);
assert_eq!(char_len("\x63"), 1u);
assert_eq!(char_len("\xa2"), 1u);
assert_eq!(char_len("\u03c0"), 1u);
assert_eq!(char_len("\u2620"), 1u);
assert_eq!(char_len("\U0001d11e"), 1u);
assert_eq!(char_len("ประเทศไทย中华Việt Nam"), 19u);
assert_eq!("".char_len(), 0u);
assert_eq!("hello world".char_len(), 11u);
assert_eq!("\x63".char_len(), 1u);
assert_eq!("\xa2".char_len(), 1u);
assert_eq!("\u03c0".char_len(), 1u);
assert_eq!("\u2620".char_len(), 1u);
assert_eq!("\U0001d11e".char_len(), 1u);
assert_eq!("ประเทศไทย中华Việt Nam".char_len(), 19u);
}
#[test]
@@ -2397,10 +2325,31 @@ fn test_rfind() {
assert_eq!("ประเทศไทย中华Việt Nam".rfind(|c: char| c == '华'), Some(30u));
}
#[test]
fn test_push_str() {
let mut s = ~"";
s.push_str("");
assert_eq!(s.slice_from(0), "");
s.push_str("abc");
assert_eq!(s.slice_from(0), "abc");
s.push_str("ประเทศไทย中华Việt Nam");
assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
}
#[test]
fn test_append() {
let mut s = ~"";
s = s.append("");
assert_eq!(s.slice_from(0), "");
s = s.append("abc");
assert_eq!(s.slice_from(0), "abc");
s = s.append("ประเทศไทย中华Việt Nam");
assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
}
#[test]
fn test_pop_char() {
let mut data = ~"ประเทศไทย中华";
let cc = pop_char(&mut data);
let cc = data.pop_char();
assert_eq!(~"ประเทศไทย中", data);
assert_eq!('华', cc);
}
@@ -2408,7 +2357,7 @@ fn test_pop_char() {
#[test]
fn test_pop_char_2() {
let mut data2 = ~"";
let cc2 = pop_char(&mut data2);
let cc2 = data2.pop_char();
assert_eq!(~"", data2);
assert_eq!('华', cc2);
}
@@ -2418,7 +2367,29 @@ fn test_pop_char_2() {
#[ignore(cfg(windows))]
fn test_pop_char_fail() {
let mut data = ~"";
let _cc3 = pop_char(&mut data);
let _cc3 = data.pop_char();
}
#[test]
fn test_push_char() {
let mut data = ~"ประเทศไทย中";
data.push_char('华');
assert_eq!(~"ประเทศไทย中华", data);
}
#[test]
fn test_shift_char() {
let mut data = ~"ประเทศไทย中";
let cc = data.shift_char();
assert_eq!(~"ระเทศไทย中", data);
assert_eq!('ป', cc);
}
#[test]
fn test_unshift_char() {
let mut data = ~"ประเทศไทย中";
data.unshift_char('华');
assert_eq!(~"华ประเทศไทย中", data);
}
#[test]
@@ -2466,13 +2437,13 @@ fn test_find_str() {
}
#[test]
fn test_substr() {
fn t(a: &str, b: &str, start: int) {
assert_eq!(a.substr(start as uint, b.len()), b);
fn test_slice_chars() {
fn t(a: &str, b: &str, start: uint) {
assert_eq!(a.slice_chars(start, start + b.char_len()), b);
}
t("hello", "llo", 2);
t("hello", "el", 1);
assert_eq!("ะเทศไท", "ประเทศไทย中华Việt Nam".substr(6u, 6u));
assert_eq!("ะเทศไท", "ประเทศไทย中华Việt Nam".slice_chars(2, 8));
}
#[test]
@@ -2522,11 +2493,11 @@ fn t(v: &[&str], sep: &str, s: &str) {
#[test]
fn test_repeat() {
assert_eq!(repeat("x", 4), ~"xxxx");
assert_eq!(repeat("hi", 4), ~"hihihihi");
assert_eq!(repeat("ไท华", 3), ~"ไท华ไท华ไท华");
assert_eq!(repeat("", 4), ~"");
assert_eq!(repeat("hi", 0), ~"");
assert_eq!("x".repeat(4), ~"xxxx");
assert_eq!("hi".repeat(4), ~"hihihihi");
assert_eq!("ไท华".repeat(3), ~"ไท华ไท华ไท华");
assert_eq!("".repeat(4), ~"");
assert_eq!("hi".repeat(0), ~"");
}
#[test]
@@ -2578,13 +2549,13 @@ fn test_is_empty() {
#[test]
fn test_replace() {
let a = "a";
assert_eq!(replace("", a, "b"), ~"");
assert_eq!(replace("a", a, "b"), ~"b");
assert_eq!(replace("ab", a, "b"), ~"bb");
assert_eq!("".replace(a, "b"), ~"");
assert_eq!("a".replace(a, "b"), ~"b");
assert_eq!("ab".replace(a, "b"), ~"bb");
let test = "test";
assert!(replace(" test test ", test, "toast") ==
assert!(" test test ".replace(test, "toast") ==
~" toast toast ");
assert_eq!(replace(" test test ", test, ""), ~" ");
assert_eq!(" test test ".replace(test, ""), ~" ");
}
#[test]
@@ -2594,7 +2565,7 @@ fn test_replace_2a() {
let a = ~"ประเ";
let A = ~"دولة الكويتทศไทย中华";
assert_eq!(replace(data, a, repl), A);
assert_eq!(data.replace(a, repl), A);
}
#[test]
@@ -2604,7 +2575,7 @@ fn test_replace_2b() {
let b = ~"ะเ";
let B = ~"ปรدولة الكويتทศไทย中华";
assert_eq!(replace(data, b, repl), B);
assert_eq!(data.replace(b, repl), B);
}
#[test]
@@ -2614,7 +2585,7 @@ fn test_replace_2c() {
let c = ~"中华";
let C = ~"ประเทศไทยدولة الكويت";
assert_eq!(replace(data, c, repl), C);
assert_eq!(data.replace(c, repl), C);
}
#[test]
@@ -2623,7 +2594,7 @@ fn test_replace_2d() {
let repl = ~"دولة الكويت";
let d = ~"ไท华";
assert_eq!(replace(data, d, repl), data);
assert_eq!(data.replace(d, repl), data);
}
#[test]
@@ -2707,26 +2678,41 @@ fn test_slice_to() {
#[test]
fn test_trim_left_chars() {
assert_eq!(" *** foo *** ".trim_left_chars([]), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_left_chars(['*', ' ']), "foo *** ");
assert_eq!(" *** *** ".trim_left_chars(['*', ' ']), "");
assert_eq!("foo *** ".trim_left_chars(['*', ' ']), "foo *** ");
let v: &[char] = &[];
assert_eq!(" *** foo *** ".trim_left_chars(&v), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_left_chars(& &['*', ' ']), "foo *** ");
assert_eq!(" *** *** ".trim_left_chars(& &['*', ' ']), "");
assert_eq!("foo *** ".trim_left_chars(& &['*', ' ']), "foo *** ");
assert_eq!("11foo1bar11".trim_left_chars(&'1'), "foo1bar11");
assert_eq!("12foo1bar12".trim_left_chars(& &['1', '2']), "foo1bar12");
assert_eq!("123foo1bar123".trim_left_chars(&|c: char| c.is_digit()), "foo1bar123");
}
#[test]
fn test_trim_right_chars() {
assert_eq!(" *** foo *** ".trim_right_chars([]), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_right_chars(['*', ' ']), " *** foo");
assert_eq!(" *** *** ".trim_right_chars(['*', ' ']), "");
assert_eq!(" *** foo".trim_right_chars(['*', ' ']), " *** foo");
let v: &[char] = &[];
assert_eq!(" *** foo *** ".trim_right_chars(&v), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_right_chars(& &['*', ' ']), " *** foo");
assert_eq!(" *** *** ".trim_right_chars(& &['*', ' ']), "");
assert_eq!(" *** foo".trim_right_chars(& &['*', ' ']), " *** foo");
assert_eq!("11foo1bar11".trim_right_chars(&'1'), "11foo1bar");
assert_eq!("12foo1bar12".trim_right_chars(& &['1', '2']), "12foo1bar");
assert_eq!("123foo1bar123".trim_right_chars(&|c: char| c.is_digit()), "123foo1bar");
}
#[test]
fn test_trim_chars() {
assert_eq!(" *** foo *** ".trim_chars([]), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_chars(['*', ' ']), "foo");
assert_eq!(" *** *** ".trim_chars(['*', ' ']), "");
assert_eq!("foo".trim_chars(['*', ' ']), "foo");
let v: &[char] = &[];
assert_eq!(" *** foo *** ".trim_chars(&v), " *** foo *** ");
assert_eq!(" *** foo *** ".trim_chars(& &['*', ' ']), "foo");
assert_eq!(" *** *** ".trim_chars(& &['*', ' ']), "");
assert_eq!("foo".trim_chars(& &['*', ' ']), "foo");
assert_eq!("11foo1bar11".trim_chars(&'1'), "foo1bar");
assert_eq!("12foo1bar12".trim_chars(& &['1', '2']), "foo1bar");
assert_eq!("123foo1bar123".trim_chars(&|c: char| c.is_digit()), "foo1bar");
}
#[test]
@@ -2905,12 +2891,70 @@ fn test_from_buf() {
}
}
#[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]
@@ -2985,7 +3029,7 @@ fn test_subslice_offset_2() {
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();
@@ -3104,30 +3148,27 @@ fn test_char_at_reverse() {
#[test]
fn test_escape_unicode() {
assert_eq!(escape_unicode("abc"), ~"\\x61\\x62\\x63");
assert_eq!(escape_unicode("a c"), ~"\\x61\\x20\\x63");
assert_eq!(escape_unicode("\r\n\t"), ~"\\x0d\\x0a\\x09");
assert_eq!(escape_unicode("'\"\\"), ~"\\x27\\x22\\x5c");
assert!(escape_unicode("\x00\x01\xfe\xff") ==
~"\\x00\\x01\\xfe\\xff");
assert_eq!(escape_unicode("\u0100\uffff"), ~"\\u0100\\uffff");
assert!(escape_unicode("\U00010000\U0010ffff") ==
~"\\U00010000\\U0010ffff");
assert_eq!(escape_unicode("ab\ufb00"), ~"\\x61\\x62\\ufb00");
assert_eq!(escape_unicode("\U0001d4ea\r"), ~"\\U0001d4ea\\x0d");
assert_eq!("abc".escape_unicode(), ~"\\x61\\x62\\x63");
assert_eq!("a c".escape_unicode(), ~"\\x61\\x20\\x63");
assert_eq!("\r\n\t".escape_unicode(), ~"\\x0d\\x0a\\x09");
assert_eq!("'\"\\".escape_unicode(), ~"\\x27\\x22\\x5c");
assert_eq!("\x00\x01\xfe\xff".escape_unicode(), ~"\\x00\\x01\\xfe\\xff");
assert_eq!("\u0100\uffff".escape_unicode(), ~"\\u0100\\uffff");
assert_eq!("\U00010000\U0010ffff".escape_unicode(), ~"\\U00010000\\U0010ffff");
assert_eq!("ab\ufb00".escape_unicode(), ~"\\x61\\x62\\ufb00");
assert_eq!("\U0001d4ea\r".escape_unicode(), ~"\\U0001d4ea\\x0d");
}
#[test]
fn test_escape_default() {
assert_eq!(escape_default("abc"), ~"abc");
assert_eq!(escape_default("a c"), ~"a c");
assert_eq!(escape_default("\r\n\t"), ~"\\r\\n\\t");
assert_eq!(escape_default("'\"\\"), ~"\\'\\\"\\\\");
assert_eq!(escape_default("\u0100\uffff"), ~"\\u0100\\uffff");
assert!(escape_default("\U00010000\U0010ffff") ==
~"\\U00010000\\U0010ffff");
assert_eq!(escape_default("ab\ufb00"), ~"ab\\ufb00");
assert_eq!(escape_default("\U0001d4ea\r"), ~"\\U0001d4ea\\r");
assert_eq!("abc".escape_default(), ~"abc");
assert_eq!("a c".escape_default(), ~"a c");
assert_eq!("\r\n\t".escape_default(), ~"\\r\\n\\t");
assert_eq!("'\"\\".escape_default(), ~"\\'\\\"\\\\");
assert_eq!("\u0100\uffff".escape_default(), ~"\\u0100\\uffff");
assert_eq!("\U00010000\U0010ffff".escape_default(), ~"\\U00010000\\U0010ffff");
assert_eq!("ab\ufb00".escape_default(), ~"ab\\ufb00");
assert_eq!("\U0001d4ea\r".escape_default(), ~"\\U0001d4ea\\r");
}
#[test]
@@ -3135,6 +3176,11 @@ fn test_to_managed() {
assert_eq!("abc".to_managed(), @"abc");
assert_eq!("abcdef".slice(1, 5).to_managed(), @"bcde");
}
#[test]
fn test_to_owned() {
assert_eq!("abc".to_owned(), ~"abc");
assert_eq!("abcdef".slice(1, 5).to_owned(), ~"bcde");
}
#[test]
fn test_total_ord() {
+8 -10
View File
@@ -18,7 +18,7 @@
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 @@ fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
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())
}
}
+4 -4
View File
@@ -325,7 +325,7 @@ pub fn parse_type(s: &str, i: uint, lim: uint, err: ErrorFn) ->
'o' => TyOctal,
'f' => TyFloat,
'?' => TyPoly,
_ => err(~"unknown type in conversion: " + s.substr(i, 1))
_ => err(fmt!("unknown type in conversion: %c", s.char_at(i)))
};
Parsed::new(t, i + 1)
@@ -546,7 +546,7 @@ pub fn conv_str(cv: Conv, s: &str, buf: &mut ~str) {
// displayed
let unpadded = match cv.precision {
CountImplied => s,
CountIs(max) => if (max as uint) < str::char_len(s) {
CountIs(max) => if (max as uint) < s.char_len() {
s.slice(0, max as uint)
} else {
s
@@ -584,7 +584,7 @@ pub fn uint_to_str_prec(num: uint, radix: uint, prec: uint) -> ~str {
~""
} else {
let s = uint::to_str_radix(num, radix);
let len = str::char_len(s);
let len = s.char_len();
if len < prec {
let diff = prec - len;
let pad = str::from_chars(vec::from_elem(diff, '0'));
@@ -614,7 +614,7 @@ pub fn pad(cv: Conv, s: &str, head: Option<char>, mode: PadMode,
}
CountIs(width) => { width as uint }
};
let strlen = str::char_len(s) + headsize;
let strlen = s.char_len() + headsize;
if uwidth <= strlen {
for head.iter().advance |&c| {
buf.push_char(c);
+5 -11
View File
@@ -171,11 +171,6 @@ pub fn from_elem<T:Copy>(n_elts: uint, t: T) -> ~[T] {
}
}
/// Creates a new unique vector with the same contents as the slice
pub fn to_owned<T:Copy>(t: &[T]) -> ~[T] {
from_fn(t.len(), |i| t[i])
}
/// Creates a new vector with a capacity of `capacity`
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
let mut vec = ~[];
@@ -1787,7 +1782,7 @@ pub trait CopyableVector<T> {
/// Extension methods for vectors
impl<'self,T:Copy> CopyableVector<T> for &'self [T] {
/// Returns a copy of `v`.
/// Creates a new unique vector with the same contents as the slice
#[inline]
fn to_owned(&self) -> ~[T] {
let mut result = ~[];
@@ -1796,7 +1791,6 @@ fn to_owned(&self) -> ~[T] {
result.push(copy *e);
}
result
}
}
@@ -3361,19 +3355,19 @@ fn test_each_permutation() {
let mut results: ~[~[int]];
results = ~[];
for each_permutation([]) |v| { results.push(to_owned(v)); }
for each_permutation([]) |v| { results.push(v.to_owned()); }
assert_eq!(results, ~[~[]]);
results = ~[];
for each_permutation([7]) |v| { results.push(to_owned(v)); }
for each_permutation([7]) |v| { results.push(v.to_owned()); }
assert_eq!(results, ~[~[7]]);
results = ~[];
for each_permutation([1,1]) |v| { results.push(to_owned(v)); }
for each_permutation([1,1]) |v| { results.push(v.to_owned()); }
assert_eq!(results, ~[~[1,1],~[1,1]]);
results = ~[];
for each_permutation([5,2,0]) |v| { results.push(to_owned(v)); }
for each_permutation([5,2,0]) |v| { results.push(v.to_owned()); }
assert!(results ==
~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]);
}
+1 -1
View File
@@ -259,7 +259,7 @@ pub fn last_meta_item_list_by_name(items: ~[@ast::meta_item], name: &str)
pub fn sort_meta_items(items: &[@ast::meta_item]) -> ~[@ast::meta_item] {
// This is sort of stupid here, converting to a vec of mutables and back
let mut v = vec::to_owned(items);
let mut v = items.to_owned();
do extra::sort::quick_sort(v) |ma, mb| {
get_meta_item_name(*ma) <= get_meta_item_name(*mb)
}
+1 -3
View File
@@ -21,8 +21,6 @@
use parse;
use parse::token;
use core::vec;
enum State {
Asm,
Outputs,
@@ -45,7 +43,7 @@ pub fn expand_asm(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let p = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(),
vec::to_owned(tts));
tts.to_owned());
let mut asm = ~"";
let mut outputs = ~[];
+1 -2
View File
@@ -22,7 +22,6 @@
use parse::token::{ident_to_str, intern, str_to_ident};
use core::hashmap::HashMap;
use core::vec;
// new-style macro! tt code:
//
@@ -367,7 +366,7 @@ pub fn get_exprs_from_tts(cx: @ExtCtxt, tts: &[ast::token_tree])
-> ~[@ast::expr] {
let p = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(),
vec::to_owned(tts));
tts.to_owned());
let mut es = ~[];
while *p.token != token::EOF {
if es.len() != 0 {
+1 -2
View File
@@ -18,7 +18,6 @@
use parse::token::{get_ident_interner};
use core::io;
use core::vec;
pub fn expand_syntax_ext(cx: @ExtCtxt,
sp: codemap::span,
@@ -28,7 +27,7 @@ pub fn expand_syntax_ext(cx: @ExtCtxt,
cx.print_backtrace();
io::stdout().write_line(
print::pprust::tt_to_str(
ast::tt_delim(vec::to_owned(tt)),
ast::tt_delim(tt.to_owned()),
get_ident_interner()));
//trivial expression
+2 -6
View File
@@ -19,8 +19,6 @@
use parse::token;
use parse;
use core::vec;
/**
*
* Quasiquoting works via token trees.
@@ -40,8 +38,6 @@ pub mod rt {
use parse;
use print::pprust;
use core::str;
pub use ast::*;
pub use parse::token::*;
pub use parse::new_parser_from_tts;
@@ -128,7 +124,7 @@ fn to_source(&self) -> ~str {
impl<'self> ToSource for &'self str {
fn to_source(&self) -> ~str {
let lit = dummy_spanned(ast::lit_str(@str::to_owned(*self)));
let lit = dummy_spanned(ast::lit_str(@self.to_owned()));
pprust::lit_to_str(@lit)
}
}
@@ -661,7 +657,7 @@ fn expand_tts(cx: @ExtCtxt,
let p = parse::new_parser_from_tts(
cx.parse_sess(),
cx.cfg(),
vec::to_owned(tts)
tts.to_owned()
);
*p.quote_depth += 1u;
let tts = p.parse_all_token_trees();
+1 -3
View File
@@ -18,8 +18,6 @@
use parse::parser::Parser;
use parse::token::keywords;
use core::vec;
pub fn expand_trace_macros(cx: @ExtCtxt,
sp: span,
tt: &[ast::token_tree])
@@ -29,7 +27,7 @@ pub fn expand_trace_macros(cx: @ExtCtxt,
let tt_rdr = new_tt_reader(
copy cx.parse_sess().span_diagnostic,
None,
vec::to_owned(tt)
tt.to_owned()
);
let rdr = tt_rdr as @reader;
let rust_parser = Parser(
+2 -3
View File
@@ -26,7 +26,6 @@
use print;
use core::io;
use core::vec;
pub fn add_new_extension(cx: @ExtCtxt,
sp: span,
@@ -84,7 +83,7 @@ fn generic_extension(cx: @ExtCtxt, sp: span, name: ident,
io::println(fmt!("%s! { %s }",
cx.str_of(name),
print::pprust::tt_to_str(
ast::tt_delim(vec::to_owned(arg)),
ast::tt_delim(arg.to_owned()),
get_ident_interner())));
}
@@ -101,7 +100,7 @@ fn generic_extension(cx: @ExtCtxt, sp: span, name: ident,
let arg_rdr = new_tt_reader(
s_d,
None,
vec::to_owned(arg)
arg.to_owned()
) as @reader;
match parse(cx.parse_sess(), cx.cfg(), arg_rdr, *mtcs) {
success(named_matches) => {
+1 -1
View File
@@ -193,7 +193,7 @@ pub fn to_str(in: @ident_interner, t: &Token) -> ~str {
}
body
}
LIT_STR(ref s) => { ~"\"" + str::escape_default(*ident_to_str(s)) + "\"" }
LIT_STR(ref s) => { ~"\"" + ident_to_str(s).escape_default() + "\"" }
/* Name components */
IDENT(s, _) => copy *in.get(s.name),
+1 -2
View File
@@ -31,7 +31,6 @@
use core::char;
use core::io;
use core::str;
use core::u64;
use core::uint;
use core::iterator::IteratorUtil;
@@ -2113,7 +2112,7 @@ pub fn print_comment(s: @ps, cmnt: &comments::cmnt) {
pub fn print_string(s: @ps, st: &str) {
word(s.s, "\"");
word(s.s, str::escape_default(st));
word(s.s, st.escape_default());
word(s.s, "\"");
}
+1 -1
View File
@@ -93,7 +93,7 @@ fn make(&mut self, n: uint) {
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()),
@@ -81,7 +81,8 @@ fn sortKV<TT:Copy + Ord,UU:Copy + Ord>(orig: ~[(TT,UU)]) -> ~[(TT,UU)] {
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);
}
}
+1 -2
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;
+1 -2
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;
+1 -1
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));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn emit(im: &mut HashMap<~str, int>, ctrl: SharedChan<ctrl_proto>, key: ~str,
}
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);
+1 -1
View File
@@ -15,6 +15,6 @@
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);
}
+1 -1
View File
@@ -14,5 +14,5 @@ struct S { f0: ~str, f1: int }
pub fn main() {
let s = ~"Hello, world!";
let _s = S { f0: str::to_owned(s), ..S { f0: s, f1: 23 } };
let _s = S { f0: s.to_owned(), ..S { f0: s, f1: 23 } };
}
+1 -1
View File
@@ -14,5 +14,5 @@ struct S { f0: ~str, f1: ~str }
pub fn main() {
let s = ~"Hello, world!";
let _s = S { f1: str::to_owned(s), f0: s };
let _s = S { f1: s.to_owned(), f0: s };
}
+7 -7
View File
@@ -21,24 +21,24 @@ pub fn main() {
let schs: ~[char] = s.iter().collect();
assert!(s.len() == 10u);
assert!(str::char_len(s) == 4u);
assert!(s.char_len() == 4u);
assert!(schs.len() == 4u);
assert!(str::from_chars(schs) == s);
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])));
let mut stack = ~"a×c€";
assert_eq!(str::pop_char(&mut stack), '€');
assert_eq!(str::pop_char(&mut stack), 'c');
assert_eq!(stack.pop_char(), '€');
assert_eq!(stack.pop_char(), 'c');
stack.push_char('u');
assert!(stack == ~"a×u");
assert_eq!(str::shift_char(&mut stack), 'a');
assert_eq!(str::shift_char(&mut stack), '×');
str::unshift_char(&mut stack, 'ß');
assert_eq!(stack.shift_char(), 'a');
assert_eq!(stack.shift_char(), '×');
stack.unshift_char('ß');
assert!(stack == ~"ßu");
}