diff options
| author | Patrick Walton <pcwalton@mimiga.net> | 2014-05-16 10:45:16 -0700 |
|---|---|---|
| committer | Patrick Walton <pcwalton@mimiga.net> | 2014-05-22 14:42:01 -0700 |
| commit | 36195eb91f15975fed7555a3aa52807ecd5698a1 (patch) | |
| tree | d0e99310be4a24e76b8d6b13f05ec79c1f89b6ba /src/libstd | |
| parent | e402e75f4eb79af09b9451f0f232f994b3e2c998 (diff) | |
| download | rust-36195eb91f15975fed7555a3aa52807ecd5698a1.tar.gz rust-36195eb91f15975fed7555a3aa52807ecd5698a1.zip | |
libstd: Remove `~str` from all `libstd` modules except `fmt` and `str`.
Diffstat (limited to 'src/libstd')
50 files changed, 494 insertions, 442 deletions
diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index e087b3d1774..8240211a839 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 { +unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> StrBuf { let mut s = string.to_owned(); for b in str::raw::as_owned_vec(&mut s).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())) + 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())) + 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()))); 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/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..6feaf10d5c5 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) } @@ -952,9 +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_str = + (prefix + n.to_str().into_owned()).to_owned(); let msg = msg_str.as_bytes(); check!(w.write(msg)); } @@ -1039,7 +1041,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 +1058,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..f1f3e0a468a 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,18 @@ 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.contains(format!("{}={}", + *k, + *v).as_slice()) || + output.contains(format!("{}=\'{}\'", + *k, + *v).as_slice())); } } }) @@ -835,9 +841,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..b9181793051 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -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..349f50b8ac7 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, CloneableVector, 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)] @@ -108,7 +109,7 @@ pub mod win32 { 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,10 +175,10 @@ 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).to_strbuf(); + let v = str::from_utf8_lossy(v).to_strbuf(); (k,v) }).collect() } @@ -273,8 +274,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).to_strbuf()) } #[cfg(unix)] @@ -302,7 +303,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}; @@ -432,8 +433,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 @@ -688,11 +689,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 +733,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 +790,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) } @@ -851,12 +852,14 @@ 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).into_strbuf()) + .collect() } #[cfg(windows)] -fn real_args() -> Vec<~str> { +fn real_args() -> Vec<StrBuf> { use slice; use option::Expect; @@ -910,10 +913,17 @@ 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]> { @@ -1509,37 +1519,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 +1557,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 +1599,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 +1610,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 +1622,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 +1651,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] 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/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..7aebb6e4796 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) 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..0b4db05545c 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -569,7 +569,9 @@ impl<'a> IntoMaybeOwned<'a> for ~str { 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.into_owned()) + } } impl<'a> IntoMaybeOwned<'a> for &'a str { @@ -657,7 +659,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), } } } @@ -1085,7 +1087,7 @@ mod tests { #[test] fn test_concat() { fn t(v: &[~str], s: &str) { - assert_eq!(v.concat(), s.to_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"); @@ -1097,7 +1099,7 @@ mod tests { #[test] fn test_connect() { 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".to_owned(), "know".to_owned(), "I'm".to_owned(), "no".to_owned(), "good".to_owned()], @@ -1110,7 +1112,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 +1123,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"); @@ -2176,16 +2178,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..bb5b94d86fa 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -12,6 +12,7 @@ use c_vec::CVec; use char::Char; +use cmp::Equiv; use container::{Container, Mutable}; use fmt; use io::Writer; @@ -337,6 +338,13 @@ 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() + } +} + #[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..f73ebc2255b 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(|| { @@ -128,7 +129,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 +204,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 +221,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 +236,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 @@ -287,7 +292,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, |
