diff --git a/doc/tutorial.md b/doc/tutorial.md index f487398d19c23..a458036116665 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -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)); } ~~~ diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 7159e51e3b6f3..c92084781287a 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -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"); diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index 62d4a32b8e239..f4754b3e4cbe1 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -12,7 +12,6 @@ use core::prelude::*; -use core::str; use core::vec; /// A trait for converting a value to base64 encoding. @@ -111,7 +110,7 @@ impl<'self> ToBase64 for &'self str { * */ fn to_base64(&self) -> ~str { - str::to_bytes(*self).to_base64() + self.as_bytes().to_base64() } } @@ -224,7 +223,7 @@ impl<'self> FromBase64 for &'self str { * ~~~ */ fn from_base64(&self) -> ~[u8] { - str::to_bytes(*self).from_base64() + self.as_bytes().from_base64() } } @@ -245,12 +244,12 @@ mod tests { #[test] fn test_from_base64() { - assert_eq!("".from_base64(), str::to_bytes("")); - assert_eq!("Zg==".from_base64(), str::to_bytes("f")); - assert_eq!("Zm8=".from_base64(), str::to_bytes("fo")); - assert_eq!("Zm9v".from_base64(), str::to_bytes("foo")); - assert_eq!("Zm9vYg==".from_base64(), str::to_bytes("foob")); - assert_eq!("Zm9vYmE=".from_base64(), str::to_bytes("fooba")) - assert_eq!("Zm9vYmFy".from_base64(), str::to_bytes("foobar")); + assert_eq!("".from_base64(), "".as_bytes().to_owned()); + assert_eq!("Zg==".from_base64(), "f".as_bytes().to_owned()); + assert_eq!("Zm8=".from_base64(), "fo".as_bytes().to_owned()); + assert_eq!("Zm9v".from_base64(), "foo".as_bytes().to_owned()); + assert_eq!("Zm9vYg==".from_base64(), "foob".as_bytes().to_owned()); + assert_eq!("Zm9vYmE=".from_base64(), "fooba".as_bytes().to_owned()); + assert_eq!("Zm9vYmFy".from_base64(), "foobar".as_bytes().to_owned()); } } diff --git a/src/libextra/ebml.rs b/src/libextra/ebml.rs index 233c804264009..dd08f23a7a10f 100644 --- a/src/libextra/ebml.rs +++ b/src/libextra/ebml.rs @@ -607,7 +607,6 @@ pub mod writer { use core::cast; use core::io; - use core::str; // ebml writing pub struct Encoder { @@ -725,7 +724,7 @@ pub mod writer { } pub fn wr_tagged_str(&mut self, tag_id: uint, v: &str) { - str::byte_slice(v, |b| self.wr_tagged_bytes(tag_id, b)); + self.wr_tagged_bytes(tag_id, v.as_bytes()); } pub fn wr_bytes(&mut self, b: &[u8]) { @@ -735,7 +734,7 @@ pub mod writer { pub fn wr_str(&mut self, s: &str) { debug!("Write str: %?", s); - self.writer.write(str::to_bytes(s)); + self.writer.write(s.as_bytes()); } } diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index add857ca9ed07..345b0e8cff769 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -487,7 +487,7 @@ mod test { let mut buf : ~[u8] = vec::from_elem(6, 0u8); let count = fi.read(buf, 10); assert_eq!(count, 6); - assert_eq!(buf, "0\n1\n2\n".to_bytes()); + assert_eq!(buf, "0\n1\n2\n".as_bytes().to_owned()); assert!(fi.eof()) assert_eq!(fi.state().line_num, 3); } diff --git a/src/libextra/flatpipes.rs b/src/libextra/flatpipes.rs index c0f619c1b858d..36ffbb731c87d 100644 --- a/src/libextra/flatpipes.rs +++ b/src/libextra/flatpipes.rs @@ -450,7 +450,7 @@ pub mod flatteners { T: Decodable>( 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); diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 8d58bd1885911..9fe81804bd2f4 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -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 mod groups { 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 mod groups { 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 mod groups { 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 mod groups { 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 mod groups { 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 mod groups { */ 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 mod groups { 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 mod groups { // 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 mod groups { row }); - return str::to_owned(brief) + + return brief.to_owned() + "\n\nOptions:\n" + rows.connect("\n") + "\n\n"; diff --git a/src/libextra/md4.rs b/src/libextra/md4.rs index f12c9d6573e90..94793804bb138 100644 --- a/src/libextra/md4.rs +++ b/src/libextra/md4.rs @@ -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 @@ pub fn md4_str(msg: &[u8]) -> ~str { /// Calculates the md4 hash of a string, returning the hex-encoded version of /// the hash -pub fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) } +pub fn md4_text(msg: &str) -> ~str { md4_str(msg.as_bytes()) } #[test] fn test_md4() { diff --git a/src/libextra/net_tcp.rs b/src/libextra/net_tcp.rs index 3ea085f5e86f1..d95807f2b91c4 100644 --- a/src/libextra/net_tcp.rs +++ b/src/libextra/net_tcp.rs @@ -1636,7 +1636,7 @@ mod test { assert_eq!(net::ip::get_port(&sock.get_peer_addr()), 8887); // Fulfill the protocol the test server expects - let resp_bytes = str::to_bytes("ping"); + let resp_bytes = "ping".as_bytes().to_owned(); tcp_write_single(&sock, resp_bytes); debug!("message sent"); sock.read(0u); @@ -1756,9 +1756,7 @@ mod test { buf_write(sock_buf, expected_req); // so contrived! - let actual_resp = do str::as_bytes(&expected_resp.to_str()) |resp_buf| { - buf_read(sock_buf, resp_buf.len()) - }; + let actual_resp = buf_read(sock_buf, expected_resp.as_bytes().len()); let actual_req = server_result_po.recv(); debug!("REQ: expected: '%s' actual: '%s'", @@ -1810,11 +1808,10 @@ mod test { fn buf_write(w: &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: &R, len: uint) -> ~str { @@ -1877,7 +1874,8 @@ mod test { server_ch.send( str::from_bytes(data)); debug!("SERVER: before write"); - tcp_write_single(&sock, str::to_bytes(resp_cell2.take())); + let s = resp_cell2.take(); + tcp_write_single(&sock, s.as_bytes().to_owned()); debug!("SERVER: after write.. die"); kill_ch.send(None); } @@ -1949,7 +1947,7 @@ mod test { } else { let sock = result::unwrap(connect_result); - let resp_bytes = str::to_bytes(resp); + let resp_bytes = resp.as_bytes().to_owned(); tcp_write_single(&sock, resp_bytes); let read_result = sock.read(0u); if read_result.is_err() { diff --git a/src/libextra/net_url.rs b/src/libextra/net_url.rs index 83cda31c68089..31d728f18130b 100644 --- a/src/libextra/net_url.rs +++ b/src/libextra/net_url.rs @@ -1060,7 +1060,7 @@ mod tests { /* assert_eq!(decode_form_urlencoded([]).len(), 0); - let s = str::to_bytes("a=1&foo+bar=abc&foo+bar=12+%3D+34"); + let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes(); let form = decode_form_urlencoded(s); assert_eq!(form.len(), 2); assert_eq!(form.get_ref(&~"a"), &~[~"1"]); diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index c6e7592a314e1..8c2615de26ba2 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -524,7 +524,7 @@ impl ToStrRadix for BigUint { 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::parse_bytes(str::to_bytes(s), radix) + BigUint::parse_bytes(s.as_bytes(), radix) } } @@ -564,7 +564,7 @@ impl 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::parse_bytes(str::to_bytes(s), radix) + BigInt::parse_bytes(s.as_bytes(), radix) } } diff --git a/src/libextra/rope.rs b/src/libextra/rope.rs index de54964142349..099b257380bc4 100644 --- a/src/libextra/rope.rs +++ b/src/libextra/rope.rs @@ -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 mod node { * * 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 mod 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 mod node { 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 mod node { 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 mod node { 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 @@ mod tests { 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 @@ mod tests { } 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 @@ mod tests { } } - assert_eq!(len, str::char_len(*sample)); + assert_eq!(len, sample.char_len()); } #[test] diff --git a/src/libextra/sha1.rs b/src/libextra/sha1.rs index 658621e25bdf1..03ceded007301 100644 --- a/src/libextra/sha1.rs +++ b/src/libextra/sha1.rs @@ -25,7 +25,6 @@ use core::prelude::*; use core::iterator::IteratorUtil; -use core::str; use core::uint; use core::vec; @@ -246,8 +245,7 @@ pub fn sha1() -> @Sha1 { } fn input(&mut self, msg: &const [u8]) { add_input(self, msg); } fn input_str(&mut self, msg: &str) { - let bs = str::to_bytes(msg); - add_input(self, bs); + add_input(self, msg.as_bytes()); } fn result(&mut self) -> ~[u8] { return mk_result(self); } fn result_str(&mut self) -> ~str { diff --git a/src/libextra/stats.rs b/src/libextra/stats.rs index 0cc1ee9a1d716..17bdf6c3a1dd2 100644 --- a/src/libextra/stats.rs +++ b/src/libextra/stats.rs @@ -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 @@ impl<'self> Stats for &'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; diff --git a/src/libextra/terminfo/parm.rs b/src/libextra/terminfo/parm.rs index 4eb48f60a9999..40191c8992578 100644 --- a/src/libextra/terminfo/parm.rs +++ b/src/libextra/terminfo/parm.rs @@ -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, diff --git a/src/libextra/terminfo/searcher.rs b/src/libextra/terminfo/searcher.rs index ecc99f74626c1..1ef410252ab93 100644 --- a/src/libextra/terminfo/searcher.rs +++ b/src/libextra/terminfo/searcher.rs @@ -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); } diff --git a/src/libextra/time.rs b/src/libextra/time.rs index caaa2994405e0..8b754f8c560e5 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -1029,7 +1029,7 @@ mod tests { 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) } } diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index 3f74b905f2a6f..0918ab8ddadad 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -769,10 +769,10 @@ mod test_treemap { fn u8_map() { let mut m = TreeMap::new(); - let k1 = str::to_bytes("foo"); - let k2 = str::to_bytes("bar"); - let v1 = str::to_bytes("baz"); - let v2 = str::to_bytes("foobar"); + let k1 = "foo".as_bytes(); + let k2 = "bar".as_bytes(); + let v1 = "baz".as_bytes(); + let v2 = "foobar".as_bytes(); m.insert(copy k1, copy v1); m.insert(copy k2, copy v2); diff --git a/src/libextra/uv_ll.rs b/src/libextra/uv_ll.rs index 187960b91016a..744f4555d5cbd 100644 --- a/src/libextra/uv_ll.rs +++ b/src/libextra/uv_ll.rs @@ -1368,7 +1368,7 @@ mod test { // In C, this would be a malloc'd or stack-allocated // struct that we'd cast to a void* and store as the // data field in our uv_connect_t struct - let req_str_bytes = str::to_bytes(req_str); + let req_str_bytes = req_str.as_bytes(); let req_msg_ptr: *u8 = vec::raw::to_ptr(req_str_bytes); debug!("req_msg ptr: %u", req_msg_ptr as uint); let req_msg = ~[ @@ -1626,7 +1626,7 @@ mod test { let server_write_req = write_t(); let server_write_req_ptr: *uv_write_t = &server_write_req; - let resp_str_bytes = str::to_bytes(server_resp_msg); + let resp_str_bytes = server_resp_msg.as_bytes(); let resp_msg_ptr: *u8 = vec::raw::to_ptr(resp_str_bytes); debug!("resp_msg ptr: %u", resp_msg_ptr as uint); let resp_msg = ~[ diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index dbeea417a3dd9..5ca25c11ba02f 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -328,7 +328,7 @@ pub fn check_variants_T(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)); diff --git a/src/librust/rust.rc b/src/librust/rust.rc index 5bc490937b615..f0d4652eb1da0 100644 --- a/src/librust/rust.rc +++ b/src/librust/rust.rc @@ -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)); } diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 5375425b8530c..84fb361adb982 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -50,8 +50,7 @@ pub enum output_type { } fn write_string(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() } diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 9a6f48a325765..4b7ab6fdfc101 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -29,7 +29,6 @@ use core::hashmap::HashMap; 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", diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index c5779dde499c8..980d318ec62f9 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -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)), diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index e0061f3f95e57..b34bdafbeda5a 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -202,7 +202,8 @@ fn encode_type_param_bounds(ebml_w: &mut writer::Encoder, fn encode_variant_id(ebml_w: &mut writer::Encoder, vid: def_id) { ebml_w.start_tag(tag_items_data_item_variant); - ebml_w.writer.write(str::to_bytes(def_to_str(vid))); + let s = def_to_str(vid); + ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -271,7 +272,7 @@ fn encode_symbol(ecx: @EncodeContext, match ecx.item_symbols.find(&id) { Some(x) => { debug!("encode_symbol(id=%?, str=%s)", id, *x); - ebml_w.writer.write(str::to_bytes(*x)); + ebml_w.writer.write(x.as_bytes()); } None => { ecx.diag.handler().bug( @@ -285,7 +286,7 @@ fn encode_discriminant(ecx: @EncodeContext, ebml_w: &mut writer::Encoder, id: node_id) { ebml_w.start_tag(tag_items_data_item_symbol); - ebml_w.writer.write(str::to_bytes(*ecx.discrim_symbols.get_copy(&id))); + ebml_w.writer.write(ecx.discrim_symbols.get_copy(&id).as_bytes()); ebml_w.end_tag(); } @@ -293,13 +294,15 @@ fn encode_disr_val(_: @EncodeContext, ebml_w: &mut writer::Encoder, disr_val: int) { ebml_w.start_tag(tag_disr_val); - ebml_w.writer.write(str::to_bytes(int::to_str(disr_val))); + let s = int::to_str(disr_val); + ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } fn encode_parent_item(ebml_w: &mut writer::Encoder, id: def_id) { ebml_w.start_tag(tag_items_data_parent_item); - ebml_w.writer.write(str::to_bytes(def_to_str(id))); + let s = def_to_str(id); + ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -954,7 +957,8 @@ fn encode_info_for_item(ecx: @EncodeContext, for methods.each |m| { ebml_w.start_tag(tag_item_impl_method); let method_def_id = local_def(m.id); - ebml_w.writer.write(str::to_bytes(def_to_str(method_def_id))); + let s = def_to_str(method_def_id); + ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } for opt_trait.iter().advance |ast_trait_ref| { @@ -1218,7 +1222,7 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) { meta_word(name) => { ebml_w.start_tag(tag_meta_item_word); ebml_w.start_tag(tag_meta_item_name); - ebml_w.writer.write(str::to_bytes(*name)); + ebml_w.writer.write(name.as_bytes()); ebml_w.end_tag(); ebml_w.end_tag(); } @@ -1227,10 +1231,10 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) { lit_str(value) => { ebml_w.start_tag(tag_meta_item_name_value); ebml_w.start_tag(tag_meta_item_name); - ebml_w.writer.write(str::to_bytes(*name)); + ebml_w.writer.write(name.as_bytes()); ebml_w.end_tag(); ebml_w.start_tag(tag_meta_item_value); - ebml_w.writer.write(str::to_bytes(*value)); + ebml_w.writer.write(value.as_bytes()); ebml_w.end_tag(); ebml_w.end_tag(); } @@ -1240,7 +1244,7 @@ fn encode_meta_item(ebml_w: &mut writer::Encoder, mi: @meta_item) { meta_list(name, ref items) => { ebml_w.start_tag(tag_meta_item_list); ebml_w.start_tag(tag_meta_item_name); - ebml_w.writer.write(str::to_bytes(*name)); + ebml_w.writer.write(name.as_bytes()); ebml_w.end_tag(); for items.each |inner_item| { encode_meta_item(ebml_w, *inner_item); @@ -1398,20 +1402,21 @@ fn encode_crate_dep(ecx: @EncodeContext, dep: decoder::crate_dep) { ebml_w.start_tag(tag_crate_dep); ebml_w.start_tag(tag_crate_dep_name); - ebml_w.writer.write(str::to_bytes(*ecx.tcx.sess.str_of(dep.name))); + let s = ecx.tcx.sess.str_of(dep.name); + ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); ebml_w.start_tag(tag_crate_dep_vers); - ebml_w.writer.write(str::to_bytes(*dep.vers)); + ebml_w.writer.write(dep.vers.as_bytes()); ebml_w.end_tag(); ebml_w.start_tag(tag_crate_dep_hash); - ebml_w.writer.write(str::to_bytes(*dep.hash)); + ebml_w.writer.write(dep.hash.as_bytes()); ebml_w.end_tag(); ebml_w.end_tag(); } fn encode_hash(ebml_w: &mut writer::Encoder, hash: &str) { ebml_w.start_tag(tag_crate_hash); - ebml_w.writer.write(str::to_bytes(hash)); + ebml_w.writer.write(hash.as_bytes()); ebml_w.end_tag(); } @@ -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) } diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 6314cb6269768..d65e7e0ed4fe3 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -13,7 +13,6 @@ use core::prelude::*; use core::option; use core::os; use core::result; -use core::str; // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should @@ -81,7 +80,7 @@ pub fn mk_filesearch(maybe_sysroot: &Option<@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(filesearch: @FileSearch, pick: pick) -> Option { 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()]) } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 2017c29590cbe..370804cb7507e 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -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( diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index c352771733934..00d06f0a3d8c9 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -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 } } diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 007970067b331..7f57b4b0c0d7a 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -23,7 +23,6 @@ use core::i16; 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 @@ impl Context { 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('_') } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 7c9877a838ad7..1adb991c96e71 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -2678,14 +2678,14 @@ impl Resolver { 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 => (), }; diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 8e1b165f40896..3ec86688c3169 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -48,7 +48,6 @@ use core::iterator::IteratorUtil; use core::container::Map; use core::libc::c_ulonglong; use core::option::{Option, Some, None}; -use core::vec; use lib::llvm::{ValueRef, TypeRef, True, IntEQ, IntNE}; use middle::trans::_match; @@ -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() } } diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index f47775f0700a0..bee63a35a2488 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -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) } diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 25aa59b852de8..af10845181008 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -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"); diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 5b286a7831198..65755345ac3d5 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -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 } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index ba446d6016c6c..df3bc753ae188 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -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)) } diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index adb0f43e2d720..ff19893daad9c 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -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 { diff --git a/src/librustdoc/attr_parser.rs b/src/librustdoc/attr_parser.rs index 47c54ee8e8f45..026f57df03556 100644 --- a/src/librustdoc/attr_parser.rs +++ b/src/librustdoc/attr_parser.rs @@ -17,7 +17,6 @@ an AST's attributes. use core::prelude::*; -use core::str; use syntax::ast; use syntax::attr; diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 691f0dfedc4ca..ef65cc8e5a1b8 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -262,7 +262,7 @@ mod test { .. default_config(&Path("test")) }; let mock_process_output: ~fn(&str, &[~str]) -> ProcessOutput = |_, _| { - ProcessOutput { status: 0, output: "pandoc 1.8.2.1".to_bytes(), error: ~[] } + ProcessOutput { status: 0, output: "pandoc 1.8.2.1".as_bytes().to_owned(), error: ~[] } }; let result = maybe_find_pandoc(&config, None, mock_process_output); assert!(result == result::Ok(Some(~"pandoc"))); diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index f018a237b7e29..c116ccd698692 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -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() } } } diff --git a/src/librustdoc/escape_pass.rs b/src/librustdoc/escape_pass.rs index 045e916b11006..2f09e0a5ddc55 100644 --- a/src/librustdoc/escape_pass.rs +++ b/src/librustdoc/escape_pass.rs @@ -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] diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index 36eb5e77ad651..3634155b8a3d8 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -22,8 +22,6 @@ use markdown_pass; 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 @@ pub fn pandoc_header_id(header: &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 diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index b6917f527a1ff..6f480d1877077 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -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; } diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index f8b39d9fbc72f..3e1883062f33c 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -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(); diff --git a/src/librustpkg/package_path.rs b/src/librustpkg/package_path.rs index a54f9ad152f48..161634be650cb 100644 --- a/src/librustpkg/package_path.rs +++ b/src/librustpkg/package_path.rs @@ -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(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 { diff --git a/src/librustpkg/package_source.rs b/src/librustpkg/package_source.rs index a4a392e4bbbe1..6d8a6095ca438 100644 --- a/src/librustpkg/package_source.rs +++ b/src/librustpkg/package_source.rs @@ -183,7 +183,7 @@ impl PkgSrc { 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); diff --git a/src/libstd/hashmap.rs b/src/libstd/hashmap.rs index 7a9435d2ecd0b..c0cc92723ba4d 100644 --- a/src/libstd/hashmap.rs +++ b/src/libstd/hashmap.rs @@ -866,6 +866,23 @@ mod test_map { 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)] diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 58711360c3564..07e129e3c289a 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -761,7 +761,7 @@ impl ReaderUtil for T { 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(bytes: &[u8], f: &fn(@Reader) -> T) -> T { } pub fn with_str_reader(s: &str, f: &fn(@Reader) -> T) -> T { - str::byte_slice(s, |bytes| with_bytes_reader(bytes, f)) + with_bytes_reader(s.as_bytes(), f) } // Writing @@ -1462,7 +1462,7 @@ impl WriterUtil for T { self.write_str(str::from_char(ch)); } } - fn write_str(&self, s: &str) { str::byte_slice(s, |v| self.write(v)) } + fn write_str(&self, s: &str) { self.write(s.as_bytes()) } fn write_line(&self, s: &str) { self.write_str(s); self.write_str(&"\n"); diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 3583e2f366ff3..74f74d11b7302 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -793,27 +793,27 @@ mod tests { #[test] fn test_parse_bytes() { - use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123 as $T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9 as $T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83 as $T)); - assert_eq!(i32::parse_bytes(to_bytes("123"), 16u), Some(291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("ffff"), 16u), Some(65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("FFFF"), 16u), Some(65535 as i32)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35 as $T)); - assert_eq!(parse_bytes(to_bytes("Z"), 36u), Some(35 as $T)); - - 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!(parse_bytes(to_bytes("Z"), 35u).is_none()); - assert!(parse_bytes(to_bytes("-9"), 2u).is_none()); + 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("-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("Z".as_bytes(), 35u).is_none()); + assert!(parse_bytes("-9".as_bytes(), 2u).is_none()); } #[test] diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 30efe9a392233..3905d82cd0f5c 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -16,6 +16,7 @@ use ops::{Add, Sub, Mul, Div, Rem, Neg}; use option::{None, Option, Some}; use char; use str; +use str::{StrSlice}; use kinds::Copy; use vec; use vec::{CopyableVector, ImmutableVector}; @@ -189,18 +190,18 @@ pub fn to_str_bytes_common (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+Mul+ special: bool, exponent: ExponentFormat, empty_zero: bool, ignore_underscores: bool ) -> Option { - 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) } diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index a7aebf1f176c2..2bc1ca9c67330 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -538,16 +538,16 @@ mod tests { #[test] pub fn test_parse_bytes() { - use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123u as $T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9u as $T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83u as $T)); - assert_eq!(u16::parse_bytes(to_bytes("123"), 16u), Some(291u as u16)); - assert_eq!(u16::parse_bytes(to_bytes("ffff"), 16u), Some(65535u as u16)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35u as $T)); - - assert!(parse_bytes(to_bytes("Z"), 10u).is_none()); - assert!(parse_bytes(to_bytes("_"), 2u).is_none()); + 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("Z".as_bytes(), 10u).is_none()); + assert!(parse_bytes("_".as_bytes(), 2u).is_none()); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 66993fb909963..044b305a0dd9d 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -1448,9 +1448,9 @@ mod tests { use rand::RngUtil; use rand; use run; - use str; use str::StrSlice; use vec; + use vec::CopyableVector; use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR}; @@ -1684,7 +1684,7 @@ mod tests { }; assert!((ostream as uint != 0u)); let s = ~"hello"; - let mut buf = str::to_bytes(s) + [0 as u8]; + let mut buf = s.as_bytes_with_null().to_owned(); do vec::as_mut_buf(buf) |b, _len| { assert!((libc::fwrite(b as *c_void, 1u as size_t, (s.len() + 1u) as size_t, ostream) diff --git a/src/libstd/path.rs b/src/libstd/path.rs index d62fc8c2cbafd..02772604e45ca 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -515,7 +515,7 @@ impl GenericPath for 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 @@ impl GenericPath for WindowsPath { (None, None) => { host = None; device = None; - rest = str::to_owned(s); + rest = s.to_owned(); } } @@ -729,7 +729,7 @@ impl GenericPath for 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 mod windows { mod tests { use option::{None, Some}; use path::{PosixPath, WindowsPath, windows}; - use str; #[test] fn test_double_slash_collapsing() { @@ -984,7 +983,7 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { 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); diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index 476aef3709335..e969c5d4e3a15 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -64,7 +64,7 @@ pub use path::PosixPath; pub use path::WindowsPath; pub use ptr::RawPtr; pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr}; -pub use str::{StrVector, StrSlice, OwnedStr, StrUtil}; +pub use str::{StrVector, StrSlice, OwnedStr, StrUtil, NullTerminatedStr}; pub use from_str::{FromStr}; pub use to_bytes::IterBytes; pub use to_str::{ToStr, ToStrConsume}; diff --git a/src/libstd/rand.rs b/src/libstd/rand.rs index 7946f7e4f13f6..f785020593005 100644 --- a/src/libstd/rand.rs +++ b/src/libstd/rand.rs @@ -577,7 +577,7 @@ impl RngUtil for R { /// Shuffle a vec fn shuffle(&mut self, values: &[T]) -> ~[T] { - let mut m = vec::to_owned(values); + let mut m = values.to_owned(); self.shuffle_mut(m); m } diff --git a/src/libstd/rt/io/file.rs b/src/libstd/rt/io/file.rs index 1f61cf25fbdd4..a99f5da032c39 100644 --- a/src/libstd/rt/io/file.rs +++ b/src/libstd/rt/io/file.rs @@ -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()); } diff --git a/src/libstd/rt/io/flate.rs b/src/libstd/rt/io/flate.rs index 0a9e0b1e38f23..e57b80658eef2 100644 --- a/src/libstd/rt/io/flate.rs +++ b/src/libstd/rt/io/flate.rs @@ -108,7 +108,7 @@ mod test { let mem_writer = MemWriter::new(); let mut deflate_writer = DeflateWriter::new(mem_writer); let in_msg = "test"; - let in_bytes = in_msg.to_bytes(); + let in_bytes = in_msg.as_bytes(); deflate_writer.write(in_bytes); deflate_writer.flush(); let buf = deflate_writer.inner().inner(); diff --git a/src/libstd/run.rs b/src/libstd/run.rs index 6b2fecc500180..b204cf6cfb04f 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -741,8 +741,7 @@ fn with_envp(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| diff --git a/src/libstd/str.rs b/src/libstd/str.rs index f270964c3b569..fdf12d406e81f 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -26,7 +26,7 @@ use clone::Clone; 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,101 +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 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 - } -} - -impl<'self> StrVector for &'self [&'self str] { - /// Concatenate a vector of strings. - pub fn concat(&self) -> ~str { - if self.is_empty() { return ~""; } + let len = self.iter().transform(|s| s.as_slice().len()).sum(); - let mut len = 0; - for self.each |ss| { - len += ss.len(); - } let mut s = ~""; s.reserve(len); @@ -262,8 +174,8 @@ impl<'self> StrVector for &'self [&'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); @@ -283,10 +195,8 @@ impl<'self> StrVector for &'self [&'self 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; @@ -297,8 +207,8 @@ impl<'self> StrVector for &'self [&'self 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; @@ -318,120 +228,6 @@ impl<'self> StrVector for &'self [&'self str] { } } -/// 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(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 @@ impl CharEq for extern "Rust" fn(char) -> bool { 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 @@ pub fn each_split_within<'a>(ss: &'a str, 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 @@ static tag_five_b: uint = 248u; static max_five_b: uint = 67108864u; static tag_six_b: uint = 252u; -/** - * Work with the byte buffer of a string. - * - * Allows for unsafe manipulation of strings, which is useful for foreign - * interop. - * - * # Example - * - * ~~~ {.rust} - * let i = str::as_bytes("Hello World") { |bytes| bytes.len() }; - * ~~~ - */ -#[inline] -pub fn as_bytes(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 @@ impl<'self> StrUtil for &'self str { // 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 @@ pub mod raw { #[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 @@ pub mod traits { #[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 @@ pub trait StrSlice<'self> { 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(&self, to_trim: &C) -> &'self str; + fn trim_left_chars(&self, to_trim: &C) -> &'self str; + fn trim_right_chars(&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 @@ pub trait StrSlice<'self> { fn char_at(&self, i: uint) -> char; fn char_range_at_reverse(&self, start: uint) -> CharRange; fn char_at_reverse(&self, i: uint) -> char; - fn to_bytes(&self) -> ~[u8]; + fn as_bytes(&self) -> &'self [u8]; fn find(&self, search: C) -> Option; fn rfind(&self, search: C) -> Option; fn find_str(&self, &str) -> Option; + + fn repeat(&self, nn: uint) -> ~str; + + fn slice_shift_char(&self) -> (char, &'self str); } /// Extension methods for strings @@ -1635,12 +1334,12 @@ impl<'self> StrSlice<'self> for &'self str { /// An iterator over the bytes of `self` #[inline] fn bytes_iter(&self) -> StrBytesIterator<'self> { - StrBytesIterator { it: as_bytes_slice(*self).iter() } + StrBytesIterator { it: self.as_bytes().iter() } } /// An iterator over the bytes of `self`, in reverse order #[inline] fn bytes_rev_iter(&self) -> StrBytesRevIterator<'self> { - StrBytesRevIterator { it: as_bytes_slice(*self).rev_iter() } + StrBytesRevIterator { it: self.as_bytes().rev_iter() } } /// An iterator over substrings of `self`, separated by characters @@ -1753,7 +1452,8 @@ impl<'self> StrSlice<'self> for &'self str { } /// 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 @@ impl<'self> StrSlice<'self> for &'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 @@ impl<'self> StrSlice<'self> for &'self str { 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 @@ impl<'self> StrSlice<'self> for &'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(&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(&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 @@ impl<'self> StrSlice<'self> for &'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(&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 @@ impl<'self> StrSlice<'self> for &'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 @@ impl<'self> StrSlice<'self> for &'self str { self.char_range_at_reverse(i).ch } - fn to_bytes(&self) -> ~[u8] { to_bytes(*self) } + /** + * Work with the byte buffer of a string as a byte slice. + * + * The byte slice does not include the null terminator. + */ + fn as_bytes(&self) -> &'self [u8] { + unsafe { + let (ptr, len): (*u8, uint) = ::cast::transmute(*self); + let outgoing_tuple: (*u8, uint) = (ptr, len - 1); + ::cast::transmute(outgoing_tuple) + } + } /** * Returns the byte index of the first character of `self` that matches `search` @@ -2094,6 +1866,92 @@ impl<'self> StrSlice<'self> for &'self str { .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 @@ impl OwnedStr for ~str { 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 @@ impl OwnedStr for ~str { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { #[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 @@ mod tests { #[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 @@ mod tests { } #[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 @@ mod tests { #[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 @@ mod tests { #[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 @@ mod tests { let a = ~"ประเ"; let A = ~"دولة الكويتทศไทย中华"; - assert_eq!(replace(data, a, repl), A); + assert_eq!(data.replace(a, repl), A); } #[test] @@ -2604,7 +2575,7 @@ mod tests { let b = ~"ะเ"; let B = ~"ปรدولة الكويتทศไทย中华"; - assert_eq!(replace(data, b, repl), B); + assert_eq!(data.replace(b, repl), B); } #[test] @@ -2614,7 +2585,7 @@ mod tests { let c = ~"中华"; let C = ~"ประเทศไทยدولة الكويت"; - assert_eq!(replace(data, c, repl), C); + assert_eq!(data.replace(c, repl), C); } #[test] @@ -2623,7 +2594,7 @@ mod tests { let repl = ~"دولة الكويت"; let d = ~"ไท华"; - assert_eq!(replace(data, d, repl), data); + assert_eq!(data.replace(d, repl), data); } #[test] @@ -2707,26 +2678,41 @@ mod tests { #[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 @@ mod tests { } } + #[test] + fn test_as_bytes() { + // no null + let v = [ + 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, + 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, + 109 + ]; + assert_eq!("".as_bytes(), &[]); + assert_eq!("abc".as_bytes(), &['a' as u8, 'b' as u8, 'c' as u8]); + assert_eq!("ศไทย中华Việt Nam".as_bytes(), v); + } + + #[test] + fn test_as_bytes_with_null() { + // has null + let v = [ + 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, + 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, + 109, 0 + ]; + + assert_eq!("".as_bytes_with_null(), &[0]); + assert_eq!("abc".as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]); + assert_eq!("ศไทย中华Việt Nam".as_bytes_with_null(), v); + + let s1 = @""; + let s2 = @"abc"; + let s3 = @"ศไทย中华Việt Nam"; + assert_eq!(s1.as_bytes_with_null(), &[0]); + assert_eq!(s2.as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]); + assert_eq!(s3.as_bytes_with_null(), v); + + let s1 = ~""; + let s2 = ~"abc"; + let s3 = ~"ศไทย中华Việt Nam"; + assert_eq!(s1.as_bytes_with_null(), &[0]); + assert_eq!(s2.as_bytes_with_null(), &['a' as u8, 'b' as u8, 'c' as u8, 0]); + assert_eq!(s3.as_bytes_with_null(), v); + } + + #[test] + fn test_as_bytes_with_null_consume() { + let s = ~"ศไทย中华Việt Nam"; + let v = ~[ + 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, + 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, + 109, 0 + ]; + assert_eq!((~"").as_bytes_with_null_consume(), ~[0]); + assert_eq!((~"abc").as_bytes_with_null_consume(), + ~['a' as u8, 'b' as u8, 'c' as u8, 0]); + assert_eq!(s.as_bytes_with_null_consume(), v); + } + #[test] #[ignore(cfg(windows))] #[should_fail] fn test_as_bytes_fail() { - // Don't double free - as_bytes::<()>(&~"", |_bytes| fail!() ); + // Don't double free. (I'm not sure if this exercises the + // original problem code path anymore.) + let s = ~""; + let _bytes = s.as_bytes_with_null(); + fail!(); } #[test] @@ -2985,7 +3029,7 @@ mod tests { fn vec_str_conversions() { let s1: ~str = ~"All mimsy were the borogoves"; - let v: ~[u8] = to_bytes(s1); + let v: ~[u8] = s1.as_bytes().to_owned(); let s2: ~str = from_bytes(v); let mut i: uint = 0u; let n1: uint = s1.len(); @@ -3104,30 +3148,27 @@ mod tests { #[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 @@ mod tests { 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() { diff --git a/src/libstd/to_bytes.rs b/src/libstd/to_bytes.rs index 77e7583ebe532..c0c8b729f9ea6 100644 --- a/src/libstd/to_bytes.rs +++ b/src/libstd/to_bytes.rs @@ -18,7 +18,7 @@ use io; use io::Writer; use option::{None, Option, Some}; use old_iter::BaseIter; -use str; +use str::StrSlice; pub type Cb<'self> = &'self fn(buf: &[u8]) -> bool; @@ -239,27 +239,25 @@ impl IterBytes for @[A] { impl<'self> IterBytes for &'self str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { - do str::byte_slice(*self) |bytes| { - f(bytes) - } + f(self.as_bytes()) } } impl IterBytes for ~str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { - do str::byte_slice(*self) |bytes| { - f(bytes) - } + // this should possibly include the null terminator, but that + // breaks .find_equiv on hashmaps. + f(self.as_bytes()) } } impl IterBytes for @str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { - do str::byte_slice(*self) |bytes| { - f(bytes) - } + // this should possibly include the null terminator, but that + // breaks .find_equiv on hashmaps. + f(self.as_bytes()) } } diff --git a/src/libstd/unstable/extfmt.rs b/src/libstd/unstable/extfmt.rs index 8a6f58d7992e9..7d9ce585d7c52 100644 --- a/src/libstd/unstable/extfmt.rs +++ b/src/libstd/unstable/extfmt.rs @@ -325,7 +325,7 @@ pub mod ct { '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 mod rt { // 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 mod rt { ~"" } 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 mod rt { } 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); diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 19233c533481e..52cb20458ea54 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -171,11 +171,6 @@ pub fn from_elem(n_elts: uint, t: T) -> ~[T] { } } -/// Creates a new unique vector with the same contents as the slice -pub fn to_owned(t: &[T]) -> ~[T] { - from_fn(t.len(), |i| t[i]) -} - /// Creates a new vector with a capacity of `capacity` pub fn with_capacity(capacity: uint) -> ~[T] { let mut vec = ~[]; @@ -1787,7 +1782,7 @@ pub trait CopyableVector { /// Extension methods for vectors impl<'self,T:Copy> CopyableVector 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 @@ impl<'self,T:Copy> CopyableVector for &'self [T] { result.push(copy *e); } result - } } @@ -3361,19 +3355,19 @@ mod tests { 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]]); } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 51334772c84b3..da5874f7b0522 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -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) } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index d3efd07aa045d..f9f9f7216a4f6 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -21,8 +21,6 @@ use ext::base::*; 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 = ~[]; diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index a3432a00edc03..73f68735bcd35 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -22,7 +22,6 @@ use parse::token; use parse::token::{ident_to_str, intern, str_to_ident}; use core::hashmap::HashMap; -use core::vec; // new-style macro! tt code: // @@ -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 { diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index 3ad4f87083f3d..ff8b492c94384 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -18,7 +18,6 @@ use print; use parse::token::{get_ident_interner}; use core::io; -use core::vec; pub fn expand_syntax_ext(cx: @ExtCtxt, sp: codemap::span, @@ -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 diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 2c6f40091ac9f..92727c7397748 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -19,8 +19,6 @@ use parse::token::*; 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 @@ pub mod rt { 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(); diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index 3baf432f24d65..09b3fd2343400 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -18,8 +18,6 @@ use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; use parse::token::keywords; -use core::vec; - pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) @@ -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( diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 1822117507d7f..7805e7364677c 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -26,7 +26,6 @@ use parse::token::{FAT_ARROW, SEMI, nt_matchers, nt_tt}; use print; use core::io; -use core::vec; pub fn add_new_extension(cx: @ExtCtxt, sp: span, @@ -84,7 +83,7 @@ pub fn add_new_extension(cx: @ExtCtxt, 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 @@ pub fn add_new_extension(cx: @ExtCtxt, 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) => { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 7359448a8f236..91605db77b54a 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -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), diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b6459fe30a355..ea33c04dbb5f6 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -31,7 +31,6 @@ use print::pprust; 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, "\""); } diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index bc1685a109220..3d5fc01afa6a2 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -93,7 +93,7 @@ impl RepeatFasta { let stdout = self.stdout; let alu_len = self.alu.len(); let mut buf = vec::from_elem(alu_len + LINE_LEN, 0u8); - let alu: &[u8] = str::byte_slice_no_callback(self.alu); + let alu: &[u8] = self.alu.as_bytes_with_null(); copy_memory(buf, alu, alu_len); copy_memory(vec::mut_slice(buf, alu_len, buf.len()), diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 9ba9b9759fd11..b7969fb0552e3 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -81,7 +81,8 @@ fn sort_and_fmt(mm: &HashMap<~[u8], uint>, total: uint) -> ~str { fn find(mm: &HashMap<~[u8], uint>, key: ~str) -> uint { // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use // to_ascii_consume and to_str_consume to not do a unnecessary copy. - match mm.find(&str::to_bytes(key.to_ascii().to_lower().to_str_ascii())) { + let key = key.to_ascii().to_lower().to_str_ascii(); + match mm.find_equiv(&key.as_bytes()) { option::None => { return 0u; } option::Some(&num) => { return num; } } @@ -208,10 +209,10 @@ fn main() { // process the sequence for k-mers (_, true) => { - let line_bytes = str::to_bytes(line); + let line_bytes = line.as_bytes(); for sizes.eachi |ii, _sz| { - let mut lb = copy line_bytes; + let mut lb = line_bytes.to_owned(); to_child[ii].send(lb); } } diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index a70e073007306..646b9788f706a 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -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; diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 0a093d87a1586..b869aa0e342cb 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -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; diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index 27b0c90379108..36ac10915c06f 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -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)); } } diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index e731703133248..eae2f507c5197 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -48,7 +48,7 @@ mod map_reduce { } let (pp, cc) = stream(); error!("sending find_reducer"); - ctrl.send(find_reducer(str::to_bytes(key), cc)); + ctrl.send(find_reducer(key.as_bytes().to_owned(), cc)); error!("receiving"); let c = pp.recv(); error!(c); diff --git a/src/test/run-pass/issue-1696.rs b/src/test/run-pass/issue-1696.rs index 62088e013be1e..103679a13eff9 100644 --- a/src/test/run-pass/issue-1696.rs +++ b/src/test/run-pass/issue-1696.rs @@ -15,6 +15,6 @@ use std::str; pub fn main() { let mut m = HashMap::new(); - m.insert(str::to_bytes(~"foo"), str::to_bytes(~"bar")); + m.insert("foo".as_bytes().to_owned(), "bar".as_bytes().to_owned()); error!(m); } diff --git a/src/test/run-pass/struct-order-of-eval-1.rs b/src/test/run-pass/struct-order-of-eval-1.rs index cfa0401e5b942..42908a339d200 100644 --- a/src/test/run-pass/struct-order-of-eval-1.rs +++ b/src/test/run-pass/struct-order-of-eval-1.rs @@ -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 } }; } diff --git a/src/test/run-pass/struct-order-of-eval-2.rs b/src/test/run-pass/struct-order-of-eval-2.rs index f58e5bab3febf..b6851a728882a 100644 --- a/src/test/run-pass/struct-order-of-eval-2.rs +++ b/src/test/run-pass/struct-order-of-eval-2.rs @@ -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 }; } diff --git a/src/test/run-pass/utf8_chars.rs b/src/test/run-pass/utf8_chars.rs index d3bfd9b0164d5..c126a84e78227 100644 --- a/src/test/run-pass/utf8_chars.rs +++ b/src/test/run-pass/utf8_chars.rs @@ -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"); }