diff options
| author | bors <bors@rust-lang.org> | 2014-05-22 15:16:31 -0700 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-05-22 15:16:31 -0700 |
| commit | 87ad19eb78239707f1ceed43e475c6aa052efdbc (patch) | |
| tree | 35940d52f145bca81dcf73e5e7da7f3847ceb413 /src/libstd | |
| parent | e402e75f4eb79af09b9451f0f232f994b3e2c998 (diff) | |
| parent | e878721d70349e2055f0ef854085de92e9498fde (diff) | |
| download | rust-87ad19eb78239707f1ceed43e475c6aa052efdbc.tar.gz rust-87ad19eb78239707f1ceed43e475c6aa052efdbc.zip | |
auto merge of #14310 : pcwalton/rust/detildestr-alllibs, r=brson
r? @brson
Diffstat (limited to 'src/libstd')
52 files changed, 775 insertions, 765 deletions
diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index e087b3d1774..e5689158601 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -16,10 +16,9 @@ use iter::Iterator; use mem; use option::{Option, Some, None}; use slice::{ImmutableVector, MutableVector, Vector}; -use str::OwnedStr; -use str::Str; -use str::{StrAllocating, StrSlice}; +use str::{OwnedStr, Str, StrAllocating, StrSlice}; use str; +use strbuf::StrBuf; use to_str::{IntoStr}; use vec::Vec; @@ -249,7 +248,7 @@ impl OwnedAsciiCast for ~[u8] { } } -impl OwnedAsciiCast for ~str { +impl OwnedAsciiCast for StrBuf { #[inline] fn is_ascii(&self) -> bool { self.as_slice().is_ascii() @@ -257,7 +256,7 @@ impl OwnedAsciiCast for ~str { #[inline] unsafe fn into_ascii_nocheck(self) -> Vec<Ascii> { - let v: ~[u8] = mem::transmute(self); + let v: Vec<u8> = mem::transmute(self); v.into_ascii_nocheck() } } @@ -314,17 +313,18 @@ impl<'a> AsciiStr for &'a [Ascii] { impl IntoStr for ~[Ascii] { #[inline] - fn into_str(self) -> ~str { - unsafe { mem::transmute(self) } + fn into_str(self) -> StrBuf { + let vector: Vec<Ascii> = self.as_slice().iter().map(|x| *x).collect(); + vector.into_str() } } impl IntoStr for Vec<Ascii> { #[inline] - fn into_str(self) -> ~str { + fn into_str(self) -> StrBuf { unsafe { let s: &str = mem::transmute(self.as_slice()); - s.to_owned() + s.to_strbuf() } } } @@ -346,12 +346,12 @@ pub trait OwnedStrAsciiExt { /// Convert the string to ASCII upper case: /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', /// but non-ASCII letters are unchanged. - fn into_ascii_upper(self) -> ~str; + fn into_ascii_upper(self) -> StrBuf; /// Convert the string to ASCII lower case: /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', /// but non-ASCII letters are unchanged. - fn into_ascii_lower(self) -> ~str; + fn into_ascii_lower(self) -> StrBuf; } /// Extension methods for ASCII-subset only operations on string slices @@ -359,12 +359,12 @@ pub trait StrAsciiExt { /// Makes a copy of the string in ASCII upper case: /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', /// but non-ASCII letters are unchanged. - fn to_ascii_upper(&self) -> ~str; + fn to_ascii_upper(&self) -> StrBuf; /// Makes a copy of the string in ASCII lower case: /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', /// but non-ASCII letters are unchanged. - fn to_ascii_lower(&self) -> ~str; + fn to_ascii_lower(&self) -> StrBuf; /// Check that two strings are an ASCII case-insensitive match. /// Same as `to_ascii_lower(a) == to_ascii_lower(b)`, @@ -374,12 +374,12 @@ pub trait StrAsciiExt { impl<'a> StrAsciiExt for &'a str { #[inline] - fn to_ascii_upper(&self) -> ~str { + fn to_ascii_upper(&self) -> StrBuf { unsafe { str_copy_map_bytes(*self, ASCII_UPPER_MAP) } } #[inline] - fn to_ascii_lower(&self) -> ~str { + fn to_ascii_lower(&self) -> StrBuf { unsafe { str_copy_map_bytes(*self, ASCII_LOWER_MAP) } } @@ -394,36 +394,36 @@ impl<'a> StrAsciiExt for &'a str { } } -impl OwnedStrAsciiExt for ~str { +impl OwnedStrAsciiExt for StrBuf { #[inline] - fn into_ascii_upper(self) -> ~str { + fn into_ascii_upper(self) -> StrBuf { unsafe { str_map_bytes(self, ASCII_UPPER_MAP) } } #[inline] - fn into_ascii_lower(self) -> ~str { + fn into_ascii_lower(self) -> StrBuf { unsafe { str_map_bytes(self, ASCII_LOWER_MAP) } } } #[inline] -unsafe fn str_map_bytes(string: ~str, map: &'static [u8]) -> ~str { +unsafe fn str_map_bytes(string: StrBuf, map: &'static [u8]) -> StrBuf { let mut bytes = string.into_bytes(); for b in bytes.mut_iter() { *b = map[*b as uint]; } - str::raw::from_utf8_owned(bytes) + str::from_utf8(bytes.as_slice()).unwrap().to_strbuf() } #[inline] -unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> ~str { - let mut s = string.to_owned(); - for b in str::raw::as_owned_vec(&mut s).mut_iter() { +unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> StrBuf { + let mut s = string.to_strbuf(); + for b in s.as_mut_bytes().mut_iter() { *b = map[*b as uint]; } - s + s.into_strbuf() } static ASCII_LOWER_MAP: &'static [u8] = &[ @@ -552,15 +552,17 @@ mod tests { assert_eq!("( ;".to_ascii(), v2ascii!([40, 32, 59])); // FIXME: #5475 borrowchk error, owned vectors do not live long enough // if chained-from directly - let v = box [40u8, 32u8, 59u8]; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59])); - let v = "( ;".to_owned(); assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59])); + let v = box [40u8, 32u8, 59u8]; + assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59])); + let v = "( ;".to_strbuf(); + assert_eq!(v.as_slice().to_ascii(), v2ascii!([40, 32, 59])); - assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_owned()); - assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_owned()); + assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_strbuf()); + assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_strbuf()); - assert_eq!("".to_ascii().to_lower().into_str(), "".to_owned()); - assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_owned()); - assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_owned()); + assert_eq!("".to_ascii().to_lower().into_str(), "".to_strbuf()); + assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_strbuf()); + assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_strbuf()); assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii())); @@ -572,16 +574,16 @@ mod tests { #[test] fn test_ascii_vec_ng() { - assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_owned()); - assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_owned()); - assert_eq!("".to_ascii().to_lower().into_str(), "".to_owned()); - assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_owned()); - assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_owned()); + assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_strbuf()); + assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_strbuf()); + assert_eq!("".to_ascii().to_lower().into_str(), "".to_strbuf()); + assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_strbuf()); + assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_strbuf()); } #[test] fn test_owned_ascii_vec() { - assert_eq!(("( ;".to_owned()).into_ascii(), vec2ascii![40, 32, 59]); + assert_eq!(("( ;".to_strbuf()).into_ascii(), vec2ascii![40, 32, 59]); assert_eq!((box [40u8, 32u8, 59u8]).into_ascii(), vec2ascii![40, 32, 59]); } @@ -593,8 +595,8 @@ mod tests { #[test] fn test_ascii_into_str() { - assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_owned()); - assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_owned()); + assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_strbuf()); + assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_strbuf()); } #[test] @@ -641,70 +643,70 @@ mod tests { assert_eq!((vec![40u8, 32u8, 59u8]).into_ascii_opt(), Some(vec2ascii![40, 32, 59])); assert_eq!((vec![127u8, 128u8, 255u8]).into_ascii_opt(), None); - assert_eq!(("( ;".to_owned()).into_ascii_opt(), Some(vec2ascii![40, 32, 59])); - assert_eq!(("zoä华".to_owned()).into_ascii_opt(), None); + assert_eq!(("( ;".to_strbuf()).into_ascii_opt(), Some(vec2ascii![40, 32, 59])); + assert_eq!(("zoä华".to_strbuf()).into_ascii_opt(), None); } #[test] fn test_to_ascii_upper() { - assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), "URL()URL()URL()üRL".to_owned()); - assert_eq!("hıKß".to_ascii_upper(), "HıKß".to_owned()); + assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), "URL()URL()URL()üRL".to_strbuf()); + assert_eq!("hıKß".to_ascii_upper(), "HıKß".to_strbuf()); let mut i = 0; while i <= 500 { let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 } else { i }; - assert_eq!(from_char(from_u32(i).unwrap()).to_ascii_upper(), - from_char(from_u32(upper).unwrap())) + assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_upper(), + from_char(from_u32(upper).unwrap()).to_strbuf()) i += 1; } } #[test] fn test_to_ascii_lower() { - assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), "url()url()url()Ürl".to_owned()); + assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), "url()url()url()Ürl".to_strbuf()); // Dotted capital I, Kelvin sign, Sharp S. - assert_eq!("HİKß".to_ascii_lower(), "hİKß".to_owned()); + assert_eq!("HİKß".to_ascii_lower(), "hİKß".to_strbuf()); let mut i = 0; while i <= 500 { let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } else { i }; - assert_eq!(from_char(from_u32(i).unwrap()).to_ascii_lower(), - from_char(from_u32(lower).unwrap())) + assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_lower(), + from_char(from_u32(lower).unwrap()).to_strbuf()) i += 1; } } #[test] fn test_into_ascii_upper() { - assert_eq!(("url()URL()uRl()ürl".to_owned()).into_ascii_upper(), - "URL()URL()URL()üRL".to_owned()); - assert_eq!(("hıKß".to_owned()).into_ascii_upper(), "HıKß".to_owned()); + assert_eq!(("url()URL()uRl()ürl".to_strbuf()).into_ascii_upper(), + "URL()URL()URL()üRL".to_strbuf()); + assert_eq!(("hıKß".to_strbuf()).into_ascii_upper(), "HıKß".to_strbuf()); let mut i = 0; while i <= 500 { let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 } else { i }; - assert_eq!(from_char(from_u32(i).unwrap()).into_ascii_upper(), - from_char(from_u32(upper).unwrap())) + assert_eq!(from_char(from_u32(i).unwrap()).to_strbuf().into_ascii_upper(), + from_char(from_u32(upper).unwrap()).to_strbuf()) i += 1; } } #[test] fn test_into_ascii_lower() { - assert_eq!(("url()URL()uRl()Ürl".to_owned()).into_ascii_lower(), - "url()url()url()Ürl".to_owned()); + assert_eq!(("url()URL()uRl()Ürl".to_strbuf()).into_ascii_lower(), + "url()url()url()Ürl".to_strbuf()); // Dotted capital I, Kelvin sign, Sharp S. - assert_eq!(("HİKß".to_owned()).into_ascii_lower(), "hİKß".to_owned()); + assert_eq!(("HİKß".to_strbuf()).into_ascii_lower(), "hİKß".to_strbuf()); let mut i = 0; while i <= 500 { let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } else { i }; - assert_eq!(from_char(from_u32(i).unwrap()).into_ascii_lower(), - from_char(from_u32(lower).unwrap())) + assert_eq!(from_char(from_u32(i).unwrap()).to_strbuf().into_ascii_lower(), + from_char(from_u32(lower).unwrap()).to_strbuf()) i += 1; } } @@ -724,8 +726,11 @@ mod tests { let c = i; let lower = if 'A' as u32 <= c && c <= 'Z' as u32 { c + 'a' as u32 - 'A' as u32 } else { c }; - assert!(from_char(from_u32(i).unwrap()). - eq_ignore_ascii_case(from_char(from_u32(lower).unwrap()))); + assert!(from_char(from_u32(i).unwrap()).as_slice() + .eq_ignore_ascii_case( + from_char( + from_u32(lower) + .unwrap()).as_slice())); i += 1; } } @@ -733,12 +738,12 @@ mod tests { #[test] fn test_to_str() { let s = Ascii{ chr: 't' as u8 }.to_str(); - assert_eq!(s, "t".to_owned()); + assert_eq!(s, "t".to_strbuf()); } #[test] fn test_show() { let c = Ascii { chr: 't' as u8 }; - assert_eq!(format!("{}", c), "t".to_owned()); + assert_eq!(format_strbuf!("{}", c), "t".to_strbuf()); } } diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index 0c529ee4d96..4622c0934fe 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -323,29 +323,6 @@ impl<'a> ToCStr for &'a str { } } -impl ToCStr for ~str { - #[inline] - fn to_c_str(&self) -> CString { - self.as_bytes().to_c_str() - } - - #[inline] - unsafe fn to_c_str_unchecked(&self) -> CString { - self.as_bytes().to_c_str_unchecked() - } - - #[inline] - fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { - self.as_bytes().with_c_str(f) - } - - #[inline] - unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T { - self.as_bytes().with_c_str_unchecked(f) - } -} - - impl ToCStr for StrBuf { #[inline] fn to_c_str(&self) -> CString { diff --git a/src/libstd/comm/mod.rs b/src/libstd/comm/mod.rs index fd5b92ba469..b2521f2978a 100644 --- a/src/libstd/comm/mod.rs +++ b/src/libstd/comm/mod.rs @@ -990,7 +990,7 @@ mod test { pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => from_str::<uint>(val).unwrap(), + Some(val) => from_str::<uint>(val.as_slice()).unwrap(), None => 1, } } @@ -1523,7 +1523,7 @@ mod sync_tests { pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => from_str::<uint>(val).unwrap(), + Some(val) => from_str::<uint>(val.as_slice()).unwrap(), None => 1, } } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 86b77a46a39..db23a5f1720 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -27,9 +27,9 @@ general case. The `format!` macro is intended to be familiar to those coming from C's printf/fprintf functions or Python's `str.format` function. In its current -revision, the `format!` macro returns a `~str` type which is the result of the -formatting. In the future it will also be able to pass in a stream to format -arguments directly while performing minimal allocations. +revision, the `format!` macro returns a `StrBuf` type which is the result of +the formatting. In the future it will also be able to pass in a stream to +format arguments directly while performing minimal allocations. Some examples of the `format!` extension are: @@ -282,7 +282,7 @@ use std::io; # #[allow(unused_must_use)] # fn main() { -format_args!(fmt::format, "this returns {}", "~str"); +format_args!(fmt::format, "this returns {}", "StrBuf"); let some_writer: &mut io::Writer = &mut io::stdout(); format_args!(|args| { write!(some_writer, "{}", args) }, "print with a {}", "closure"); @@ -488,7 +488,7 @@ use io; use option::None; use repr; use result::{Ok, Err}; -use str::{StrAllocating}; +use str::{Str, StrAllocating}; use str; use strbuf::StrBuf; use slice::Vector; @@ -545,10 +545,10 @@ pub trait Poly { /// let s = format_args!(fmt::format, "Hello, {}!", "world"); /// assert_eq!(s, "Hello, world!".to_owned()); /// ``` -pub fn format(args: &Arguments) -> ~str { +pub fn format(args: &Arguments) -> StrBuf{ let mut output = io::MemWriter::new(); let _ = write!(&mut output, "{}", args); - str::from_utf8(output.unwrap().as_slice()).unwrap().to_owned() + str::from_utf8(output.unwrap().as_slice()).unwrap().into_strbuf() } /// Temporary transition utility @@ -572,7 +572,7 @@ impl<T> Poly for T { // this allocation of a new string _ => { let s = repr::repr_to_str(self); - f.pad(s) + f.pad(s.as_slice()) } } } diff --git a/src/libstd/hash/mod.rs b/src/libstd/hash/mod.rs index a510aa90343..1dad1667ebd 100644 --- a/src/libstd/hash/mod.rs +++ b/src/libstd/hash/mod.rs @@ -23,7 +23,7 @@ * #[deriving(Hash)] * struct Person { * id: uint, - * name: ~str, + * name: StrBuf, * phone: u64, * } * @@ -43,7 +43,7 @@ * * struct Person { * id: uint, - * name: ~str, + * name: StrBuf, * phone: u64, * } * @@ -145,13 +145,6 @@ impl<'a, S: Writer> Hash<S> for &'a str { } } -impl<S: Writer> Hash<S> for ~str { - #[inline] - fn hash(&self, state: &mut S) { - self.as_slice().hash(state); - } -} - macro_rules! impl_hash_tuple( () => ( impl<S: Writer> Hash<S> for () { diff --git a/src/libstd/hash/sip.rs b/src/libstd/hash/sip.rs index 58e0f4c717d..1434e3c7ad7 100644 --- a/src/libstd/hash/sip.rs +++ b/src/libstd/hash/sip.rs @@ -458,12 +458,12 @@ mod tests { let mut state_inc = SipState::new_with_keys(k0, k1); let mut state_full = SipState::new_with_keys(k0, k1); - fn to_hex_str(r: &[u8, ..8]) -> ~str { + fn to_hex_str(r: &[u8, ..8]) -> StrBuf { let mut s = StrBuf::new(); for b in r.iter() { - s.push_str((*b as uint).to_str_radix(16u)); + s.push_str((*b as uint).to_str_radix(16u).as_slice()); } - s.into_owned() + s } fn result_bytes(h: u64) -> ~[u8] { @@ -478,13 +478,13 @@ mod tests { ] } - fn result_str(h: u64) -> ~str { + fn result_str(h: u64) -> StrBuf { let r = result_bytes(h); let mut s = StrBuf::new(); for b in r.iter() { - s.push_str((*b as uint).to_str_radix(16u)); + s.push_str((*b as uint).to_str_radix(16u).as_slice()); } - s.into_owned() + s } while t < 64 { @@ -636,7 +636,6 @@ officia deserunt mollit anim id est laborum."; struct Compound { x: u8, y: u64, - z: ~str, } #[bench] @@ -644,7 +643,6 @@ officia deserunt mollit anim id est laborum."; let compound = Compound { x: 1, y: 2, - z: "foobarbaz".to_owned(), }; b.iter(|| { assert_eq!(hash(&compound), 15783192367317361799); diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 2880365cf34..c7b0d660624 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -537,9 +537,9 @@ mod test { fn test_read_line() { let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc"))); let mut reader = BufferedReader::with_capacity(2, in_buf); - assert_eq!(reader.read_line(), Ok("a\n".to_owned())); - assert_eq!(reader.read_line(), Ok("b\n".to_owned())); - assert_eq!(reader.read_line(), Ok("c".to_owned())); + assert_eq!(reader.read_line(), Ok("a\n".to_strbuf())); + assert_eq!(reader.read_line(), Ok("b\n".to_strbuf())); + assert_eq!(reader.read_line(), Ok("c".to_strbuf())); assert!(reader.read_line().is_err()); } @@ -548,9 +548,9 @@ mod test { let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc"))); let mut reader = BufferedReader::with_capacity(2, in_buf); let mut it = reader.lines(); - assert_eq!(it.next(), Some(Ok("a\n".to_owned()))); - assert_eq!(it.next(), Some(Ok("b\n".to_owned()))); - assert_eq!(it.next(), Some(Ok("c".to_owned()))); + assert_eq!(it.next(), Some(Ok("a\n".to_strbuf()))); + assert_eq!(it.next(), Some(Ok("b\n".to_strbuf()))); + assert_eq!(it.next(), Some(Ok("c".to_strbuf()))); assert_eq!(it.next(), None); } diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index a497ffd40a0..d8edd6517d5 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -745,7 +745,8 @@ mod test { pub fn tmpdir() -> TempDir { use os; use rand; - let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>())); + let ret = os::tmpdir().join( + format_strbuf!("rust-{}", rand::random::<u32>())); check!(io::fs::mkdir(&ret, io::UserRWX)); TempDir(ret) } @@ -854,7 +855,7 @@ mod test { } check!(unlink(filename)); let read_str = str::from_utf8(read_mem).unwrap(); - assert!(read_str == final_msg.to_owned()); + assert!(read_str.as_slice() == final_msg.as_slice()); }) iotest!(fn file_test_io_seek_shakedown() { @@ -952,10 +953,10 @@ mod test { check!(mkdir(dir, io::UserRWX)); let prefix = "foo"; for n in range(0,3) { - let f = dir.join(format!("{}.txt", n)); + let f = dir.join(format_strbuf!("{}.txt", n)); let mut w = check!(File::create(&f)); - let msg_str = (prefix + n.to_str().to_owned()).to_owned(); - let msg = msg_str.as_bytes(); + let msg_str = format!("{}{}", prefix, n.to_str()); + let msg = msg_str.as_slice().as_bytes(); check!(w.write(msg)); } let files = check!(readdir(dir)); @@ -967,7 +968,7 @@ mod test { let read_str = str::from_utf8(mem).unwrap(); let expected = match n { None|Some("") => fail!("really shouldn't happen.."), - Some(n) => prefix+n + Some(n) => format!("{}{}", prefix, n), }; assert_eq!(expected.as_slice(), read_str); } @@ -1039,7 +1040,7 @@ mod test { let tmpdir = tmpdir(); let mut dirpath = tmpdir.path().clone(); - dirpath.push(format!("test-가一ー你好")); + dirpath.push(format_strbuf!("test-가一ー你好")); check!(mkdir(&dirpath, io::UserRWX)); assert!(dirpath.is_dir()); @@ -1056,7 +1057,7 @@ mod test { let tmpdir = tmpdir(); let unicode = tmpdir.path(); - let unicode = unicode.join(format!("test-각丁ー再见")); + let unicode = unicode.join(format_strbuf!("test-각丁ー再见")); check!(mkdir(&unicode, io::UserRWX)); assert!(unicode.exists()); assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists()); diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 92b546d5770..c1e228cd693 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -497,7 +497,7 @@ mod test { writer.write_line("testing").unwrap(); writer.write_str("testing").unwrap(); let mut r = BufReader::new(writer.get_ref()); - assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_owned()); + assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_strbuf()); } #[test] @@ -507,7 +507,7 @@ mod test { writer.write_char('\n').unwrap(); writer.write_char('ệ').unwrap(); let mut r = BufReader::new(writer.get_ref()); - assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_owned()); + assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_strbuf()); } #[test] diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index a043722581b..50bd3e7067c 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -76,7 +76,7 @@ Some examples of obvious things you might want to do let path = Path::new("message.txt"); let mut file = BufferedReader::new(File::open(&path)); - let lines: Vec<~str> = file.lines().map(|x| x.unwrap()).collect(); + let lines: Vec<StrBuf> = file.lines().map(|x| x.unwrap()).collect(); ``` * Make a simple TCP client connection and request @@ -228,6 +228,7 @@ use result::{Ok, Err, Result}; use slice::{Vector, MutableVector, ImmutableVector}; use str::{StrSlice, StrAllocating}; use str; +use strbuf::StrBuf; use uint; use vec::Vec; @@ -292,7 +293,7 @@ pub struct IoError { /// A human-readable description about the error pub desc: &'static str, /// Detailed information about this error, not always available - pub detail: Option<~str> + pub detail: Option<StrBuf> } impl IoError { @@ -364,7 +365,11 @@ impl IoError { IoError { kind: kind, desc: desc, - detail: if detail {Some(os::error_string(errno))} else {None}, + detail: if detail { + Some(os::error_string(errno)) + } else { + None + }, } } @@ -490,8 +495,10 @@ pub trait Reader { /// bytes are read. fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> { if min > buf.len() { - return Err(IoError { detail: Some("the buffer is too short".to_owned()), - ..standard_error(InvalidInput) }); + return Err(IoError { + detail: Some("the buffer is too short".to_strbuf()), + ..standard_error(InvalidInput) + }); } let mut read = 0; while read < min { @@ -556,8 +563,10 @@ pub trait Reader { /// bytes are read. fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> { if min > len { - return Err(IoError { detail: Some("the buffer is too short".to_owned()), - ..standard_error(InvalidInput) }); + return Err(IoError { + detail: Some("the buffer is too short".to_strbuf()), + ..standard_error(InvalidInput) + }); } let start_len = buf.len(); @@ -623,10 +632,10 @@ pub trait Reader { /// This function returns all of the same errors as `read_to_end` with an /// additional error if the reader's contents are not a valid sequence of /// UTF-8 bytes. - fn read_to_str(&mut self) -> IoResult<~str> { + fn read_to_str(&mut self) -> IoResult<StrBuf> { self.read_to_end().and_then(|s| { match str::from_utf8(s.as_slice()) { - Some(s) => Ok(s.to_owned()), + Some(s) => Ok(s.to_strbuf()), None => Err(standard_error(InvalidInput)), } }) @@ -1235,8 +1244,8 @@ pub struct Lines<'r, T> { buffer: &'r mut T, } -impl<'r, T: Buffer> Iterator<IoResult<~str>> for Lines<'r, T> { - fn next(&mut self) -> Option<IoResult<~str>> { +impl<'r, T: Buffer> Iterator<IoResult<StrBuf>> for Lines<'r, T> { + fn next(&mut self) -> Option<IoResult<StrBuf>> { match self.buffer.read_line() { Ok(x) => Some(Ok(x)), Err(IoError { kind: EndOfFile, ..}) => None, @@ -1321,10 +1330,10 @@ pub trait Buffer: Reader { /// /// Additionally, this function can fail if the line of input read is not a /// valid UTF-8 sequence of bytes. - fn read_line(&mut self) -> IoResult<~str> { + fn read_line(&mut self) -> IoResult<StrBuf> { self.read_until('\n' as u8).and_then(|line| match str::from_utf8(line.as_slice()) { - Some(s) => Ok(s.to_owned()), + Some(s) => Ok(s.to_strbuf()), None => Err(standard_error(InvalidInput)), } ) diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index f469c419e8e..4bf71b5480e 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -445,8 +445,8 @@ mod test { #[test] fn ipv6_addr_to_str() { let a1 = Ipv6Addr(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280); - assert!(a1.to_str() == "::ffff:192.0.2.128".to_owned() || - a1.to_str() == "::FFFF:192.0.2.128".to_owned()); - assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_owned()); + assert!(a1.to_str() == "::ffff:192.0.2.128".to_strbuf() || + a1.to_str() == "::FFFF:192.0.2.128".to_strbuf()); + assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_strbuf()); } } diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index dec68b9d89e..ac17bc1de13 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -434,7 +434,7 @@ mod test { let socket_addr = next_test_ip4(); let ip_str = socket_addr.ip.to_str(); let port = socket_addr.port; - let listener = TcpListener::bind(ip_str, port); + let listener = TcpListener::bind(ip_str.as_slice(), port); let mut acceptor = listener.listen(); spawn(proc() { @@ -452,7 +452,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut stream = TcpStream::connect("localhost", addr.port); @@ -469,7 +469,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut stream = TcpStream::connect("127.0.0.1", addr.port); @@ -486,7 +486,7 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut stream = TcpStream::connect("::1", addr.port); @@ -503,10 +503,10 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); stream.write([99]).unwrap(); }); @@ -520,10 +520,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); stream.write([99]).unwrap(); }); @@ -537,10 +537,10 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -554,10 +554,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -571,10 +571,10 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -596,10 +596,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -621,10 +621,10 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -648,10 +648,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let _stream = TcpStream::connect(ip_str, port); + let _stream = TcpStream::connect(ip_str.as_slice(), port); // Close }); @@ -676,11 +676,11 @@ mod test { let ip_str = addr.ip.to_str(); let port = addr.port; let max = 10u; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { for _ in range(0, max) { - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); stream.write([99]).unwrap(); } }); @@ -697,11 +697,11 @@ mod test { let ip_str = addr.ip.to_str(); let port = addr.port; let max = 10u; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { for _ in range(0, max) { - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); stream.write([99]).unwrap(); } }); @@ -718,7 +718,7 @@ mod test { let ip_str = addr.ip.to_str(); let port = addr.port; static MAX: int = 10; - let acceptor = TcpListener::bind(ip_str, port).listen(); + let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut acceptor = acceptor; @@ -743,7 +743,7 @@ mod test { spawn(proc() { debug!("connecting"); - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); // Connect again before writing connect(i + 1, addr); debug!("writing"); @@ -757,7 +757,7 @@ mod test { let ip_str = addr.ip.to_str(); let port = addr.port; static MAX: int = 10; - let acceptor = TcpListener::bind(ip_str, port).listen(); + let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut acceptor = acceptor; @@ -782,7 +782,7 @@ mod test { spawn(proc() { debug!("connecting"); - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); // Connect again before writing connect(i + 1, addr); debug!("writing"); @@ -796,7 +796,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let acceptor = TcpListener::bind(ip_str, port).listen(); + let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut acceptor = acceptor; @@ -821,7 +821,7 @@ mod test { spawn(proc() { debug!("connecting"); - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); // Connect again before writing connect(i + 1, addr); debug!("writing"); @@ -835,7 +835,7 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let acceptor = TcpListener::bind(ip_str, port).listen(); + let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut acceptor = acceptor; @@ -860,7 +860,7 @@ mod test { spawn(proc() { debug!("connecting"); - let mut stream = TcpStream::connect(ip_str, port); + let mut stream = TcpStream::connect(ip_str.as_slice(), port); // Connect again before writing connect(i + 1, addr); debug!("writing"); @@ -872,7 +872,7 @@ mod test { pub fn socket_name(addr: SocketAddr) { let ip_str = addr.ip.to_str(); let port = addr.port; - let mut listener = TcpListener::bind(ip_str, port).unwrap(); + let mut listener = TcpListener::bind(ip_str.as_slice(), port).unwrap(); // Make sure socket_name gives // us the socket we binded to. @@ -884,13 +884,13 @@ mod test { pub fn peer_name(addr: SocketAddr) { let ip_str = addr.ip.to_str(); let port = addr.port; - let acceptor = TcpListener::bind(ip_str, port).listen(); + let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { let mut acceptor = acceptor; acceptor.accept().unwrap(); }); - let stream = TcpStream::connect(ip_str, port); + let stream = TcpStream::connect(ip_str.as_slice(), port); assert!(stream.is_ok()); let mut stream = stream.unwrap(); @@ -920,7 +920,7 @@ mod test { let (tx, rx) = channel(); spawn(proc() { let ip_str = addr.ip.to_str(); - let mut srv = TcpListener::bind(ip_str, port).listen().unwrap(); + let mut srv = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); tx.send(()); let mut cl = srv.accept().unwrap(); cl.write([10]).unwrap(); @@ -931,7 +931,7 @@ mod test { rx.recv(); let ip_str = addr.ip.to_str(); - let mut c = TcpStream::connect(ip_str, port).unwrap(); + let mut c = TcpStream::connect(ip_str.as_slice(), port).unwrap(); let mut b = [0, ..10]; assert_eq!(c.read(b), Ok(1)); c.write([1]).unwrap(); @@ -942,9 +942,9 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let listener = TcpListener::bind(ip_str, port).unwrap().listen(); + let listener = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen(); assert!(listener.is_ok()); - match TcpListener::bind(ip_str, port).listen() { + match TcpListener::bind(ip_str.as_slice(), port).listen() { Ok(..) => fail!(), Err(e) => { assert!(e.kind == ConnectionRefused || e.kind == OtherIoError); @@ -960,14 +960,14 @@ mod test { spawn(proc() { let ip_str = addr.ip.to_str(); rx.recv(); - let _stream = TcpStream::connect(ip_str, port).unwrap(); + let _stream = TcpStream::connect(ip_str.as_slice(), port).unwrap(); // Close rx.recv(); }); { let ip_str = addr.ip.to_str(); - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); tx.send(()); { let _stream = acceptor.accept().unwrap(); @@ -976,17 +976,17 @@ mod test { } // Close listener } - let _listener = TcpListener::bind(addr.ip.to_str(), port); + let _listener = TcpListener::bind(addr.ip.to_str().as_slice(), port); }) iotest!(fn tcp_clone_smoke() { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port); + let mut s = TcpStream::connect(ip_str.as_slice(), port); let mut buf = [0, 0]; assert_eq!(s.read(buf), Ok(1)); assert_eq!(buf[0], 1); @@ -1014,12 +1014,12 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); let (tx1, rx) = channel(); let tx2 = tx1.clone(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port); + let mut s = TcpStream::connect(ip_str.as_slice(), port); s.write([1]).unwrap(); rx.recv(); s.write([2]).unwrap(); @@ -1048,10 +1048,10 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut acceptor = TcpListener::bind(ip_str, port).listen(); + let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port); + let mut s = TcpStream::connect(ip_str.as_slice(), port); let mut buf = [0, 1]; s.read(buf).unwrap(); s.read(buf).unwrap(); @@ -1077,7 +1077,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let a = TcpListener::bind(ip_str, port).unwrap().listen(); + let a = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen(); spawn(proc() { let mut a = a; let mut c = a.accept().unwrap(); @@ -1085,7 +1085,7 @@ mod test { c.write([1]).unwrap(); }); - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); assert!(s.obj.close_write().is_ok()); assert!(s.write([1]).is_err()); assert_eq!(s.read_to_end(), Ok(vec!(1))); @@ -1095,7 +1095,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut a = TcpListener::bind(ip_str, port).unwrap().listen().unwrap(); + let mut a = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen().unwrap(); a.set_timeout(Some(10)); @@ -1114,7 +1114,8 @@ mod test { if !cfg!(target_os = "freebsd") { let (tx, rx) = channel(); spawn(proc() { - tx.send(TcpStream::connect(addr.ip.to_str(), port).unwrap()); + tx.send(TcpStream::connect(addr.ip.to_str().as_slice(), + port).unwrap()); }); let _l = rx.recv(); for i in range(0, 1001) { @@ -1131,7 +1132,8 @@ mod test { // Unset the timeout and make sure that this always blocks. a.set_timeout(None); spawn(proc() { - drop(TcpStream::connect(addr.ip.to_str(), port).unwrap()); + drop(TcpStream::connect(addr.ip.to_str().as_slice(), + port).unwrap()); }); a.accept().unwrap(); }) @@ -1140,7 +1142,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let a = TcpListener::bind(ip_str, port).listen().unwrap(); + let a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (_tx, rx) = channel::<()>(); spawn(proc() { let mut a = a; @@ -1149,7 +1151,7 @@ mod test { }); let mut b = [0]; - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); let mut s2 = s.clone(); // closing should prevent reads/writes @@ -1178,7 +1180,7 @@ mod test { let addr = next_test_ip4(); let ip_str = addr.ip.to_str(); let port = addr.port; - let a = TcpListener::bind(ip_str, port).listen().unwrap(); + let a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (_tx, rx) = channel::<()>(); spawn(proc() { let mut a = a; @@ -1186,7 +1188,7 @@ mod test { let _ = rx.recv_opt(); }); - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); let s2 = s.clone(); let (tx, rx) = channel(); spawn(proc() { @@ -1205,10 +1207,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut a = TcpListener::bind(ip_str, port).listen().unwrap(); + let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); rx.recv(); assert!(s.write([0]).is_ok()); let _ = rx.recv_opt(); @@ -1239,10 +1241,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut a = TcpListener::bind(ip_str, port).listen().unwrap(); + let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); rx.recv(); let mut amt = 0; while amt < 100 * 128 * 1024 { @@ -1269,10 +1271,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut a = TcpListener::bind(ip_str, port).listen().unwrap(); + let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); rx.recv(); assert!(s.write([0]).is_ok()); let _ = rx.recv_opt(); @@ -1298,10 +1300,10 @@ mod test { let addr = next_test_ip6(); let ip_str = addr.ip.to_str(); let port = addr.port; - let mut a = TcpListener::bind(ip_str, port).listen().unwrap(); + let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); spawn(proc() { - let mut s = TcpStream::connect(ip_str, port).unwrap(); + let mut s = TcpStream::connect(ip_str.as_slice(), port).unwrap(); rx.recv(); assert_eq!(s.write([0]), Ok(())); let _ = rx.recv_opt(); diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index fc760e6fe4c..7d84530282f 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -583,11 +583,11 @@ mod tests { } }) - pub fn read_all(input: &mut Reader) -> ~str { + pub fn read_all(input: &mut Reader) -> StrBuf { input.read_to_str().unwrap() } - pub fn run_output(cmd: Command) -> ~str { + pub fn run_output(cmd: Command) -> StrBuf { let p = cmd.spawn(); assert!(p.is_ok()); let mut p = p.unwrap(); @@ -601,7 +601,7 @@ mod tests { iotest!(fn stdout_works() { let mut cmd = Command::new("echo"); cmd.arg("foobar").stdout(CreatePipe(false, true)); - assert_eq!(run_output(cmd), "foobar\n".to_owned()); + assert_eq!(run_output(cmd), "foobar\n".to_strbuf()); }) #[cfg(unix, not(target_os="android"))] @@ -610,7 +610,7 @@ mod tests { cmd.arg("-c").arg("pwd") .cwd(&Path::new("/")) .stdout(CreatePipe(false, true)); - assert_eq!(run_output(cmd), "/\n".to_owned()); + assert_eq!(run_output(cmd), "/\n".to_strbuf()); }) #[cfg(unix, not(target_os="android"))] @@ -624,7 +624,7 @@ mod tests { drop(p.stdin.take()); let out = read_all(p.stdout.get_mut_ref() as &mut Reader); assert!(p.wait().unwrap().success()); - assert_eq!(out, "foobar\n".to_owned()); + assert_eq!(out, "foobar\n".to_strbuf()); }) #[cfg(not(target_os="android"))] @@ -682,7 +682,7 @@ mod tests { let output_str = str::from_utf8(output.as_slice()).unwrap(); assert!(status.success()); - assert_eq!(output_str.trim().to_owned(), "hello".to_owned()); + assert_eq!(output_str.trim().to_strbuf(), "hello".to_strbuf()); // FIXME #7224 if !running_on_valgrind() { assert_eq!(error, Vec::new()); @@ -719,7 +719,7 @@ mod tests { let output_str = str::from_utf8(output.as_slice()).unwrap(); assert!(status.success()); - assert_eq!(output_str.trim().to_owned(), "hello".to_owned()); + assert_eq!(output_str.trim().to_strbuf(), "hello".to_strbuf()); // FIXME #7224 if !running_on_valgrind() { assert_eq!(error, Vec::new()); @@ -749,9 +749,9 @@ mod tests { let prog = pwd_cmd().spawn().unwrap(); let output = str::from_utf8(prog.wait_with_output().unwrap() - .output.as_slice()).unwrap().to_owned(); + .output.as_slice()).unwrap().to_strbuf(); let parent_dir = os::getcwd(); - let child_dir = Path::new(output.trim()); + let child_dir = Path::new(output.as_slice().trim()); let parent_stat = parent_dir.stat().unwrap(); let child_stat = child_dir.stat().unwrap(); @@ -768,8 +768,8 @@ mod tests { let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap(); let output = str::from_utf8(prog.wait_with_output().unwrap() - .output.as_slice()).unwrap().to_owned(); - let child_dir = Path::new(output.trim()); + .output.as_slice()).unwrap().to_strbuf(); + let child_dir = Path::new(output.as_slice().trim().into_strbuf()); let parent_stat = parent_dir.stat().unwrap(); let child_stat = child_dir.stat().unwrap(); @@ -803,12 +803,14 @@ mod tests { let prog = env_cmd().spawn().unwrap(); let output = str::from_utf8(prog.wait_with_output().unwrap() - .output.as_slice()).unwrap().to_owned(); + .output.as_slice()).unwrap().to_strbuf(); let r = os::env(); for &(ref k, ref v) in r.iter() { // don't check windows magical empty-named variables - assert!(k.is_empty() || output.contains(format!("{}={}", *k, *v))); + assert!(k.is_empty() || + output.as_slice() + .contains(format!("{}={}", *k, *v).as_slice())); } }) #[cfg(target_os="android")] @@ -819,14 +821,20 @@ mod tests { let mut prog = env_cmd().spawn().unwrap(); let output = str::from_utf8(prog.wait_with_output() .unwrap().output.as_slice()) - .unwrap().to_owned(); + .unwrap().to_strbuf(); let r = os::env(); for &(ref k, ref v) in r.iter() { // don't check android RANDOM variables - if *k != "RANDOM".to_owned() { - assert!(output.contains(format!("{}={}", *k, *v)) || - output.contains(format!("{}=\'{}\'", *k, *v))); + if *k != "RANDOM".to_strbuf() { + assert!(output.as_slice() + .contains(format!("{}={}", + *k, + *v).as_slice()) || + output.as_slice() + .contains(format!("{}=\'{}\'", + *k, + *v).as_slice())); } } }) @@ -835,9 +843,9 @@ mod tests { let new_env = box [("RUN_TEST_NEW_ENV", "123")]; let prog = env_cmd().env(new_env).spawn().unwrap(); let result = prog.wait_with_output().unwrap(); - let output = str::from_utf8_lossy(result.output.as_slice()).into_owned(); + let output = str::from_utf8_lossy(result.output.as_slice()).into_strbuf(); - assert!(output.contains("RUN_TEST_NEW_ENV=123"), + assert!(output.as_slice().contains("RUN_TEST_NEW_ENV=123"), "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output); }) diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 991f3992dd1..3a103651d63 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -409,7 +409,7 @@ mod tests { set_stdout(box w); println!("hello!"); }); - assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_owned()); + assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_strbuf()); }) iotest!(fn capture_stderr() { @@ -422,6 +422,6 @@ mod tests { fail!("my special message"); }); let s = r.read_to_str().unwrap(); - assert!(s.contains("my special message")); + assert!(s.as_slice().contains("my special message")); }) } diff --git a/src/libstd/io/tempfile.rs b/src/libstd/io/tempfile.rs index b4fb95c8af7..806df838c91 100644 --- a/src/libstd/io/tempfile.rs +++ b/src/libstd/io/tempfile.rs @@ -42,10 +42,11 @@ impl TempDir { static mut CNT: atomics::AtomicUint = atomics::INIT_ATOMIC_UINT; for _ in range(0u, 1000) { - let filename = format!("rs-{}-{}-{}", - unsafe { libc::getpid() }, - unsafe { CNT.fetch_add(1, atomics::SeqCst) }, - suffix); + let filename = + format_strbuf!("rs-{}-{}-{}", + unsafe { libc::getpid() }, + unsafe { CNT.fetch_add(1, atomics::SeqCst) }, + suffix); let p = tmpdir.join(filename); match fs::mkdir(&p, io::UserRWX) { Err(..) => {} diff --git a/src/libstd/io/test.rs b/src/libstd/io/test.rs index dd874fecc52..de8a6f4beb5 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/io/test.rs @@ -67,14 +67,14 @@ pub fn next_test_unix() -> Path { // base port and pid are an attempt to be unique between multiple // test-runners of different configurations running on one // buildbot, the count is to be unique within this executable. - let string = format!("rust-test-unix-path-{}-{}-{}", - base_port(), - unsafe {libc::getpid()}, - unsafe {COUNT.fetch_add(1, Relaxed)}); + let string = format_strbuf!("rust-test-unix-path-{}-{}-{}", + base_port(), + unsafe {libc::getpid()}, + unsafe {COUNT.fetch_add(1, Relaxed)}); if cfg!(unix) { os::tmpdir().join(string) } else { - Path::new(r"\\.\pipe\" + string) + Path::new(format_strbuf!("{}{}", r"\\.\pipe\", string)) } } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index a9ec9c1ddc5..22ac397c702 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -47,9 +47,9 @@ //! for which the [`slice`](slice/index.html) module defines many //! methods. //! -//! UTF-8 strings, `~str` and `&str`, are built-in types, and the -//! standard library defines methods for them on a variety of traits -//! in the [`str`](str/index.html) module. Rust strings are immutable; +//! `&str`, a UTF-8 string, is a built-in type, and the standard library +//! defines methods for it on a variety of traits in the +//! [`str`](str/index.html) module. Rust strings are immutable; //! use the `StrBuf` type defined in [`strbuf`](strbuf/index.html) //! for a mutable string builder. //! @@ -284,4 +284,5 @@ mod std { // The test runner requires std::slice::Vector, so re-export std::slice just for it. #[cfg(test)] pub use slice; + #[cfg(test)] pub use strbuf; } diff --git a/src/libstd/local_data.rs b/src/libstd/local_data.rs index 1a971594837..8798c035fca 100644 --- a/src/libstd/local_data.rs +++ b/src/libstd/local_data.rs @@ -274,12 +274,12 @@ mod tests { #[test] fn test_tls_multitask() { - static my_key: Key<~str> = &Key; - my_key.replace(Some("parent data".to_owned())); + static my_key: Key<StrBuf> = &Key; + my_key.replace(Some("parent data".to_strbuf())); task::spawn(proc() { // TLS shouldn't carry over. assert!(my_key.get().is_none()); - my_key.replace(Some("child data".to_owned())); + my_key.replace(Some("child data".to_strbuf())); assert!(my_key.get().get_ref().as_slice() == "child data"); // should be cleaned up for us }); @@ -292,17 +292,17 @@ mod tests { #[test] fn test_tls_overwrite() { - static my_key: Key<~str> = &Key; - my_key.replace(Some("first data".to_owned())); - my_key.replace(Some("next data".to_owned())); // Shouldn't leak. + static my_key: Key<StrBuf> = &Key; + my_key.replace(Some("first data".to_strbuf())); + my_key.replace(Some("next data".to_strbuf())); // Shouldn't leak. assert!(my_key.get().unwrap().as_slice() == "next data"); } #[test] fn test_tls_pop() { - static my_key: Key<~str> = &Key; - my_key.replace(Some("weasel".to_owned())); - assert!(my_key.replace(None).unwrap() == "weasel".to_owned()); + static my_key: Key<StrBuf> = &Key; + my_key.replace(Some("weasel".to_strbuf())); + assert!(my_key.replace(None).unwrap() == "weasel".to_strbuf()); // Pop must remove the data from the map. assert!(my_key.replace(None).is_none()); } @@ -315,19 +315,19 @@ mod tests { // to get recorded as something within a rust stack segment. Then a // subsequent upcall (esp. for logging, think vsnprintf) would run on // a stack smaller than 1 MB. - static my_key: Key<~str> = &Key; + static my_key: Key<StrBuf> = &Key; task::spawn(proc() { - my_key.replace(Some("hax".to_owned())); + my_key.replace(Some("hax".to_strbuf())); }); } #[test] fn test_tls_multiple_types() { - static str_key: Key<~str> = &Key; + static str_key: Key<StrBuf> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; task::spawn(proc() { - str_key.replace(Some("string data".to_owned())); + str_key.replace(Some("string data".to_strbuf())); box_key.replace(Some(@())); int_key.replace(Some(42)); }); @@ -335,12 +335,12 @@ mod tests { #[test] fn test_tls_overwrite_multiple_types() { - static str_key: Key<~str> = &Key; + static str_key: Key<StrBuf> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; task::spawn(proc() { - str_key.replace(Some("string data".to_owned())); - str_key.replace(Some("string data 2".to_owned())); + str_key.replace(Some("string data".to_strbuf())); + str_key.replace(Some("string data 2".to_strbuf())); box_key.replace(Some(@())); box_key.replace(Some(@())); int_key.replace(Some(42)); @@ -354,13 +354,13 @@ mod tests { #[test] #[should_fail] fn test_tls_cleanup_on_failure() { - static str_key: Key<~str> = &Key; + static str_key: Key<StrBuf> = &Key; static box_key: Key<@()> = &Key; static int_key: Key<int> = &Key; - str_key.replace(Some("parent data".to_owned())); + str_key.replace(Some("parent data".to_strbuf())); box_key.replace(Some(@())); task::spawn(proc() { - str_key.replace(Some("string data".to_owned())); + str_key.replace(Some("string data".to_strbuf())); box_key.replace(Some(@())); int_key.replace(Some(42)); fail!(); diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index e9ea0df2a7b..66d93c230a5 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -20,6 +20,7 @@ use intrinsics; use libc::c_int; use num::strconv; use num; +use strbuf::StrBuf; pub use core::f32::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON, MIN_VALUE}; pub use core::f32::{MIN_POS_VALUE, MAX_VALUE, MIN_EXP, MAX_EXP, MIN_10_EXP}; @@ -242,7 +243,7 @@ impl FloatMath for f32 { /// /// * num - The float value #[inline] -pub fn to_str(num: f32) -> ~str { +pub fn to_str(num: f32) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r @@ -254,7 +255,7 @@ pub fn to_str(num: f32) -> ~str { /// /// * num - The float value #[inline] -pub fn to_str_hex(num: f32) -> ~str { +pub fn to_str_hex(num: f32) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 16u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r @@ -268,7 +269,7 @@ pub fn to_str_hex(num: f32) -> ~str { /// * num - The float value /// * radix - The base to use #[inline] -pub fn to_str_radix_special(num: f32, rdx: uint) -> (~str, bool) { +pub fn to_str_radix_special(num: f32, rdx: uint) -> (StrBuf, bool) { strconv::float_to_str_common(num, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false) } @@ -281,7 +282,7 @@ pub fn to_str_radix_special(num: f32, rdx: uint) -> (~str, bool) { /// * num - The float value /// * digits - The number of significant digits #[inline] -pub fn to_str_exact(num: f32, dig: uint) -> ~str { +pub fn to_str_exact(num: f32, dig: uint) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpNone, false); r @@ -295,7 +296,7 @@ pub fn to_str_exact(num: f32, dig: uint) -> ~str { /// * num - The float value /// * digits - The number of significant digits #[inline] -pub fn to_str_digits(num: f32, dig: uint) -> ~str { +pub fn to_str_digits(num: f32, dig: uint) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpNone, false); r @@ -310,7 +311,7 @@ pub fn to_str_digits(num: f32, dig: uint) -> ~str { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> ~str { +pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpDec, upper); r @@ -325,7 +326,7 @@ pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> ~str { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> ~str { +pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpDec, upper); r @@ -345,7 +346,7 @@ impl num::ToStrRadix for f32 { /// possible misinterpretation of the result at higher bases. If those values /// are expected, use `to_str_radix_special()` instead. #[inline] - fn to_str_radix(&self, rdx: uint) -> ~str { + fn to_str_radix(&self, rdx: uint) -> StrBuf { let (r, special) = strconv::float_to_str_common( *self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); if special { fail!("number has a special value, \ diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index 869a275b1d4..be4e4dc0d66 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -19,6 +19,7 @@ use intrinsics; use libc::c_int; use num::strconv; use num; +use strbuf::StrBuf; pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON, MIN_VALUE}; pub use core::f64::{MIN_POS_VALUE, MAX_VALUE, MIN_EXP, MAX_EXP, MIN_10_EXP}; @@ -250,7 +251,7 @@ impl FloatMath for f64 { /// /// * num - The float value #[inline] -pub fn to_str(num: f64) -> ~str { +pub fn to_str(num: f64) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r @@ -262,7 +263,7 @@ pub fn to_str(num: f64) -> ~str { /// /// * num - The float value #[inline] -pub fn to_str_hex(num: f64) -> ~str { +pub fn to_str_hex(num: f64) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 16u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r @@ -276,7 +277,7 @@ pub fn to_str_hex(num: f64) -> ~str { /// * num - The float value /// * radix - The base to use #[inline] -pub fn to_str_radix_special(num: f64, rdx: uint) -> (~str, bool) { +pub fn to_str_radix_special(num: f64, rdx: uint) -> (StrBuf, bool) { strconv::float_to_str_common(num, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false) } @@ -289,7 +290,7 @@ pub fn to_str_radix_special(num: f64, rdx: uint) -> (~str, bool) { /// * num - The float value /// * digits - The number of significant digits #[inline] -pub fn to_str_exact(num: f64, dig: uint) -> ~str { +pub fn to_str_exact(num: f64, dig: uint) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpNone, false); r @@ -303,7 +304,7 @@ pub fn to_str_exact(num: f64, dig: uint) -> ~str { /// * num - The float value /// * digits - The number of significant digits #[inline] -pub fn to_str_digits(num: f64, dig: uint) -> ~str { +pub fn to_str_digits(num: f64, dig: uint) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpNone, false); r @@ -318,7 +319,7 @@ pub fn to_str_digits(num: f64, dig: uint) -> ~str { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> ~str { +pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpDec, upper); r @@ -333,7 +334,7 @@ pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> ~str { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> ~str { +pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> StrBuf { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpDec, upper); r @@ -353,7 +354,7 @@ impl num::ToStrRadix for f64 { /// possible misinterpretation of the result at higher bases. If those values /// are expected, use `to_str_radix_special()` instead. #[inline] - fn to_str_radix(&self, rdx: uint) -> ~str { + fn to_str_radix(&self, rdx: uint) -> StrBuf { let (r, special) = strconv::float_to_str_common( *self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); if special { fail!("number has a special value, \ diff --git a/src/libstd/num/i16.rs b/src/libstd/num/i16.rs index 396037d0dba..7d08c181e9e 100644 --- a/src/libstd/num/i16.rs +++ b/src/libstd/num/i16.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::i16::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i32.rs b/src/libstd/num/i32.rs index 5640e82d077..2504d3f5766 100644 --- a/src/libstd/num/i32.rs +++ b/src/libstd/num/i32.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::i32::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i64.rs b/src/libstd/num/i64.rs index 40245691e34..7fc6a091dfc 100644 --- a/src/libstd/num/i64.rs +++ b/src/libstd/num/i64.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::i64::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i8.rs b/src/libstd/num/i8.rs index 7ddddd893e2..a39a6ced077 100644 --- a/src/libstd/num/i8.rs +++ b/src/libstd/num/i8.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::i8::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs index dc4d80601b7..2a23a35be6d 100644 --- a/src/libstd/num/int.rs +++ b/src/libstd/num/int.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::int::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index ddff42f68db..31a0edfbc38 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -77,8 +77,8 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] - fn to_str_radix(&self, radix: uint) -> ~str { - format!("{}", ::fmt::radix(*self, radix as u8)) + fn to_str_radix(&self, radix: uint) -> StrBuf { + format_strbuf!("{}", ::fmt::radix(*self, radix as u8)) } } @@ -136,39 +136,39 @@ mod tests { #[test] fn test_to_str() { - assert_eq!((0 as $T).to_str_radix(10u), "0".to_owned()); - assert_eq!((1 as $T).to_str_radix(10u), "1".to_owned()); - assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_owned()); - assert_eq!((127 as $T).to_str_radix(16u), "7f".to_owned()); - assert_eq!((100 as $T).to_str_radix(10u), "100".to_owned()); + assert_eq!((0 as $T).to_str_radix(10u), "0".to_strbuf()); + assert_eq!((1 as $T).to_str_radix(10u), "1".to_strbuf()); + assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_strbuf()); + assert_eq!((127 as $T).to_str_radix(16u), "7f".to_strbuf()); + assert_eq!((100 as $T).to_str_radix(10u), "100".to_strbuf()); } #[test] fn test_int_to_str_overflow() { let mut i8_val: i8 = 127_i8; - assert_eq!(i8_val.to_str(), "127".to_owned()); + assert_eq!(i8_val.to_str(), "127".to_strbuf()); i8_val += 1 as i8; - assert_eq!(i8_val.to_str(), "-128".to_owned()); + assert_eq!(i8_val.to_str(), "-128".to_strbuf()); let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16_val.to_str(), "32767".to_owned()); + assert_eq!(i16_val.to_str(), "32767".to_strbuf()); i16_val += 1 as i16; - assert_eq!(i16_val.to_str(), "-32768".to_owned()); + assert_eq!(i16_val.to_str(), "-32768".to_strbuf()); let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32_val.to_str(), "2147483647".to_owned()); + assert_eq!(i32_val.to_str(), "2147483647".to_strbuf()); i32_val += 1 as i32; - assert_eq!(i32_val.to_str(), "-2147483648".to_owned()); + assert_eq!(i32_val.to_str(), "-2147483648".to_strbuf()); let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64_val.to_str(), "9223372036854775807".to_owned()); + assert_eq!(i64_val.to_str(), "9223372036854775807".to_strbuf()); i64_val += 1 as i64; - assert_eq!(i64_val.to_str(), "-9223372036854775808".to_owned()); + assert_eq!(i64_val.to_str(), "-9223372036854775808".to_strbuf()); } #[test] diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 40167718236..c1d6bbb492d 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -15,7 +15,8 @@ #![allow(missing_doc)] -use option::{Option}; +use option::Option; +use strbuf::StrBuf; #[cfg(test)] use fmt::Show; @@ -111,7 +112,7 @@ pub trait FloatMath: Float { /// A generic trait for converting a value to a string with a radix (base) pub trait ToStrRadix { - fn to_str_radix(&self, radix: uint) -> ~str; + fn to_str_radix(&self, radix: uint) -> StrBuf; } /// A generic trait for converting a string with a radix (base) to a value diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index e58872b8395..795534dc283 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -19,9 +19,9 @@ use num::{Float, FPNaN, FPInfinite, ToPrimitive}; use num; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use option::{None, Option, Some}; -use slice::{CloneableVector, ImmutableVector, MutableVector}; +use slice::{ImmutableVector, MutableVector}; use std::cmp::{Ord, Eq}; -use str::{StrAllocating, StrSlice}; +use str::StrSlice; use strbuf::StrBuf; use vec::Vec; @@ -496,10 +496,10 @@ pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+ Div<T,T>+Neg<T>+Rem<T,T>+Mul<T,T>>( num: T, radix: uint, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_capital: bool - ) -> (~str, bool) { + ) -> (StrBuf, bool) { let (bytes, special) = float_to_str_bytes_common(num, radix, negative_zero, sign, digits, exp_format, exp_capital); - (StrBuf::from_utf8(bytes).unwrap().into_owned(), special) + (StrBuf::from_utf8(bytes).unwrap(), special) } // Some constants for from_str_bytes_common's input validation, diff --git a/src/libstd/num/u16.rs b/src/libstd/num/u16.rs index 65ac46af5aa..6d68af99890 100644 --- a/src/libstd/num/u16.rs +++ b/src/libstd/num/u16.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::u16::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u32.rs b/src/libstd/num/u32.rs index d549e4d0d63..130ca2c4855 100644 --- a/src/libstd/num/u32.rs +++ b/src/libstd/num/u32.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::u32::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u64.rs b/src/libstd/num/u64.rs index 3773e56f4d1..559fcf6e7d1 100644 --- a/src/libstd/num/u64.rs +++ b/src/libstd/num/u64.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::u64::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u8.rs b/src/libstd/num/u8.rs index 372e38d6652..f855c8c4951 100644 --- a/src/libstd/num/u8.rs +++ b/src/libstd/num/u8.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::u8::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs index c419276fa24..f651cf72cca 100644 --- a/src/libstd/num/uint.rs +++ b/src/libstd/num/uint.rs @@ -15,6 +15,7 @@ use num::{ToStrRadix, FromStrRadix}; use num::strconv; use option::Option; use slice::ImmutableVector; +use strbuf::StrBuf; pub use core::uint::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index 7977c647606..ba329065a6e 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -78,8 +78,8 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] - fn to_str_radix(&self, radix: uint) -> ~str { - format!("{}", ::fmt::radix(*self, radix as u8)) + fn to_str_radix(&self, radix: uint) -> StrBuf { + format_strbuf!("{}", ::fmt::radix(*self, radix as u8)) } } @@ -94,13 +94,13 @@ mod tests { #[test] pub fn test_to_str() { - assert_eq!((0 as $T).to_str_radix(10u), "0".to_owned()); - assert_eq!((1 as $T).to_str_radix(10u), "1".to_owned()); - assert_eq!((2 as $T).to_str_radix(10u), "2".to_owned()); - assert_eq!((11 as $T).to_str_radix(10u), "11".to_owned()); - assert_eq!((11 as $T).to_str_radix(16u), "b".to_owned()); - assert_eq!((255 as $T).to_str_radix(16u), "ff".to_owned()); - assert_eq!((0xff as $T).to_str_radix(10u), "255".to_owned()); + assert_eq!((0 as $T).to_str_radix(10u), "0".to_strbuf()); + assert_eq!((1 as $T).to_str_radix(10u), "1".to_strbuf()); + assert_eq!((2 as $T).to_str_radix(10u), "2".to_strbuf()); + assert_eq!((11 as $T).to_str_radix(10u), "11".to_strbuf()); + assert_eq!((11 as $T).to_str_radix(16u), "b".to_strbuf()); + assert_eq!((255 as $T).to_str_radix(16u), "ff".to_strbuf()); + assert_eq!((0xff as $T).to_str_radix(10u), "255".to_strbuf()); } #[test] @@ -133,28 +133,28 @@ mod tests { #[test] fn test_uint_to_str_overflow() { let mut u8_val: u8 = 255_u8; - assert_eq!(u8_val.to_str(), "255".to_owned()); + assert_eq!(u8_val.to_str(), "255".to_strbuf()); u8_val += 1 as u8; - assert_eq!(u8_val.to_str(), "0".to_owned()); + assert_eq!(u8_val.to_str(), "0".to_strbuf()); let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16_val.to_str(), "65535".to_owned()); + assert_eq!(u16_val.to_str(), "65535".to_strbuf()); u16_val += 1 as u16; - assert_eq!(u16_val.to_str(), "0".to_owned()); + assert_eq!(u16_val.to_str(), "0".to_strbuf()); let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32_val.to_str(), "4294967295".to_owned()); + assert_eq!(u32_val.to_str(), "4294967295".to_strbuf()); u32_val += 1 as u32; - assert_eq!(u32_val.to_str(), "0".to_owned()); + assert_eq!(u32_val.to_str(), "0".to_strbuf()); let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64_val.to_str(), "18446744073709551615".to_owned()); + assert_eq!(u64_val.to_str(), "18446744073709551615".to_strbuf()); u64_val += 1 as u64; - assert_eq!(u64_val.to_str(), "0".to_owned()); + assert_eq!(u64_val.to_str(), "0".to_strbuf()); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index a4705b78caa..493dd86b276 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -30,21 +30,22 @@ use clone::Clone; use container::Container; -use libc; +use fmt; +use iter::Iterator; use libc::{c_void, c_int}; +use libc; +use ops::Drop; use option::{Some, None, Option}; use os; -use ops::Drop; -use result::{Err, Ok, Result}; +use path::{Path, GenericPath}; +use ptr::RawPtr; use ptr; -use str; +use result::{Err, Ok, Result}; +use slice::{Vector, ImmutableVector, MutableVector, OwnedVector}; use str::{Str, StrSlice, StrAllocating}; -use fmt; +use str; +use strbuf::StrBuf; use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst}; -use path::{Path, GenericPath}; -use iter::Iterator; -use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector}; -use ptr::RawPtr; use vec::Vec; #[cfg(unix)] @@ -103,12 +104,13 @@ pub mod win32 { use option; use os::TMPBUF_SZ; use slice::{MutableVector, ImmutableVector}; + use strbuf::StrBuf; use str::{StrSlice, StrAllocating}; use str; use vec::Vec; pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD) - -> Option<~str> { + -> Option<StrBuf> { unsafe { let mut n = TMPBUF_SZ as DWORD; @@ -174,20 +176,20 @@ fn with_env_lock<T>(f: || -> T) -> T { /// /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()` /// for details. -pub fn env() -> Vec<(~str,~str)> { +pub fn env() -> Vec<(StrBuf,StrBuf)> { env_as_bytes().move_iter().map(|(k,v)| { - let k = str::from_utf8_lossy(k).into_owned(); - let v = str::from_utf8_lossy(v).into_owned(); + let k = str::from_utf8_lossy(k.as_slice()).to_strbuf(); + let v = str::from_utf8_lossy(v.as_slice()).to_strbuf(); (k,v) }).collect() } /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. -pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { +pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> { unsafe { #[cfg(windows)] - unsafe fn get_env_pairs() -> Vec<~[u8]> { + unsafe fn get_env_pairs() -> Vec<Vec<u8>> { use slice::raw; use libc::funcs::extra::kernel32::{ @@ -227,7 +229,7 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { result } #[cfg(unix)] - unsafe fn get_env_pairs() -> Vec<~[u8]> { + unsafe fn get_env_pairs() -> Vec<Vec<u8>> { use c_str::CString; extern { @@ -240,18 +242,19 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { } let mut result = Vec::new(); ptr::array_each(environ, |e| { - let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned(); + let env_pair = + Vec::from_slice(CString::new(e, false).as_bytes_no_nul()); result.push(env_pair); }); result } - fn env_convert(input: Vec<~[u8]>) -> Vec<(~[u8], ~[u8])> { + fn env_convert(input: Vec<Vec<u8>>) -> Vec<(Vec<u8>, Vec<u8>)> { let mut pairs = Vec::new(); for p in input.iter() { - let mut it = p.splitn(1, |b| *b == '=' as u8); - let key = it.next().unwrap().to_owned(); - let val = it.next().unwrap_or(&[]).to_owned(); + let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8); + let key = Vec::from_slice(it.next().unwrap()); + let val = Vec::from_slice(it.next().unwrap_or(&[])); pairs.push((key, val)); } pairs @@ -273,8 +276,8 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { /// # Failure /// /// Fails if `n` has any interior NULs. -pub fn getenv(n: &str) -> Option<~str> { - getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v).into_owned()) +pub fn getenv(n: &str) -> Option<StrBuf> { + getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_strbuf()) } #[cfg(unix)] @@ -284,7 +287,7 @@ pub fn getenv(n: &str) -> Option<~str> { /// # Failure /// /// Fails if `n` has any interior NULs. -pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { +pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { use c_str::CString; unsafe { @@ -293,7 +296,8 @@ pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { if s.is_null() { None } else { - Some(CString::new(s, false).as_bytes_no_nul().to_owned()) + Some(Vec::from_slice(CString::new(s, + false).as_bytes_no_nul())) } }) } @@ -302,7 +306,7 @@ pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { #[cfg(windows)] /// Fetches the environment variable `n` from the current process, returning /// None if the variable isn't set. -pub fn getenv(n: &str) -> Option<~str> { +pub fn getenv(n: &str) -> Option<StrBuf> { unsafe { with_env_lock(|| { use os::win32::{as_utf16_p, fill_utf16_buf_and_decode}; @@ -318,7 +322,7 @@ pub fn getenv(n: &str) -> Option<~str> { #[cfg(windows)] /// Fetches the environment variable `n` byte vector from the current process, /// returning None if the variable isn't set. -pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { +pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { getenv(n).map(|s| s.into_bytes()) } @@ -432,8 +436,8 @@ pub fn pipe() -> Pipe { } /// Returns the proper dll filename for the given basename of a file. -pub fn dll_filename(base: &str) -> ~str { - format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX) +pub fn dll_filename(base: &str) -> StrBuf { + format_strbuf!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX) } /// Optionally returns the filesystem path of the current executable which is @@ -527,7 +531,7 @@ pub fn self_exe_path() -> Option<Path> { * Otherwise, homedir returns option::none. */ pub fn homedir() -> Option<Path> { - // FIXME (#7188): getenv needs a ~[u8] variant + // FIXME (#7188): getenv needs a Vec<u8> variant return match getenv("HOME") { Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()), _ => secondary() @@ -688,11 +692,11 @@ pub fn errno() -> uint { } /// Return the string corresponding to an `errno()` value of `errnum`. -pub fn error_string(errnum: uint) -> ~str { +pub fn error_string(errnum: uint) -> StrBuf { return strerror(errnum); #[cfg(unix)] - fn strerror(errnum: uint) -> ~str { + fn strerror(errnum: uint) -> StrBuf { #[cfg(target_os = "macos")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] @@ -732,12 +736,12 @@ pub fn error_string(errnum: uint) -> ~str { fail!("strerror_r failure"); } - str::raw::from_c_str(p as *c_char) + str::raw::from_c_str(p as *c_char).into_strbuf() } } #[cfg(windows)] - fn strerror(errnum: uint) -> ~str { + fn strerror(errnum: uint) -> StrBuf { use libc::types::os::arch::extra::DWORD; use libc::types::os::arch::extra::LPWSTR; use libc::types::os::arch::extra::LPVOID; @@ -789,7 +793,7 @@ pub fn error_string(errnum: uint) -> ~str { } /// Get a string representing the platform-dependent last error -pub fn last_os_error() -> ~str { +pub fn last_os_error() -> StrBuf { error_string(errno() as uint) } @@ -816,11 +820,12 @@ pub fn get_exit_status() -> int { } #[cfg(target_os = "macos")] -unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<~[u8]> { +unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<Vec<u8>> { use c_str::CString; Vec::from_fn(argc as uint, |i| { - CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned() + Vec::from_slice(CString::new(*argv.offset(i as int), + false).as_bytes_no_nul()) }) } @@ -830,7 +835,7 @@ unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<~[u8]> { * Returns a list of the command line arguments. */ #[cfg(target_os = "macos")] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec<Vec<u8>> { unsafe { let (argc, argv) = (*_NSGetArgc() as int, *_NSGetArgv() as **c_char); @@ -841,7 +846,7 @@ fn real_args_as_bytes() -> Vec<~[u8]> { #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec<Vec<u8>> { use rt; match rt::args::clone() { @@ -851,12 +856,15 @@ fn real_args_as_bytes() -> Vec<~[u8]> { } #[cfg(not(windows))] -fn real_args() -> Vec<~str> { - real_args_as_bytes().move_iter().map(|v| str::from_utf8_lossy(v).into_owned()).collect() +fn real_args() -> Vec<StrBuf> { + real_args_as_bytes().move_iter() + .map(|v| { + str::from_utf8_lossy(v.as_slice()).into_strbuf() + }).collect() } #[cfg(windows)] -fn real_args() -> Vec<~str> { +fn real_args() -> Vec<StrBuf> { use slice; use option::Expect; @@ -886,7 +894,7 @@ fn real_args() -> Vec<~str> { } #[cfg(windows)] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec<Vec<u8>> { real_args().move_iter().map(|s| s.into_bytes()).collect() } @@ -910,13 +918,20 @@ extern "system" { /// /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD. /// See `str::from_utf8_lossy` for details. -pub fn args() -> Vec<~str> { +#[cfg(not(test))] +pub fn args() -> Vec<StrBuf> { real_args() } +#[cfg(test)] +#[allow(missing_doc)] +pub fn args() -> ::realstd::vec::Vec<::realstd::strbuf::StrBuf> { + ::realstd::os::args() +} + /// Returns the arguments which this program was started with (normally passed /// via the command line) as byte vectors. -pub fn args_as_bytes() -> Vec<~[u8]> { +pub fn args_as_bytes() -> Vec<Vec<u8>> { real_args_as_bytes() } @@ -1509,37 +1524,37 @@ mod tests { assert!(a.len() >= 1); } - fn make_rand_name() -> ~str { + fn make_rand_name() -> StrBuf { let mut rng = rand::task_rng(); let n = format_strbuf!("TEST{}", rng.gen_ascii_str(10u).as_slice()); assert!(getenv(n.as_slice()).is_none()); - n.into_owned() + n } #[test] fn test_setenv() { let n = make_rand_name(); - setenv(n, "VALUE"); - assert_eq!(getenv(n), option::Some("VALUE".to_owned())); + setenv(n.as_slice(), "VALUE"); + assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_strbuf())); } #[test] fn test_unsetenv() { let n = make_rand_name(); - setenv(n, "VALUE"); - unsetenv(n); - assert_eq!(getenv(n), option::None); + setenv(n.as_slice(), "VALUE"); + unsetenv(n.as_slice()); + assert_eq!(getenv(n.as_slice()), option::None); } #[test] #[ignore] fn test_setenv_overwrite() { let n = make_rand_name(); - setenv(n, "1"); - setenv(n, "2"); - assert_eq!(getenv(n), option::Some("2".to_owned())); - setenv(n, ""); - assert_eq!(getenv(n), option::Some("".to_owned())); + setenv(n.as_slice(), "1"); + setenv(n.as_slice(), "2"); + assert_eq!(getenv(n.as_slice()), option::Some("2".to_strbuf())); + setenv(n.as_slice(), ""); + assert_eq!(getenv(n.as_slice()), option::Some("".to_strbuf())); } // Windows GetEnvironmentVariable requires some extra work to make sure @@ -1547,16 +1562,16 @@ mod tests { #[test] #[ignore] fn test_getenv_big() { - let mut s = "".to_owned(); + let mut s = "".to_strbuf(); let mut i = 0; while i < 100 { - s = s + "aaaaaaaaaa"; + s.push_str("aaaaaaaaaa"); i += 1; } let n = make_rand_name(); - setenv(n, s); + setenv(n.as_slice(), s.as_slice()); debug!("{}", s.clone()); - assert_eq!(getenv(n), option::Some(s)); + assert_eq!(getenv(n.as_slice()), option::Some(s)); } #[test] @@ -1589,7 +1604,7 @@ mod tests { for p in e.iter() { let (n, v) = (*p).clone(); debug!("{:?}", n.clone()); - let v2 = getenv(n); + let v2 = getenv(n.as_slice()); // MingW seems to set some funky environment variables like // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned // from env() but not visible from getenv(). @@ -1600,11 +1615,11 @@ mod tests { #[test] fn test_env_set_get_huge() { let n = make_rand_name(); - let s = "x".repeat(10000); - setenv(n, s); - assert_eq!(getenv(n), Some(s)); - unsetenv(n); - assert_eq!(getenv(n), None); + let s = "x".repeat(10000).to_strbuf(); + setenv(n.as_slice(), s.as_slice()); + assert_eq!(getenv(n.as_slice()), Some(s)); + unsetenv(n.as_slice()); + assert_eq!(getenv(n.as_slice()), None); } #[test] @@ -1612,11 +1627,11 @@ mod tests { let n = make_rand_name(); let mut e = env(); - setenv(n, "VALUE"); - assert!(!e.contains(&(n.clone(), "VALUE".to_owned()))); + setenv(n.as_slice(), "VALUE"); + assert!(!e.contains(&(n.clone(), "VALUE".to_strbuf()))); e = env(); - assert!(e.contains(&(n, "VALUE".to_owned()))); + assert!(e.contains(&(n, "VALUE".to_strbuf()))); } #[test] @@ -1641,7 +1656,9 @@ mod tests { setenv("HOME", ""); assert!(os::homedir().is_none()); - for s in oldhome.iter() { setenv("HOME", *s) } + for s in oldhome.iter() { + setenv("HOME", s.as_slice()) + } } #[test] @@ -1668,8 +1685,12 @@ mod tests { setenv("USERPROFILE", "/home/PaloAlto"); assert!(os::homedir() == Some(Path::new("/home/MountainView"))); - for s in oldhome.iter() { setenv("HOME", *s) } - for s in olduserprofile.iter() { setenv("USERPROFILE", *s) } + for s in oldhome.iter() { + setenv("HOME", s.as_slice()) + } + for s in olduserprofile.iter() { + setenv("USERPROFILE", s.as_slice()) + } } #[test] diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 2960d55f337..1bd099e5d24 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -519,28 +519,12 @@ impl<'a> BytesContainer for &'a str { fn is_str(_: Option<&'a str>) -> bool { true } } -impl BytesContainer for ~str { - #[inline] - fn container_as_bytes<'a>(&'a self) -> &'a [u8] { - self.as_bytes() - } - #[inline] - fn container_as_str<'a>(&'a self) -> Option<&'a str> { - Some(self.as_slice()) - } - #[inline] - fn is_str(_: Option<~str>) -> bool { true } -} impl BytesContainer for StrBuf { #[inline] fn container_as_bytes<'a>(&'a self) -> &'a [u8] { self.as_bytes() } #[inline] - fn container_into_owned_bytes(self) -> Vec<u8> { - self.into_bytes() - } - #[inline] fn container_as_str<'a>(&'a self) -> Option<&'a str> { Some(self.as_slice()) } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 4f7132dc6e4..8a939a92846 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -781,7 +781,7 @@ mod tests { t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e"); t!(s: "a/b/c", ["d", "/e"], "/e"); t!(s: "a/b/c", ["d", "/e", "f"], "/e/f"); - t!(s: "a/b/c", ["d".to_owned(), "e".to_owned()], "a/b/c/d/e"); + t!(s: "a/b/c", ["d".to_strbuf(), "e".to_strbuf()], "a/b/c/d/e"); t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e")); t!(v: b!("a/b/c"), [b!("d"), b!("/e"), b!("f")], b!("/e/f")); t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e")); @@ -886,7 +886,7 @@ mod tests { t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e"); t!(s: "a/b/c", ["..", "d"], "a/b/d"); t!(s: "a/b/c", ["d", "/e", "f"], "/e/f"); - t!(s: "a/b/c", ["d".to_owned(), "e".to_owned()], "a/b/c/d/e"); + t!(s: "a/b/c", ["d".to_strbuf(), "e".to_strbuf()], "a/b/c/d/e"); t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e")); t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e")); } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 176788edcc4..1c671b30e80 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -136,10 +136,17 @@ impl<'a> ToCStr for &'a Path { } impl<S: Writer> ::hash::Hash<S> for Path { + #[cfg(not(test))] #[inline] fn hash(&self, state: &mut S) { self.repr.hash(state) } + + #[cfg(test)] + #[inline] + fn hash(&self, _: &mut S) { + // No-op because the `hash` implementation will be wrong. + } } impl BytesContainer for Path { @@ -589,7 +596,7 @@ impl GenericPath for Path { } } } - Some(Path::new(comps.connect("\\"))) + Some(Path::new(comps.connect("\\").into_strbuf())) } } @@ -754,7 +761,10 @@ impl Path { let mut s = StrBuf::from_str(s.slice_to(len)); unsafe { let v = s.as_mut_vec(); - *v.get_mut(0) = v.get(0).to_ascii().to_upper().to_byte(); + *v.get_mut(0) = v.get(0) + .to_ascii() + .to_upper() + .to_byte(); } if is_abs { // normalize C:/ to C:\ @@ -913,7 +923,7 @@ pub fn make_non_verbatim(path: &Path) -> Option<Path> { } Some(VerbatimUNCPrefix(_,_)) => { // \\?\UNC\server\share - Path::new(format!(r"\\{}", repr.slice_from(7))) + Path::new(format_strbuf!(r"\\{}", repr.slice_from(7))) } }; if new_path.prefix.is_none() { @@ -1331,9 +1341,9 @@ mod tests { #[test] fn test_display_str() { let path = Path::new("foo"); - assert_eq!(path.display().to_str(), "foo".to_owned()); + assert_eq!(path.display().to_str(), "foo".to_strbuf()); let path = Path::new(b!("\\")); - assert_eq!(path.filename_display().to_str(), "".to_owned()); + assert_eq!(path.filename_display().to_str(), "".to_strbuf()); let path = Path::new("foo"); let mo = path.display().as_maybe_owned(); @@ -1594,7 +1604,7 @@ mod tests { t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e"); t!(s: "a\\b\\c", ["d", "\\e"], "\\e"); t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f"); - t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e"); + t!(s: "a\\b\\c", ["d".to_strbuf(), "e".to_strbuf()], "a\\b\\c\\d\\e"); t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e")); t!(v: b!("a\\b\\c"), [b!("d"), b!("\\e"), b!("f")], b!("\\e\\f")); t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], @@ -1735,7 +1745,7 @@ mod tests { t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e"); t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d"); t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f"); - t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e"); + t!(s: "a\\b\\c", ["d".to_strbuf(), "e".to_strbuf()], "a\\b\\c\\d\\e"); t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e")); t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a\\b\\c\\d\\e")); diff --git a/src/libstd/repr.rs b/src/libstd/repr.rs index 35f32d08728..8da906d8521 100644 --- a/src/libstd/repr.rs +++ b/src/libstd/repr.rs @@ -16,21 +16,22 @@ More runtime type reflection #![allow(missing_doc)] -use mem::transmute; use char; use container::Container; +use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc}; use io; use iter::Iterator; +use mem::transmute; use option::{Some, None, Option}; use ptr::RawPtr; -use reflect; +use raw; use reflect::{MovePtr, align}; +use reflect; use result::{Ok, Err}; -use str::StrSlice; -use to_str::ToStr; use slice::Vector; -use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc}; -use raw; +use str::{Str, StrSlice}; +use strbuf::StrBuf; +use to_str::ToStr; use vec::Vec; macro_rules! try( ($me:expr, $e:expr) => ( @@ -296,10 +297,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { } fn visit_estr_uniq(&mut self) -> bool { - self.get::<~str>(|this, s| { - try!(this, this.writer.write(['~' as u8])); - this.write_escaped_slice(*s) - }) + true } fn visit_estr_slice(&mut self) -> bool { @@ -604,14 +602,14 @@ pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> { } } -pub fn repr_to_str<T>(t: &T) -> ~str { +pub fn repr_to_str<T>(t: &T) -> StrBuf { use str; use str::StrAllocating; use io; let mut result = io::MemWriter::new(); write_repr(&mut result as &mut io::Writer, t).unwrap(); - str::from_utf8(result.unwrap().as_slice()).unwrap().to_owned() + str::from_utf8(result.unwrap().as_slice()).unwrap().to_strbuf() } #[cfg(test)] @@ -638,8 +636,6 @@ fn test_repr() { exact_test(&false, "false"); exact_test(&1.234, "1.234f64"); exact_test(&("hello"), "\"hello\""); - // FIXME What do I do about this one? - exact_test(&("he\u10f3llo".to_owned()), "~\"he\\u10f3llo\""); exact_test(&(@10), "@10"); exact_test(&(box 10), "box 10"); @@ -659,14 +655,6 @@ fn test_repr() { "@repr::P{a: 10, b: 1.234f64}"); exact_test(&(box P{a:10, b:1.234}), "box repr::P{a: 10, b: 1.234f64}"); - exact_test(&(10u8, "hello".to_owned()), - "(10u8, ~\"hello\")"); - exact_test(&(10u16, "hello".to_owned()), - "(10u16, ~\"hello\")"); - exact_test(&(10u32, "hello".to_owned()), - "(10u32, ~\"hello\")"); - exact_test(&(10u64, "hello".to_owned()), - "(10u64, ~\"hello\")"); exact_test(&(&[1, 2]), "&[1, 2]"); exact_test(&(&mut [1, 2]), "&mut [1, 2]"); diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index 95d0eabd336..cde20521c2f 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -37,8 +37,8 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) } #[cfg(test)] pub unsafe fn cleanup() { realargs::cleanup() } /// Take the global arguments from global storage. -#[cfg(not(test))] pub fn take() -> Option<Vec<~[u8]>> { imp::take() } -#[cfg(test)] pub fn take() -> Option<Vec<~[u8]>> { +#[cfg(not(test))] pub fn take() -> Option<Vec<Vec<u8>>> { imp::take() } +#[cfg(test)] pub fn take() -> Option<Vec<Vec<u8>>> { match realargs::take() { realstd::option::Some(v) => Some(unsafe{ ::mem::transmute(v) }), realstd::option::None => None, @@ -48,12 +48,16 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) } /// Give the global arguments to global storage. /// /// It is an error if the arguments already exist. -#[cfg(not(test))] pub fn put(args: Vec<~[u8]>) { imp::put(args) } -#[cfg(test)] pub fn put(args: Vec<~[u8]>) { realargs::put(unsafe { ::mem::transmute(args) }) } +#[cfg(not(test))] pub fn put(args: Vec<Vec<u8>>) { imp::put(args) } +#[cfg(test)] pub fn put(args: Vec<Vec<u8>>) { + realargs::put(unsafe { + ::mem::transmute(args) + }) +} /// Make a clone of the global arguments. -#[cfg(not(test))] pub fn clone() -> Option<Vec<~[u8]>> { imp::clone() } -#[cfg(test)] pub fn clone() -> Option<Vec<~[u8]>> { +#[cfg(not(test))] pub fn clone() -> Option<Vec<Vec<u8>>> { imp::clone() } +#[cfg(test)] pub fn clone() -> Option<Vec<Vec<u8>>> { match realargs::clone() { realstd::option::Some(v) => Some(unsafe { ::mem::transmute(v) }), realstd::option::None => None, @@ -88,15 +92,15 @@ mod imp { lock.destroy(); } - pub fn take() -> Option<Vec<~[u8]>> { + pub fn take() -> Option<Vec<Vec<u8>>> { with_lock(|| unsafe { let ptr = get_global_ptr(); let val = mem::replace(&mut *ptr, None); - val.as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone()) + val.as_ref().map(|s: &Box<Vec<Vec<u8>>>| (**s).clone()) }) } - pub fn put(args: Vec<~[u8]>) { + pub fn put(args: Vec<Vec<u8>>) { with_lock(|| unsafe { let ptr = get_global_ptr(); rtassert!((*ptr).is_none()); @@ -104,10 +108,10 @@ mod imp { }) } - pub fn clone() -> Option<Vec<~[u8]>> { + pub fn clone() -> Option<Vec<Vec<u8>>> { with_lock(|| unsafe { let ptr = get_global_ptr(); - (*ptr).as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone()) + (*ptr).as_ref().map(|s: &Box<Vec<Vec<u8>>>| (**s).clone()) }) } @@ -118,22 +122,21 @@ mod imp { } } - fn get_global_ptr() -> *mut Option<Box<Vec<~[u8]>>> { + fn get_global_ptr() -> *mut Option<Box<Vec<Vec<u8>>>> { unsafe { mem::transmute(&global_args_ptr) } } // Copied from `os`. #[cfg(not(test))] - unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<~[u8]> { + unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<Vec<u8>> { use c_str::CString; use ptr::RawPtr; use libc; - use slice::CloneableVector; use vec::Vec; Vec::from_fn(argc as uint, |i| { let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false); - cs.as_bytes_no_nul().to_owned() + Vec::from_slice(cs.as_bytes_no_nul()) }) } @@ -148,7 +151,10 @@ mod imp { // Preserve the actual global state. let saved_value = take(); - let expected = vec![bytes!("happy").to_owned(), bytes!("today?").to_owned()]; + let expected = vec![ + Vec::from_slice(bytes!("happy")), + Vec::from_slice(bytes!("today?")), + ]; put(expected.clone()); assert!(clone() == Some(expected.clone())); @@ -179,15 +185,15 @@ mod imp { pub fn cleanup() { } - pub fn take() -> Option<Vec<~[u8]>> { + pub fn take() -> Option<Vec<Vec<u8>>> { fail!() } - pub fn put(_args: Vec<~[u8]>) { + pub fn put(_args: Vec<Vec<u8>>) { fail!() } - pub fn clone() -> Option<Vec<~[u8]>> { + pub fn clone() -> Option<Vec<Vec<u8>>> { fail!() } } diff --git a/src/libstd/rt/env.rs b/src/libstd/rt/env.rs index 708c42030ab..c9e5cae60e4 100644 --- a/src/libstd/rt/env.rs +++ b/src/libstd/rt/env.rs @@ -13,6 +13,7 @@ use from_str::from_str; use option::{Some, None, Expect}; use os; +use str::Str; // Note that these are all accessed without any synchronization. // They are expected to be initialized once then left alone. @@ -25,15 +26,19 @@ static mut DEBUG_BORROW: bool = false; pub fn init() { unsafe { match os::getenv("RUST_MIN_STACK") { - Some(s) => match from_str(s) { + Some(s) => match from_str(s.as_slice()) { Some(i) => MIN_STACK = i, None => () }, None => () } match os::getenv("RUST_MAX_CACHED_STACKS") { - Some(max) => MAX_CACHED_STACKS = from_str(max).expect("expected positive integer in \ - RUST_MAX_CACHED_STACKS"), + Some(max) => { + MAX_CACHED_STACKS = + from_str(max.as_slice()).expect("expected positive \ + integer in \ + RUST_MAX_CACHED_STACKS") + } None => () } match os::getenv("RUST_DEBUG_BORROW") { diff --git a/src/libstd/rt/macros.rs b/src/libstd/rt/macros.rs index 74675c85b96..aef41de925f 100644 --- a/src/libstd/rt/macros.rs +++ b/src/libstd/rt/macros.rs @@ -43,6 +43,7 @@ macro_rules! rtassert ( macro_rules! rtabort ( ($($arg:tt)*) => ( { - ::rt::util::abort(format!($($arg)*)); + use str::Str; + ::rt::util::abort(format!($($arg)*).as_slice()); } ) ) diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 8968747d990..749f44d1c9d 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -420,11 +420,11 @@ mod test { #[test] fn tls() { - local_data_key!(key: @~str) - key.replace(Some(@"data".to_owned())); + local_data_key!(key: @StrBuf) + key.replace(Some(@"data".to_strbuf())); assert_eq!(key.get().unwrap().as_slice(), "data"); - local_data_key!(key2: @~str) - key2.replace(Some(@"data".to_owned())); + local_data_key!(key2: @StrBuf) + key2.replace(Some(@"data".to_strbuf())); assert_eq!(key2.get().unwrap().as_slice(), "data"); } diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index af87a31b7bd..8f2df831196 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -71,6 +71,7 @@ use rt::backtrace; use rt::local::Local; use rt::task::Task; use str::Str; +use strbuf::StrBuf; use task::TaskResult; use uw = rt::libunwind; @@ -353,7 +354,7 @@ pub fn begin_unwind_fmt(msg: &fmt::Arguments, file: &'static str, // required with the current scheme, and (b) we don't handle // failure + OOM properly anyway (see comment in begin_unwind // below). - begin_unwind_inner(box fmt::format(msg), file, line) + begin_unwind_inner(box fmt::format_strbuf(msg), file, line) } /// This is the entry point of unwinding for fail!() and assert!(). @@ -388,7 +389,7 @@ fn begin_unwind_inner(msg: Box<Any:Send>, { let msg_s = match msg.as_ref::<&'static str>() { Some(s) => *s, - None => match msg.as_ref::<~str>() { + None => match msg.as_ref::<StrBuf>() { Some(s) => s.as_slice(), None => "Box<Any>", } diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index c9e82bd16e5..1ab9ac1b11e 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -18,7 +18,7 @@ use libc; use option::{Some, None, Option}; use os; use result::Ok; -use str::StrSlice; +use str::{Str, StrSlice}; use unstable::running_on_valgrind; use slice::ImmutableVector; @@ -55,7 +55,7 @@ pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool { pub fn default_sched_threads() -> uint { match os::getenv("RUST_THREADS") { Some(nstr) => { - let opt_n: Option<uint> = FromStr::from_str(nstr); + let opt_n: Option<uint> = FromStr::from_str(nstr.as_slice()); match opt_n { Some(n) if n > 0 => n, _ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr) @@ -145,6 +145,7 @@ which at the time convulsed us with joy, yet which are now partly lost to my memory and partly incapable of presentation to others.", _ => "You've met with a terrible fate, haven't you?" }; + ::alloc::util::make_stdlib_link_work(); // see comments in liballoc rterrln!("{}", ""); rterrln!("{}", quote); rterrln!("{}", ""); diff --git a/src/libstd/slice.rs b/src/libstd/slice.rs index 0838211b9a5..ae1caa16d28 100644 --- a/src/libstd/slice.rs +++ b/src/libstd/slice.rs @@ -1853,16 +1853,18 @@ mod tests { }) ) let empty: ~[int] = box []; - test_show_vec!(empty, "[]".to_owned()); - test_show_vec!(box [1], "[1]".to_owned()); - test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_owned()); - test_show_vec!(box [box [], box [1u], box [1u, 1u]], "[[], [1], [1, 1]]".to_owned()); + test_show_vec!(empty, "[]".to_strbuf()); + test_show_vec!(box [1], "[1]".to_strbuf()); + test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_strbuf()); + test_show_vec!(box [box [], box [1u], box [1u, 1u]], + "[[], [1], [1, 1]]".to_strbuf()); let empty_mut: &mut [int] = &mut[]; - test_show_vec!(empty_mut, "[]".to_owned()); - test_show_vec!(&mut[1], "[1]".to_owned()); - test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_owned()); - test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]], "[[], [1], [1, 1]]".to_owned()); + test_show_vec!(empty_mut, "[]".to_strbuf()); + test_show_vec!(&mut[1], "[1]".to_strbuf()); + test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_strbuf()); + test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]], + "[[], [1], [1, 1]]".to_strbuf()); } #[test] diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 617887e8af3..4ba711c4611 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -17,37 +17,29 @@ Unicode string manipulation (`str` type) Rust's string type is one of the core primitive types of the language. While represented by the name `str`, the name `str` is not actually a valid type in Rust. Each string must also be decorated with its ownership. This means that -there are two common kinds of strings in Rust: - -* `~str` - This is an owned string. This type obeys all of the normal semantics - of the `Box<T>` types, meaning that it has one, and only one, - owner. This type cannot be implicitly copied, and is moved out of - when passed to other functions. +there is one common kind of string in Rust: * `&str` - This is the borrowed string type. This type of string can only be created from the other kind of string. As the name "borrowed" implies, this type of string is owned elsewhere, and this string cannot be moved out of. -As an example, here's a few different kinds of strings. +As an example, here's the one kind of string. ```rust fn main() { - let owned_string = "I am an owned string".to_owned(); - let borrowed_string1 = "This string is borrowed with the 'static lifetime"; - let borrowed_string2: &str = owned_string; // owned strings can be borrowed + let borrowed_string = "This string is borrowed with the 'static lifetime"; } ``` -From the example above, you can see that Rust has 2 different kinds of string -literals. The owned literals correspond to the owned string types, but the -"borrowed literal" is actually more akin to C's concept of a static string. +From the example above, you can see that Rust has 1 different kind of string +literal. The "borrowed literal" is akin to C's concept of a static string. -When a string is declared without a `~` sigil, then the string is allocated -statically in the rodata of the executable/library. The string then has the -type `&'static str` meaning that the string is valid for the `'static` -lifetime, otherwise known as the lifetime of the entire program. As can be -inferred from the type, these static strings are not mutable. +String literals are allocated statically in the rodata of the +executable/library. The string then has the type `&'static str` meaning that +the string is valid for the `'static` lifetime, otherwise known as the +lifetime of the entire program. As can be inferred from the type, these static +strings are not mutable. # Mutability @@ -67,10 +59,8 @@ stream of UTF-8 bytes. All safely-created strings are guaranteed to be validly encoded UTF-8 sequences. Additionally, strings are not null-terminated and can contain null codepoints. -The actual representation of strings have direct mappings to vectors: - -* `~str` is the same as `~[u8]` -* `&str` is the same as `&[u8]` +The actual representation of strings have direct mappings to vectors: `&str` +is the same as `&[u8]`. */ @@ -81,13 +71,12 @@ use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv, Ordering}; use container::Container; use default::Default; use fmt; -use from_str::FromStr; use io::Writer; use iter::{Iterator, range, AdditiveIterator}; use mem::transmute; use mem; use option::{None, Option, Some}; -use result::{Result, Ok, Err}; +use result::Result; use slice::Vector; use slice::{ImmutableVector, MutableVector, CloneableVector}; use strbuf::StrBuf; @@ -96,7 +85,7 @@ use vec::Vec; pub use core::str::{from_utf8, CharEq, Chars, CharOffsets, RevChars}; pub use core::str::{RevCharOffsets, Bytes, RevBytes, CharSplits, RevCharSplits}; pub use core::str::{CharSplitsN, Words, AnyLines, MatchIndices, StrSplits}; -pub use core::str::{eq_slice, eq, is_utf8, is_utf16, UTF16Items}; +pub use core::str::{eq_slice, is_utf8, is_utf16, UTF16Items}; pub use core::str::{UTF16Item, ScalarValue, LoneSurrogate, utf16_items}; pub use core::str::{truncate_utf16_at_nul, utf8_char_width, CharRange}; pub use core::str::{Str, StrSlice}; @@ -109,17 +98,8 @@ Section: Creating a string /// /// Returns `Err` with the original vector if the vector contains invalid /// UTF-8. -pub fn from_utf8_owned(vv: ~[u8]) -> Result<~str, ~[u8]> { - if is_utf8(vv) { - Ok(unsafe { raw::from_utf8_owned(vv) }) - } else { - Err(vv) - } -} - -impl FromStr for ~str { - #[inline] - fn from_str(s: &str) -> Option<~str> { Some(s.to_owned()) } +pub fn from_utf8_owned(vv: Vec<u8>) -> Result<StrBuf, Vec<u8>> { + StrBuf::from_utf8(vv) } /// Convert a byte to a UTF-8 string @@ -127,35 +107,37 @@ impl FromStr for ~str { /// # Failure /// /// Fails if invalid UTF-8 -pub fn from_byte(b: u8) -> ~str { +pub fn from_byte(b: u8) -> StrBuf { assert!(b < 128u8); - unsafe { ::mem::transmute(box [b]) } + StrBuf::from_char(1, b as char) } /// Convert a char to a string -pub fn from_char(ch: char) -> ~str { +pub fn from_char(ch: char) -> StrBuf { let mut buf = StrBuf::new(); buf.push_char(ch); - buf.into_owned() + buf } /// Convert a vector of chars to a string -pub fn from_chars(chs: &[char]) -> ~str { +pub fn from_chars(chs: &[char]) -> StrBuf { chs.iter().map(|c| *c).collect() } /// Methods for vectors of strings pub trait StrVector { /// Concatenate a vector of strings. - fn concat(&self) -> ~str; + fn concat(&self) -> StrBuf; /// Concatenate a vector of strings, placing a given separator between each. - fn connect(&self, sep: &str) -> ~str; + fn connect(&self, sep: &str) -> StrBuf; } impl<'a, S: Str> StrVector for &'a [S] { - fn concat(&self) -> ~str { - if self.is_empty() { return "".to_owned(); } + fn concat(&self) -> StrBuf { + if self.is_empty() { + return StrBuf::new(); + } // `len` calculation may overflow but push_str but will check boundaries let len = self.iter().map(|s| s.as_slice().len()).sum(); @@ -166,14 +148,18 @@ impl<'a, S: Str> StrVector for &'a [S] { result.push_str(s.as_slice()) } - result.into_owned() + result } - fn connect(&self, sep: &str) -> ~str { - if self.is_empty() { return "".to_owned(); } + fn connect(&self, sep: &str) -> StrBuf { + if self.is_empty() { + return StrBuf::new(); + } // concat is faster - if sep.is_empty() { return self.concat(); } + if sep.is_empty() { + return self.concat(); + } // this is wrong without the guarantee that `self` is non-empty // `len` calculation may overflow but push_str but will check boundaries @@ -190,18 +176,18 @@ impl<'a, S: Str> StrVector for &'a [S] { } result.push_str(s.as_slice()); } - result.into_owned() + result } } impl<'a, S: Str> StrVector for Vec<S> { #[inline] - fn concat(&self) -> ~str { + fn concat(&self) -> StrBuf { self.as_slice().concat() } #[inline] - fn connect(&self, sep: &str) -> ~str { + fn connect(&self, sep: &str) -> StrBuf { self.as_slice().connect(sep) } } @@ -317,7 +303,7 @@ impl<'a> Iterator<char> for Decompositions<'a> { /// # Return value /// /// The original string with all occurrences of `from` replaced with `to` -pub fn replace(s: &str, from: &str, to: &str) -> ~str { +pub fn replace(s: &str, from: &str, to: &str) -> StrBuf { let mut result = StrBuf::new(); let mut last_end = 0; for (start, end) in s.match_indices(from) { @@ -326,7 +312,7 @@ pub fn replace(s: &str, from: &str, to: &str) -> ~str { last_end = end; } result.push_str(unsafe{raw::slice_bytes(s, last_end, s.len())}); - result.into_owned() + result } /* @@ -350,7 +336,7 @@ Section: Misc /// v[4] = 0xD800; /// assert_eq!(str::from_utf16(v), None); /// ``` -pub fn from_utf16(v: &[u16]) -> Option<~str> { +pub fn from_utf16(v: &[u16]) -> Option<StrBuf> { let mut s = StrBuf::with_capacity(v.len() / 2); for c in utf16_items(v) { match c { @@ -358,7 +344,7 @@ pub fn from_utf16(v: &[u16]) -> Option<~str> { LoneSurrogate(_) => return None } } - Some(s.into_owned()) + Some(s) } /// Decode a UTF-16 encoded vector `v` into a string, replacing @@ -376,7 +362,7 @@ pub fn from_utf16(v: &[u16]) -> Option<~str> { /// assert_eq!(str::from_utf16_lossy(v), /// "𝄞mus\uFFFDic\uFFFD".to_owned()); /// ``` -pub fn from_utf16_lossy(v: &[u16]) -> ~str { +pub fn from_utf16_lossy(v: &[u16]) -> StrBuf { utf16_items(v).map(|c| c.to_char_lossy()).collect() } @@ -523,14 +509,14 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> { Section: MaybeOwned */ -/// A MaybeOwned is a string that can hold either a ~str or a &str. +/// A MaybeOwned is a string that can hold either a StrBuf or a &str. /// This can be useful as an optimization when an allocation is sometimes /// needed but not always. pub enum MaybeOwned<'a> { /// A borrowed string Slice(&'a str), /// An owned string - Owned(~str) + Owned(StrBuf) } /// SendStr is a specialization of `MaybeOwned` to be sendable @@ -562,14 +548,11 @@ pub trait IntoMaybeOwned<'a> { fn into_maybe_owned(self) -> MaybeOwned<'a>; } -impl<'a> IntoMaybeOwned<'a> for ~str { - #[inline] - fn into_maybe_owned(self) -> MaybeOwned<'a> { Owned(self) } -} - impl<'a> IntoMaybeOwned<'a> for StrBuf { #[inline] - fn into_maybe_owned(self) -> MaybeOwned<'a> { Owned(self.into_owned()) } + fn into_maybe_owned(self) -> MaybeOwned<'a> { + Owned(self) + } } impl<'a> IntoMaybeOwned<'a> for &'a str { @@ -624,7 +607,7 @@ impl<'a> Str for MaybeOwned<'a> { impl<'a> StrAllocating for MaybeOwned<'a> { #[inline] - fn into_owned(self) -> ~str { + fn into_owned(self) -> StrBuf { match self { Slice(s) => s.to_owned(), Owned(s) => s @@ -657,7 +640,7 @@ impl<'a, H: Writer> ::hash::Hash<H> for MaybeOwned<'a> { fn hash(&self, hasher: &mut H) { match *self { Slice(s) => s.hash(hasher), - Owned(ref s) => s.hash(hasher), + Owned(ref s) => s.as_slice().hash(hasher), } } } @@ -674,58 +657,43 @@ impl<'a> fmt::Show for MaybeOwned<'a> { /// Unsafe operations pub mod raw { + use c_str::CString; use libc; use mem; - use ptr::RawPtr; use raw::Slice; - use slice::CloneableVector; - use str::{is_utf8, StrAllocating}; + use strbuf::StrBuf; + use vec::Vec; pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes}; pub use core::str::raw::{slice_unchecked}; /// Create a Rust string from a *u8 buffer of the given length - pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str { - let v = Slice { data: buf, len: len }; - let bytes: &[u8] = ::mem::transmute(v); - assert!(is_utf8(bytes)); - let s: &str = ::mem::transmute(bytes); - s.to_owned() - } - - #[lang="strdup_uniq"] - #[cfg(not(test))] - #[inline] - unsafe fn strdup_uniq(ptr: *u8, len: uint) -> ~str { - from_buf_len(ptr, len) + pub unsafe fn from_buf_len(buf: *u8, len: uint) -> StrBuf { + let mut result = StrBuf::new(); + result.push_bytes(mem::transmute(Slice { + data: buf, + len: len, + })); + result } /// Create a Rust string from a null-terminated C string - pub unsafe fn from_c_str(buf: *libc::c_char) -> ~str { - let mut curr = buf; - let mut i = 0; - while *curr != 0 { - i += 1; - curr = buf.offset(i); - } - from_buf_len(buf as *u8, i as uint) + pub unsafe fn from_c_str(c_string: *libc::c_char) -> StrBuf { + let mut buf = StrBuf::new(); + buf.push_bytes(CString::new(c_string, false).as_bytes_no_nul()); + buf } /// Converts an owned vector of bytes to a new owned string. This assumes /// that the utf-8-ness of the vector has already been validated #[inline] - pub unsafe fn from_utf8_owned(v: ~[u8]) -> ~str { + pub unsafe fn from_utf8_owned(v: Vec<u8>) -> StrBuf { mem::transmute(v) } /// Converts a byte to a string. - pub unsafe fn from_byte(u: u8) -> ~str { from_utf8_owned(box [u]) } - - /// Access the str in its vector representation. - /// The caller must preserve the valid UTF-8 property when modifying. - #[inline] - pub unsafe fn as_owned_vec<'a>(s: &'a mut ~str) -> &'a mut ~[u8] { - mem::transmute(s) + pub unsafe fn from_byte(u: u8) -> StrBuf { + from_utf8_owned(vec![u]) } /// Sets the length of a string @@ -753,8 +721,8 @@ Section: Trait implementations /// Any string that can be represented as a slice pub trait StrAllocating: Str { - /// Convert `self` into a ~str, not making a copy if possible. - fn into_owned(self) -> ~str; + /// Convert `self` into a `StrBuf`, not making a copy if possible. + fn into_owned(self) -> StrBuf; /// Convert `self` into a `StrBuf`. #[inline] @@ -765,27 +733,27 @@ pub trait StrAllocating: Str { /// Convert `self` into a `StrBuf`, not making a copy if possible. #[inline] fn into_strbuf(self) -> StrBuf { - StrBuf::from_owned_str(self.into_owned()) + self.into_owned() } /// Escape each char in `s` with `char::escape_default`. - fn escape_default(&self) -> ~str { + fn escape_default(&self) -> StrBuf { let me = self.as_slice(); let mut out = StrBuf::with_capacity(me.len()); for c in me.chars() { c.escape_default(|c| out.push_char(c)); } - out.into_owned() + out } /// Escape each char in `s` with `char::escape_unicode`. - fn escape_unicode(&self) -> ~str { + fn escape_unicode(&self) -> StrBuf { let me = self.as_slice(); let mut out = StrBuf::with_capacity(me.len()); for c in me.chars() { c.escape_unicode(|c| out.push_char(c)); } - out.into_owned() + out } /// Replace all occurrences of one string with another. @@ -812,7 +780,7 @@ pub trait StrAllocating: Str { /// // not found, so no change. /// assert_eq!(s.replace("cookie monster", "little lamb"), s); /// ``` - fn replace(&self, from: &str, to: &str) -> ~str { + fn replace(&self, from: &str, to: &str) -> StrBuf { let me = self.as_slice(); let mut result = StrBuf::new(); let mut last_end = 0; @@ -822,16 +790,16 @@ pub trait StrAllocating: Str { last_end = end; } result.push_str(unsafe{raw::slice_bytes(me, last_end, me.len())}); - result.into_owned() + result } - /// Copy a slice into a new owned str. + /// Copy a slice into a new `StrBuf`. #[inline] - fn to_owned(&self) -> ~str { + fn to_owned(&self) -> StrBuf { use slice::Vector; unsafe { - ::mem::transmute(self.as_slice().as_bytes().to_owned()) + ::mem::transmute(Vec::from_slice(self.as_slice().as_bytes())) } } @@ -848,13 +816,13 @@ pub trait StrAllocating: Str { } /// Given a string, make a new string with repeated copies of it. - fn repeat(&self, nn: uint) -> ~str { + fn repeat(&self, nn: uint) -> StrBuf { let me = self.as_slice(); let mut ret = StrBuf::with_capacity(nn * me.len()); for _ in range(0, nn) { ret.push_str(me); } - ret.into_owned() + ret } /// Levenshtein Distance between two strings. @@ -919,12 +887,9 @@ pub trait StrAllocating: Str { impl<'a> StrAllocating for &'a str { #[inline] - fn into_owned(self) -> ~str { self.to_owned() } -} - -impl<'a> StrAllocating for ~str { - #[inline] - fn into_owned(self) -> ~str { self } + fn into_owned(self) -> StrBuf { + self.to_owned() + } } /// Methods for owned strings @@ -932,23 +897,23 @@ pub trait OwnedStr { /// Consumes the string, returning the underlying byte buffer. /// /// The buffer does not have a null terminator. - fn into_bytes(self) -> ~[u8]; + fn into_bytes(self) -> Vec<u8>; /// Pushes the given string onto this string, returning the concatenation of the two strings. - fn append(self, rhs: &str) -> ~str; + fn append(self, rhs: &str) -> StrBuf; } -impl OwnedStr for ~str { +impl OwnedStr for StrBuf { #[inline] - fn into_bytes(self) -> ~[u8] { + fn into_bytes(self) -> Vec<u8> { unsafe { mem::transmute(self) } } #[inline] - fn append(self, rhs: &str) -> ~str { + fn append(self, rhs: &str) -> StrBuf { let mut new_str = StrBuf::from_owned_str(self); new_str.push_str(rhs); - new_str.into_owned() + new_str } } @@ -961,13 +926,6 @@ mod tests { use strbuf::StrBuf; #[test] - fn test_eq() { - assert!((eq(&"".to_owned(), &"".to_owned()))); - assert!((eq(&"foo".to_owned(), &"foo".to_owned()))); - assert!((!eq(&"foo".to_owned(), &"bar".to_owned()))); - } - - #[test] fn test_eq_slice() { assert!((eq_slice("foobar".slice(0, 3), "foo"))); assert!((eq_slice("barfoo".slice(3, 6), "foo"))); @@ -1025,10 +983,10 @@ mod tests { #[test] fn test_collect() { let empty = "".to_owned(); - let s: ~str = empty.chars().collect(); + let s: StrBuf = empty.as_slice().chars().collect(); assert_eq!(empty, s); let data = "ประเทศไทย中".to_owned(); - let s: ~str = data.chars().collect(); + let s: StrBuf = data.as_slice().chars().collect(); assert_eq!(data, s); } @@ -1050,23 +1008,24 @@ mod tests { assert_eq!(data.slice(2u, 6u).find_str("ab"), Some(3u - 2u)); assert!(data.slice(2u, 4u).find_str("ab").is_none()); - let mut data = "ประเทศไทย中华Việt Nam".to_owned(); - data = data + data; - assert!(data.find_str("ไท华").is_none()); - assert_eq!(data.slice(0u, 43u).find_str(""), Some(0u)); - assert_eq!(data.slice(6u, 43u).find_str(""), Some(6u - 6u)); + let string = "ประเทศไทย中华Việt Nam"; + let mut data = string.to_strbuf(); + data.push_str(string); + assert!(data.as_slice().find_str("ไท华").is_none()); + assert_eq!(data.as_slice().slice(0u, 43u).find_str(""), Some(0u)); + assert_eq!(data.as_slice().slice(6u, 43u).find_str(""), Some(6u - 6u)); - assert_eq!(data.slice(0u, 43u).find_str("ประ"), Some( 0u)); - assert_eq!(data.slice(0u, 43u).find_str("ทศไ"), Some(12u)); - assert_eq!(data.slice(0u, 43u).find_str("ย中"), Some(24u)); - assert_eq!(data.slice(0u, 43u).find_str("iệt"), Some(34u)); - assert_eq!(data.slice(0u, 43u).find_str("Nam"), Some(40u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ประ"), Some( 0u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ทศไ"), Some(12u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ย中"), Some(24u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("iệt"), Some(34u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("Nam"), Some(40u)); - assert_eq!(data.slice(43u, 86u).find_str("ประ"), Some(43u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("ย中"), Some(67u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("iệt"), Some(77u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("Nam"), Some(83u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ประ"), Some(43u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ย中"), Some(67u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("iệt"), Some(77u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("Nam"), Some(83u - 43u)); } #[test] @@ -1084,25 +1043,25 @@ mod tests { #[test] fn test_concat() { - fn t(v: &[~str], s: &str) { - assert_eq!(v.concat(), s.to_str()); + fn t(v: &[StrBuf], s: &str) { + assert_eq!(v.concat(), s.to_str().into_owned()); } t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(), "no".to_owned(), "good".to_owned()], "youknowI'mnogood"); - let v: &[~str] = []; + let v: &[StrBuf] = []; t(v, ""); t(["hi".to_owned()], "hi"); } #[test] fn test_connect() { - fn t(v: &[~str], sep: &str, s: &str) { - assert_eq!(v.connect(sep), s.to_str()); + fn t(v: &[StrBuf], sep: &str, s: &str) { + assert_eq!(v.connect(sep), s.to_str().into_owned()); } t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(), "no".to_owned(), "good".to_owned()], " ", "you know I'm no good"); - let v: &[~str] = []; + let v: &[StrBuf] = []; t(v, " ", ""); t(["hi".to_owned()], " ", "hi"); } @@ -1110,7 +1069,7 @@ mod tests { #[test] fn test_concat_slices() { fn t(v: &[&str], s: &str) { - assert_eq!(v.concat(), s.to_str()); + assert_eq!(v.concat(), s.to_str().into_owned()); } t(["you", "know", "I'm", "no", "good"], "youknowI'mnogood"); let v: &[&str] = []; @@ -1121,7 +1080,7 @@ mod tests { #[test] fn test_connect_slices() { fn t(v: &[&str], sep: &str, s: &str) { - assert_eq!(v.connect(sep), s.to_str()); + assert_eq!(v.connect(sep), s.to_str().into_owned()); } t(["you", "know", "I'm", "no", "good"], " ", "you know I'm no good"); @@ -1143,27 +1102,29 @@ mod tests { assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)}); assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)}); assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)}); - fn a_million_letter_a() -> ~str { + fn a_million_letter_a() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("aaaaaaaaaa"); i += 1; } - rs.into_owned() + rs } - fn half_a_million_letter_a() -> ~str { + fn half_a_million_letter_a() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("aaaaa"); i += 1; } - rs.into_owned() + rs } let letters = a_million_letter_a(); assert!(half_a_million_letter_a() == - unsafe {raw::slice_bytes(letters, 0u, 500000)}.to_owned()); + unsafe {raw::slice_bytes(letters.as_slice(), + 0u, + 500000)}.to_owned()); } #[test] @@ -1208,41 +1169,41 @@ mod tests { #[test] fn test_replace_2a() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let a = "ประเ".to_owned(); - let a2 = "دولة الكويتทศไทย中华".to_owned(); - assert_eq!(data.replace(a, repl), a2); + let a = "ประเ"; + let a2 = "دولة الكويتทศไทย中华"; + assert_eq!(data.replace(a, repl).as_slice(), a2); } #[test] fn test_replace_2b() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let b = "ะเ".to_owned(); - let b2 = "ปรدولة الكويتทศไทย中华".to_owned(); - assert_eq!(data.replace(b, repl), b2); + let b = "ะเ"; + let b2 = "ปรدولة الكويتทศไทย中华"; + assert_eq!(data.replace(b, repl).as_slice(), b2); } #[test] fn test_replace_2c() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let c = "中华".to_owned(); - let c2 = "ประเทศไทยدولة الكويت".to_owned(); - assert_eq!(data.replace(c, repl), c2); + let c = "中华"; + let c2 = "ประเทศไทยدولة الكويت"; + assert_eq!(data.replace(c, repl).as_slice(), c2); } #[test] fn test_replace_2d() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let d = "ไท华".to_owned(); - assert_eq!(data.replace(d, repl), data); + let d = "ไท华"; + assert_eq!(data.replace(d, repl).as_slice(), data); } #[test] @@ -1258,27 +1219,27 @@ mod tests { assert_eq!("", data.slice(3, 3)); assert_eq!("华", data.slice(30, 33)); - fn a_million_letter_X() -> ~str { + fn a_million_letter_X() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("华华华华华华华华华华"); i += 1; } - rs.into_owned() + rs } - fn half_a_million_letter_X() -> ~str { + fn half_a_million_letter_X() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("华华华华华"); i += 1; } - rs.into_owned() + rs } let letters = a_million_letter_X(); assert!(half_a_million_letter_X() == - letters.slice(0u, 3u * 500000u).to_owned()); + letters.as_slice().slice(0u, 3u * 500000u).to_owned()); } #[test] @@ -1571,17 +1532,17 @@ mod tests { #[test] fn vec_str_conversions() { - let s1: ~str = "All mimsy were the borogoves".to_owned(); + let s1: StrBuf = "All mimsy were the borogoves".to_strbuf(); - let v: ~[u8] = s1.as_bytes().to_owned(); - let s2: ~str = from_utf8(v).unwrap().to_owned(); + let v: Vec<u8> = Vec::from_slice(s1.as_bytes()); + let s2: StrBuf = from_utf8(v.as_slice()).unwrap().to_strbuf(); let mut i: uint = 0u; let n1: uint = s1.len(); let n2: uint = v.len(); assert_eq!(n1, n2); while i < n1 { - let a: u8 = s1[i]; - let b: u8 = s2[i]; + let a: u8 = s1.as_slice()[i]; + let b: u8 = s2.as_slice()[i]; debug!("{}", a); debug!("{}", b); assert_eq!(a, b); @@ -1599,7 +1560,7 @@ mod tests { assert!(!"abcde".contains("def")); assert!(!"".contains("a")); - let data = "ประเทศไทย中华Việt Nam".to_owned(); + let data = "ประเทศไทย中华Việt Nam"; assert!(data.contains("ประเ")); assert!(data.contains("ะเ")); assert!(data.contains("中华")); @@ -1719,7 +1680,7 @@ mod tests { #[test] fn test_char_at() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; for ch in v.iter() { @@ -1730,7 +1691,7 @@ mod tests { #[test] fn test_char_at_reverse() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = s.len(); for ch in v.iter().rev() { @@ -1775,7 +1736,7 @@ mod tests { #[test] fn test_char_range_at() { - let data = "b¢€𤭢𤭢€¢b".to_owned(); + let data = "b¢€𤭢𤭢€¢b"; assert_eq!('b', data.char_range_at(0).ch); assert_eq!('¢', data.char_range_at(1).ch); assert_eq!('€', data.char_range_at(3).ch); @@ -1792,28 +1753,9 @@ mod tests { } #[test] - fn test_add() { - #![allow(unnecessary_allocation)] - macro_rules! t ( - ($s1:expr, $s2:expr, $e:expr) => { { - let s1 = $s1; - let s2 = $s2; - let e = $e; - assert_eq!(s1 + s2, e.to_owned()); - assert_eq!(s1.to_owned() + s2, e.to_owned()); - } } - ); - - t!("foo", "bar", "foobar"); - t!("foo", "bar".to_owned(), "foobar"); - t!("ศไทย中", "华Việt Nam", "ศไทย中华Việt Nam"); - t!("ศไทย中", "华Việt Nam".to_owned(), "ศไทย中华Việt Nam"); - } - - #[test] fn test_iterator() { use iter::*; - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; @@ -1829,7 +1771,7 @@ mod tests { #[test] fn test_rev_iterator() { use iter::*; - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ']; let mut pos = 0; @@ -1852,7 +1794,7 @@ mod tests { #[test] fn test_bytesator() { - let s = "ศไทย中华Việt Nam".to_owned(); + 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, @@ -1868,7 +1810,7 @@ mod tests { #[test] fn test_bytes_revator() { - let s = "ศไทย中华Việt Nam".to_owned(); + 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, @@ -2025,30 +1967,30 @@ mod tests { #[test] fn test_nfd_chars() { - assert_eq!("abc".nfd_chars().collect::<~str>(), "abc".to_owned()); - assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<~str>(), "d\u0307\u01c4".to_owned()); - assert_eq!("\u2026".nfd_chars().collect::<~str>(), "\u2026".to_owned()); - assert_eq!("\u2126".nfd_chars().collect::<~str>(), "\u03a9".to_owned()); - assert_eq!("\u1e0b\u0323".nfd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("\u1e0d\u0307".nfd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("a\u0301".nfd_chars().collect::<~str>(), "a\u0301".to_owned()); - assert_eq!("\u0301a".nfd_chars().collect::<~str>(), "\u0301a".to_owned()); - assert_eq!("\ud4db".nfd_chars().collect::<~str>(), "\u1111\u1171\u11b6".to_owned()); - assert_eq!("\uac1c".nfd_chars().collect::<~str>(), "\u1100\u1162".to_owned()); + assert_eq!("abc".nfd_chars().collect::<StrBuf>(), "abc".to_strbuf()); + assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<StrBuf>(), "d\u0307\u01c4".to_strbuf()); + assert_eq!("\u2026".nfd_chars().collect::<StrBuf>(), "\u2026".to_strbuf()); + assert_eq!("\u2126".nfd_chars().collect::<StrBuf>(), "\u03a9".to_strbuf()); + assert_eq!("\u1e0b\u0323".nfd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf()); + assert_eq!("\u1e0d\u0307".nfd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf()); + assert_eq!("a\u0301".nfd_chars().collect::<StrBuf>(), "a\u0301".to_strbuf()); + assert_eq!("\u0301a".nfd_chars().collect::<StrBuf>(), "\u0301a".to_strbuf()); + assert_eq!("\ud4db".nfd_chars().collect::<StrBuf>(), "\u1111\u1171\u11b6".to_strbuf()); + assert_eq!("\uac1c".nfd_chars().collect::<StrBuf>(), "\u1100\u1162".to_strbuf()); } #[test] fn test_nfkd_chars() { - assert_eq!("abc".nfkd_chars().collect::<~str>(), "abc".to_owned()); - assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<~str>(), "d\u0307DZ\u030c".to_owned()); - assert_eq!("\u2026".nfkd_chars().collect::<~str>(), "...".to_owned()); - assert_eq!("\u2126".nfkd_chars().collect::<~str>(), "\u03a9".to_owned()); - assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("a\u0301".nfkd_chars().collect::<~str>(), "a\u0301".to_owned()); - assert_eq!("\u0301a".nfkd_chars().collect::<~str>(), "\u0301a".to_owned()); - assert_eq!("\ud4db".nfkd_chars().collect::<~str>(), "\u1111\u1171\u11b6".to_owned()); - assert_eq!("\uac1c".nfkd_chars().collect::<~str>(), "\u1100\u1162".to_owned()); + assert_eq!("abc".nfkd_chars().collect::<StrBuf>(), "abc".to_strbuf()); + assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<StrBuf>(), "d\u0307DZ\u030c".to_strbuf()); + assert_eq!("\u2026".nfkd_chars().collect::<StrBuf>(), "...".to_strbuf()); + assert_eq!("\u2126".nfkd_chars().collect::<StrBuf>(), "\u03a9".to_strbuf()); + assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf()); + assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf()); + assert_eq!("a\u0301".nfkd_chars().collect::<StrBuf>(), "a\u0301".to_strbuf()); + assert_eq!("\u0301a".nfkd_chars().collect::<StrBuf>(), "\u0301a".to_strbuf()); + assert_eq!("\ud4db".nfkd_chars().collect::<StrBuf>(), "\u1111\u1171\u11b6".to_strbuf()); + assert_eq!("\uac1c".nfkd_chars().collect::<StrBuf>(), "\u1100\u1162".to_strbuf()); } #[test] @@ -2093,7 +2035,7 @@ mod tests { } t::<&str>(); - t::<~str>(); + t::<StrBuf>(); } #[test] @@ -2122,14 +2064,15 @@ mod tests { #[test] fn test_str_from_utf8_owned() { - let xs = bytes!("hello").to_owned(); + let xs = Vec::from_slice(bytes!("hello")); assert_eq!(from_utf8_owned(xs), Ok("hello".to_owned())); - let xs = bytes!("ศไทย中华Việt Nam").to_owned(); + let xs = Vec::from_slice(bytes!("ศไทย中华Việt Nam")); assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_owned())); - let xs = bytes!("hello", 0xff).to_owned(); - assert_eq!(from_utf8_owned(xs), Err(bytes!("hello", 0xff).to_owned())); + let xs = Vec::from_slice(bytes!("hello", 0xff)); + assert_eq!(from_utf8_owned(xs), + Err(Vec::from_slice(bytes!("hello", 0xff)))); } #[test] @@ -2167,8 +2110,8 @@ mod tests { #[test] fn test_from_str() { - let owned: Option<~str> = from_str("string"); - assert_eq!(owned, Some("string".to_owned())); + let owned: Option<StrBuf> = from_str("string"); + assert_eq!(owned, Some("string".to_strbuf())); } #[test] @@ -2176,16 +2119,16 @@ mod tests { let s = Slice("abcde"); assert_eq!(s.len(), 5); assert_eq!(s.as_slice(), "abcde"); - assert_eq!(s.to_str(), "abcde".to_owned()); - assert_eq!(format!("{}", s), "abcde".to_owned()); + assert_eq!(s.to_str(), "abcde".to_strbuf()); + assert_eq!(format_strbuf!("{}", s), "abcde".to_strbuf()); assert!(s.lt(&Owned("bcdef".to_owned()))); assert_eq!(Slice(""), Default::default()); let o = Owned("abcde".to_owned()); assert_eq!(o.len(), 5); assert_eq!(o.as_slice(), "abcde"); - assert_eq!(o.to_str(), "abcde".to_owned()); - assert_eq!(format!("{}", o), "abcde".to_owned()); + assert_eq!(o.to_str(), "abcde".to_strbuf()); + assert_eq!(format_strbuf!("{}", o), "abcde".to_strbuf()); assert!(o.lt(&Slice("bcdef"))); assert_eq!(Owned("".to_owned()), Default::default()); diff --git a/src/libstd/strbuf.rs b/src/libstd/strbuf.rs index de480ef1b7f..dd462ff5ab5 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -12,8 +12,11 @@ use c_vec::CVec; use char::Char; +use cmp::Equiv; use container::{Container, Mutable}; +use default::Default; use fmt; +use from_str::FromStr; use io::Writer; use iter::{Extendable, FromIterator, Iterator, range}; use mem; @@ -21,8 +24,8 @@ use option::{None, Option, Some}; use ptr::RawPtr; use ptr; use result::{Result, Ok, Err}; -use slice::{OwnedVector, Vector, CloneableVector}; -use str::{CharRange, OwnedStr, Str, StrSlice, StrAllocating}; +use slice::Vector; +use str::{CharRange, Str, StrSlice, StrAllocating}; use str; use vec::Vec; @@ -67,10 +70,8 @@ impl StrBuf { /// Creates a new string buffer from the given owned string, taking care not to copy it. #[inline] - pub fn from_owned_str(string: ~str) -> StrBuf { - StrBuf { - vec: string.into_bytes().move_iter().collect(), - } + pub fn from_owned_str(string: StrBuf) -> StrBuf { + string } /// Returns the vector as a string buffer, if possible, taking care not to @@ -191,6 +192,13 @@ impl StrBuf { self.vec.as_slice() } + /// Works with the underlying buffer as a mutable byte slice. Unsafe + /// because this can be used to violate the UTF-8 property. + #[inline] + pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] { + self.vec.as_mut_slice() + } + /// Shorten a string to the specified length (which must be <= the current length) #[inline] pub fn truncate(&mut self, len: uint) { @@ -314,14 +322,20 @@ impl Str for StrBuf { impl StrAllocating for StrBuf { #[inline] - fn into_owned(self) -> ~str { - unsafe { - mem::transmute(self.vec.as_slice().to_owned()) - } + fn into_owned(self) -> StrBuf { + self } #[inline] - fn into_strbuf(self) -> StrBuf { self } + fn into_strbuf(self) -> StrBuf { + self + } +} + +impl Default for StrBuf { + fn default() -> StrBuf { + StrBuf::new() + } } impl fmt::Show for StrBuf { @@ -337,6 +351,20 @@ impl<H:Writer> ::hash::Hash<H> for StrBuf { } } +impl<'a, S: Str> Equiv<S> for StrBuf { + #[inline] + fn equiv(&self, other: &S) -> bool { + self.as_slice() == other.as_slice() + } +} + +impl FromStr for StrBuf { + #[inline] + fn from_str(s: &str) -> Option<StrBuf> { + Some(s.to_strbuf()) + } +} + #[cfg(test)] mod tests { extern crate test; diff --git a/src/libstd/task.rs b/src/libstd/task.rs index 5c875b4a2ad..314f659550d 100644 --- a/src/libstd/task.rs +++ b/src/libstd/task.rs @@ -51,6 +51,7 @@ use str::{Str, SendStr, IntoMaybeOwned}; #[cfg(test)] use owned::AnyOwnExt; #[cfg(test)] use result; #[cfg(test)] use str::StrAllocating; +#[cfg(test)] use strbuf::StrBuf; /// Indicates the manner in which a task exited. /// @@ -496,12 +497,12 @@ fn test_try_fail_message_static_str() { #[test] fn test_try_fail_message_owned_str() { match try(proc() { - fail!("owned string".to_owned()); + fail!("owned string".to_strbuf()); }) { Err(e) => { - type T = ~str; + type T = StrBuf; assert!(e.is::<T>()); - assert_eq!(*e.move::<T>().unwrap(), "owned string".to_owned()); + assert_eq!(*e.move::<T>().unwrap(), "owned string".to_strbuf()); } Ok(()) => fail!() } diff --git a/src/libstd/to_str.rs b/src/libstd/to_str.rs index 4132c8a5b5a..fbc4227e726 100644 --- a/src/libstd/to_str.rs +++ b/src/libstd/to_str.rs @@ -15,21 +15,24 @@ The `ToStr` trait for converting to strings */ use fmt; +use strbuf::StrBuf; /// A generic trait for converting a value to a string pub trait ToStr { /// Converts the value of `self` to an owned string - fn to_str(&self) -> ~str; + fn to_str(&self) -> StrBuf; } /// Trait for converting a type to a string, consuming it in the process. pub trait IntoStr { /// Consume and convert to a string. - fn into_str(self) -> ~str; + fn into_str(self) -> StrBuf; } impl<T: fmt::Show> ToStr for T { - fn to_str(&self) -> ~str { format!("{}", *self) } + fn to_str(&self) -> StrBuf { + format_strbuf!("{}", *self) + } } #[cfg(test)] @@ -39,23 +42,23 @@ mod tests { #[test] fn test_simple_types() { - assert_eq!(1i.to_str(), "1".to_owned()); - assert_eq!((-1i).to_str(), "-1".to_owned()); - assert_eq!(200u.to_str(), "200".to_owned()); - assert_eq!(2u8.to_str(), "2".to_owned()); - assert_eq!(true.to_str(), "true".to_owned()); - assert_eq!(false.to_str(), "false".to_owned()); - assert_eq!(().to_str(), "()".to_owned()); - assert_eq!(("hi".to_owned()).to_str(), "hi".to_owned()); + assert_eq!(1i.to_str(), "1".to_strbuf()); + assert_eq!((-1i).to_str(), "-1".to_strbuf()); + assert_eq!(200u.to_str(), "200".to_strbuf()); + assert_eq!(2u8.to_str(), "2".to_strbuf()); + assert_eq!(true.to_str(), "true".to_strbuf()); + assert_eq!(false.to_str(), "false".to_strbuf()); + assert_eq!(().to_str(), "()".to_strbuf()); + assert_eq!(("hi".to_strbuf()).to_str(), "hi".to_strbuf()); } #[test] fn test_vectors() { let x: ~[int] = box []; - assert_eq!(x.to_str(), "[]".to_owned()); - assert_eq!((box [1]).to_str(), "[1]".to_owned()); - assert_eq!((box [1, 2, 3]).to_str(), "[1, 2, 3]".to_owned()); + assert_eq!(x.to_str(), "[]".to_strbuf()); + assert_eq!((box [1]).to_str(), "[1]".to_strbuf()); + assert_eq!((box [1, 2, 3]).to_str(), "[1, 2, 3]".to_strbuf()); assert!((box [box [], box [1], box [1, 1]]).to_str() == - "[[], [1], [1, 1]]".to_owned()); + "[[], [1], [1, 1]]".to_strbuf()); } } diff --git a/src/libstd/unstable/dynamic_lib.rs b/src/libstd/unstable/dynamic_lib.rs index d50c63c5832..8e85283ee55 100644 --- a/src/libstd/unstable/dynamic_lib.rs +++ b/src/libstd/unstable/dynamic_lib.rs @@ -27,6 +27,7 @@ use path::{Path,GenericPath}; use result::*; use slice::{Vector,ImmutableVector}; use str; +use strbuf::StrBuf; use vec::Vec; pub struct DynamicLibrary { handle: *u8} @@ -56,7 +57,7 @@ impl DynamicLibrary { /// Lazily open a dynamic library. When passed None it gives a /// handle to the calling process pub fn open<T: ToCStr>(filename: Option<T>) - -> Result<DynamicLibrary, ~str> { + -> Result<DynamicLibrary, StrBuf> { unsafe { let mut filename = filename; let maybe_library = dl::check_for_errors_in(|| { @@ -118,7 +119,9 @@ impl DynamicLibrary { let mut ret = Vec::new(); match os::getenv_as_bytes(DynamicLibrary::envvar()) { Some(env) => { - for portion in env.split(|a| *a == DynamicLibrary::separator()) { + for portion in + env.as_slice() + .split(|a| *a == DynamicLibrary::separator()) { ret.push(Path::new(portion)); } } @@ -128,7 +131,7 @@ impl DynamicLibrary { } /// Access the value at the symbol of the dynamic library - pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, ~str> { + pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, StrBuf> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented @@ -203,10 +206,12 @@ mod test { pub mod dl { use prelude::*; - use c_str::ToCStr; + use c_str::{CString, ToCStr}; use libc; use ptr; - use str; + use result::*; + use str::StrAllocating; + use strbuf::StrBuf; pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 { filename.with_c_str(|raw_name| { @@ -218,7 +223,7 @@ pub mod dl { dlopen(ptr::null(), Lazy as libc::c_int) as *u8 } - pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { + pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, StrBuf> { use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT; unsafe { @@ -233,7 +238,9 @@ pub mod dl { let ret = if ptr::null() == last_error { Ok(result) } else { - Err(str::raw::from_c_str(last_error)) + Err(CString::new(last_error, false).as_str() + .unwrap() + .to_strbuf()) }; ret @@ -269,6 +276,7 @@ pub mod dl { use os; use ptr; use result::{Ok, Err, Result}; + use strbuf::StrBuf; use str; use c_str::ToCStr; @@ -287,7 +295,7 @@ pub mod dl { handle as *u8 } - pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { + pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, StrBuf> { unsafe { SetLastError(0); diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 32883707615..1776b6fbe6e 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -671,7 +671,7 @@ impl<T> Vec<T> { /// ```rust /// let v = vec!("a".to_owned(), "b".to_owned()); /// for s in v.move_iter() { - /// // s has type ~str, not &~str + /// // s has type StrBuf, not &StrBuf /// println!("{}", s); /// } /// ``` @@ -1849,9 +1849,9 @@ mod tests { let b: ~[u8] = FromVec::from_vec(a); assert_eq!(b.as_slice(), &[]); - let a = vec!["one".to_owned(), "two".to_owned()]; - let b: ~[~str] = FromVec::from_vec(a); - assert_eq!(b.as_slice(), &["one".to_owned(), "two".to_owned()]); + let a = vec!["one".to_strbuf(), "two".to_strbuf()]; + let b: ~[StrBuf] = FromVec::from_vec(a); + assert_eq!(b.as_slice(), &["one".to_strbuf(), "two".to_strbuf()]); struct Foo { x: uint, |
