From 36195eb91f15975fed7555a3aa52807ecd5698a1 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 16 May 2014 10:45:16 -0700 Subject: libstd: Remove `~str` from all `libstd` modules except `fmt` and `str`. --- src/libsyntax/parse/attr.rs | 2 +- src/libsyntax/parse/mod.rs | 8 ++- src/libsyntax/parse/obsolete.rs | 8 ++- src/libsyntax/parse/parser.rs | 127 ++++++++++++++++++++++++---------------- 4 files changed, 89 insertions(+), 56 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 80ee459a62d..6f17412fa63 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -88,7 +88,7 @@ impl<'a> ParserAttr for Parser<'a> { _ => { let token_str = self.this_token_to_str(); self.fatal(format!("expected `\\#` but found `{}`", - token_str)); + token_str).as_slice()); } }; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 8e139b049c5..31a67ff92f5 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -224,7 +224,9 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) let bytes = match File::open(path).read_to_end() { Ok(bytes) => bytes, Err(e) => { - err(format!("couldn't read {}: {}", path.display(), e)); + err(format!("couldn't read {}: {}", + path.display(), + e).as_slice()); unreachable!() } }; @@ -233,7 +235,9 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) return string_to_filemap(sess, s.to_strbuf(), path.as_str().unwrap().to_strbuf()) } - None => err(format!("{} is not UTF-8 encoded", path.display())), + None => { + err(format!("{} is not UTF-8 encoded", path.display()).as_slice()) + } } unreachable!() } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index b6aa47128e6..394b68d4a72 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -158,10 +158,14 @@ impl<'a> ParserObsoleteMethods for Parser<'a> { kind: ObsoleteSyntax, kind_str: &str, desc: &str) { - self.span_err(sp, format!("obsolete syntax: {}", kind_str)); + self.span_err(sp, + format!("obsolete syntax: {}", kind_str).as_slice()); if !self.obsolete_set.contains(&kind) { - self.sess.span_diagnostic.handler().note(format!("{}", desc)); + self.sess + .span_diagnostic + .handler() + .note(format!("{}", desc).as_slice()); self.obsolete_set.insert(kind); } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 5829f63b2c5..6bddb45201c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -371,12 +371,12 @@ impl<'a> Parser<'a> { pub fn unexpected_last(&mut self, t: &token::Token) -> ! { let token_str = Parser::token_to_str(t); self.span_fatal(self.last_span, format!("unexpected token: `{}`", - token_str)); + token_str).as_slice()); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_str(); - self.fatal(format!("unexpected token: `{}`", this_token)); + self.fatal(format!("unexpected token: `{}`", this_token).as_slice()); } // expect and consume the token t. Signal an error if @@ -389,7 +389,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_str(); self.fatal(format!("expected `{}` but found `{}`", token_str, - this_token_str)) + this_token_str).as_slice()) } } @@ -420,11 +420,15 @@ impl<'a> Parser<'a> { let expect = tokens_to_str(expected.as_slice()); let actual = self.this_token_to_str(); self.fatal( - if expected.len() != 1 { - format!("expected one of `{}` but found `{}`", expect, actual) + (if expected.len() != 1 { + (format!("expected one of `{}` but found `{}`", + expect, + actual)) } else { - format!("expected `{}` but found `{}`", expect, actual) - } + (format!("expected `{}` but found `{}`", + expect, + actual)) + }).as_slice() ) } } @@ -501,7 +505,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_str(); - self.fatal(format!( "expected ident, found `{}`", token_str)) + self.fatal((format!("expected ident, found `{}`", + token_str)).as_slice()) } } } @@ -545,7 +550,7 @@ impl<'a> Parser<'a> { let id_interned_str = token::get_ident(kw.to_ident()); let token_str = self.this_token_to_str(); self.fatal(format!("expected `{}`, found `{}`", - id_interned_str, token_str)) + id_interned_str, token_str).as_slice()) } } @@ -554,7 +559,8 @@ impl<'a> Parser<'a> { if token::is_strict_keyword(&self.token) { let token_str = self.this_token_to_str(); self.span_err(self.span, - format!("found `{}` in ident position", token_str)); + format!("found `{}` in ident position", + token_str).as_slice()); } } @@ -562,7 +568,8 @@ impl<'a> Parser<'a> { pub fn check_reserved_keywords(&mut self) { if token::is_reserved_keyword(&self.token) { let token_str = self.this_token_to_str(); - self.fatal(format!("`{}` is a reserved keyword", token_str)) + self.fatal(format!("`{}` is a reserved keyword", + token_str).as_slice()) } } @@ -581,7 +588,7 @@ impl<'a> Parser<'a> { Parser::token_to_str(&token::BINOP(token::AND)); self.fatal(format!("expected `{}`, found `{}`", found_token, - token_str)) + token_str).as_slice()) } } } @@ -600,7 +607,8 @@ impl<'a> Parser<'a> { let token_str = Parser::token_to_str(&token::BINOP(token::OR)); self.fatal(format!("expected `{}`, found `{}`", - token_str, found_token)) + token_str, + found_token).as_slice()) } } } @@ -650,7 +658,8 @@ impl<'a> Parser<'a> { let found_token = self.this_token_to_str(); let token_str = Parser::token_to_str(&token::LT); self.fatal(format!("expected `{}`, found `{}`", - token_str, found_token)) + token_str, + found_token).as_slice()) } } @@ -690,7 +699,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_str(); self.fatal(format!("expected `{}`, found `{}`", gt_str, - this_token_str)) + this_token_str).as_slice()) } } } @@ -1186,8 +1195,8 @@ impl<'a> Parser<'a> { _ => { let token_str = p.this_token_to_str(); - p.fatal(format!("expected `;` or `\\{` but found `{}`", - token_str)) + p.fatal((format!("expected `;` or `\\{` but found `{}`", + token_str)).as_slice()) } } }) @@ -1359,7 +1368,7 @@ impl<'a> Parser<'a> { TyInfer } else { let msg = format!("expected type, found token {:?}", self.token); - self.fatal(msg); + self.fatal(msg.as_slice()); }; let sp = mk_sp(lo, self.last_span.hi); @@ -1631,7 +1640,7 @@ impl<'a> Parser<'a> { }; } _ => { - self.fatal(format!("expected a lifetime name")); + self.fatal(format!("expected a lifetime name").as_slice()); } } } @@ -1667,7 +1676,7 @@ impl<'a> Parser<'a> { let msg = format!("expected `,` or `>` after lifetime \ name, got: {:?}", self.token); - self.fatal(msg); + self.fatal(msg.as_slice()); } } } @@ -2122,7 +2131,7 @@ impl<'a> Parser<'a> { }; let token_str = p.this_token_to_str(); p.fatal(format!("incorrect close delimiter: `{}`", - token_str)) + token_str).as_slice()) }, /* we ought to allow different depths of unquotation */ token::DOLLAR if p.quote_depth > 0u => { @@ -2773,7 +2782,7 @@ impl<'a> Parser<'a> { if self.token != token::RBRACE { let token_str = self.this_token_to_str(); self.fatal(format!("expected `\\}`, found `{}`", - token_str)) + token_str).as_slice()) } etc = true; break; @@ -2793,7 +2802,8 @@ impl<'a> Parser<'a> { match bind_type { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_str(); - self.fatal(format!("unexpected `{}`", token_str)) + self.fatal(format!("unexpected `{}`", + token_str).as_slice()) } _ => {} } @@ -3202,7 +3212,8 @@ impl<'a> Parser<'a> { }; let tok_str = self.this_token_to_str(); self.fatal(format!("expected {}`(` or `\\{`, but found `{}`", - ident_str, tok_str)) + ident_str, + tok_str).as_slice()) } }; @@ -3606,7 +3617,8 @@ impl<'a> Parser<'a> { fn expect_self_ident(&mut self) { if !self.is_self_ident() { let token_str = self.this_token_to_str(); - self.fatal(format!("expected `self` but found `{}`", token_str)) + self.fatal(format!("expected `self` but found `{}`", + token_str).as_slice()) } self.bump(); } @@ -3738,7 +3750,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_str(); self.fatal(format!("expected `,` or `)`, found `{}`", - token_str)) + token_str).as_slice()) } } } else { @@ -4005,8 +4017,9 @@ impl<'a> Parser<'a> { fields.push(self.parse_struct_decl_field()); } if fields.len() == 0 { - self.fatal(format!("unit-like struct definition should be written as `struct {};`", - token::get_ident(class_name))); + self.fatal(format!("unit-like struct definition should be \ + written as `struct {};`", + token::get_ident(class_name)).as_slice()); } self.bump(); } else if self.token == token::LPAREN { @@ -4036,7 +4049,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_str(); self.fatal(format!("expected `\\{`, `(`, or `;` after struct \ name but found `{}`", - token_str)) + token_str).as_slice()) } let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug. @@ -4066,7 +4079,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_str(); self.span_fatal(self.span, format!("expected `,`, or `\\}` but found `{}`", - token_str)) + token_str).as_slice()) } } a_var @@ -4147,7 +4160,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_str(); self.fatal(format!("expected item but found `{}`", - token_str)) + token_str).as_slice()) } } } @@ -4260,12 +4273,19 @@ impl<'a> Parser<'a> { (true, false) => (default_path, false), (false, true) => (secondary_path, true), (false, false) => { - self.span_fatal(id_sp, format!("file not found for module `{}`", mod_name)); + self.span_fatal(id_sp, + format!("file not found for module \ + `{}`", + mod_name).as_slice()); } (true, true) => { - self.span_fatal(id_sp, - format!("file for module `{}` found at both {} and {}", - mod_name, default_path_str, secondary_path_str)); + self.span_fatal( + id_sp, + format!("file for module `{}` found at both {} \ + and {}", + mod_name, + default_path_str, + secondary_path_str).as_slice()); } } } @@ -4348,12 +4368,14 @@ impl<'a> Parser<'a> { let ty = self.parse_ty(false); let hi = self.span.hi; self.expect(&token::SEMI); - @ast::ForeignItem { ident: ident, - attrs: attrs, - node: ForeignItemStatic(ty, mutbl), - id: ast::DUMMY_NODE_ID, - span: mk_sp(lo, hi), - vis: vis } + @ast::ForeignItem { + ident: ident, + attrs: attrs, + node: ForeignItemStatic(ty, mutbl), + id: ast::DUMMY_NODE_ID, + span: mk_sp(lo, hi), + vis: vis, + } } // parse safe/unsafe and fn @@ -4418,8 +4440,9 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_str(); self.span_fatal(self.span, - format!("expected extern crate name but found `{}`", - token_str)); + format!("expected extern crate name but \ + found `{}`", + token_str).as_slice()); } }; @@ -4586,11 +4609,10 @@ impl<'a> Parser<'a> { None => { self.span_err( self.span, - format!("illegal ABI: \ - expected one of [{}], \ - found `{}`", - abi::all_names().connect(", "), - the_string)); + format!("illegal ABI: expected one of [{}], \ + found `{}`", + abi::all_names().connect(", "), + the_string).as_slice()); None } } @@ -4645,7 +4667,8 @@ impl<'a> Parser<'a> { self.span_err(mk_sp(lo, self.last_span.hi), format!("`extern mod` is obsolete, use \ `extern crate` instead \ - to refer to external crates.")) + to refer to external \ + crates.").as_slice()) } return self.parse_item_extern_crate(lo, visibility, attrs); } @@ -4670,7 +4693,8 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_str(); self.span_fatal(self.span, - format!("expected `\\{` or `fn` but found `{}`", token_str)); + format!("expected `\\{` or `fn` but found `{}`", + token_str).as_slice()); } let is_virtual = self.eat_keyword(keywords::Virtual); @@ -5076,7 +5100,8 @@ impl<'a> Parser<'a> { } ViewItemExternCrate(..) if !extern_mod_allowed => { self.span_err(view_item.span, - "\"extern crate\" declarations are not allowed here"); + "\"extern crate\" declarations are \ + not allowed here"); } ViewItemExternCrate(..) => {} } -- cgit 1.4.1-3-g733a5 From 5633d4641f7d63805e3c12c899f8401410bd825f Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 19 May 2014 17:23:26 -0700 Subject: libstd: Remove all uses of `~str` from `libstd` --- src/libcollections/bitv.rs | 4 +- src/libgetopts/lib.rs | 12 +- src/librustc/back/link.rs | 12 +- src/librustc/driver/mod.rs | 11 +- src/librustc/metadata/encoder.rs | 6 +- src/librustc/metadata/loader.rs | 2 +- src/librustc/metadata/tydecode.rs | 2 +- src/librustc/middle/cfg/graphviz.rs | 3 +- src/librustc/middle/trans/asm.rs | 3 +- src/librustc/middle/trans/glue.rs | 5 +- src/librustc/middle/trans/reflect.rs | 14 +- src/librustc/util/ppaux.rs | 2 +- src/libserialize/json.rs | 12 +- src/libstd/ascii.rs | 4 +- src/libstd/c_str.rs | 23 --- src/libstd/lib.rs | 6 +- src/libstd/str.rs | 285 ++++++++++++++------------------ src/libstd/strbuf.rs | 35 ++-- src/libsyntax/crateid.rs | 8 +- src/libsyntax/diagnostic.rs | 9 +- src/libsyntax/ext/asm.rs | 2 +- src/libsyntax/ext/concat.rs | 2 +- src/libsyntax/ext/concat_idents.rs | 2 +- src/libsyntax/ext/quote.rs | 6 +- src/libsyntax/ext/source_util.rs | 4 +- src/libsyntax/ext/tt/macro_parser.rs | 5 +- src/libsyntax/parse/lexer.rs | 7 +- src/libsyntax/parse/parser.rs | 6 +- src/libsyntax/print/pprust.rs | 5 +- src/libterm/terminfo/parser/compiled.rs | 3 +- 30 files changed, 238 insertions(+), 262 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/libcollections/bitv.rs b/src/libcollections/bitv.rs index e2934efa43b..1c9940c5b1f 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bitv.rs @@ -538,7 +538,7 @@ impl Bitv { * The resulting string has the same length as `self`, and each * character is either '0' or '1'. */ - pub fn to_str(&self) -> ~str { + pub fn to_str(&self) -> StrBuf { let mut rs = StrBuf::new(); for i in self.iter() { if i { @@ -547,7 +547,7 @@ impl Bitv { rs.push_char('0'); } }; - rs.into_owned() + rs } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index ba30e1a2e98..60528776294 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -661,7 +661,7 @@ pub fn getopts(args: &[StrBuf], optgrps: &[OptGroup]) -> Result { /// Derive a usage message from a set of long options. pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf { - let desc_sep = "\n" + " ".repeat(24); + let desc_sep = format!("\n{}", " ".repeat(24)); let mut rows = opts.iter().map(|optref| { let OptGroup{short_name: short_name, @@ -713,7 +713,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf { row.push_char(' '); } } else { - row.push_str(desc_sep) + row.push_str(desc_sep.as_slice()) } // Normalize desc to contain words separated by one space character @@ -734,7 +734,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf { // FIXME: #5516 should be graphemes not codepoints // wrapped description - row.push_str(desc_rows.connect(desc_sep)); + row.push_str(desc_rows.connect(desc_sep.as_slice()).as_slice()); row }); @@ -784,7 +784,11 @@ fn format_option(opt: &OptGroup) -> StrBuf { /// Derive a short one-line usage summary from a set of long options. pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> StrBuf { let mut line = format_strbuf!("Usage: {} ", program_name); - line.push_str(opts.iter().map(format_option).collect::>().connect(" ")); + line.push_str(opts.iter() + .map(format_option) + .collect::>() + .connect(" ") + .as_slice()); line } diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index cd6e74beb30..9d7c07498ff 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -369,7 +369,8 @@ pub mod write { sess.note(format!("{}", &cmd).as_slice()); let mut note = prog.error.clone(); note.push_all(prog.output.as_slice()); - sess.note(str::from_utf8(note.as_slice()).unwrap().to_owned()); + sess.note(str::from_utf8(note.as_slice()).unwrap() + .as_slice()); sess.abort_if_errors(); } }, @@ -538,8 +539,8 @@ pub fn find_crate_id(attrs: &[ast::Attribute], out_filestem: &str) -> CrateId { match attr::find_crateid(attrs) { None => from_str(out_filestem).unwrap_or_else(|| { let mut s = out_filestem.chars().filter(|c| c.is_XID_continue()); - from_str(s.collect::() - .to_owned()).or(from_str("rust-out")).unwrap() + from_str(s.collect::().as_slice()) + .or(from_str("rust-out")).unwrap() }), Some(s) => s, } @@ -698,7 +699,7 @@ pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> StrBuf { // The version will get mangled to have a leading '_', but it makes more // sense to lead with a 'v' b/c this is a version... let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) { - "v" + vers + format!("v{}", vers) } else { vers.to_owned() }; @@ -1075,7 +1076,8 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, sess.note(format!("{}", &cmd).as_slice()); let mut output = prog.error.clone(); output.push_all(prog.output.as_slice()); - sess.note(str::from_utf8(output.as_slice()).unwrap().to_owned()); + sess.note(str::from_utf8(output.as_slice()).unwrap() + .as_slice()); sess.abort_if_errors(); } }, diff --git a/src/librustc/driver/mod.rs b/src/librustc/driver/mod.rs index eea6b78d3c8..2fb730e4dae 100644 --- a/src/librustc/driver/mod.rs +++ b/src/librustc/driver/mod.rs @@ -143,8 +143,8 @@ Available lint options: for &(_, name) in lint_dict.iter() { max_key = cmp::max(name.len(), max_key); } - fn padded(max: uint, s: &str) -> ~str { - " ".repeat(max - s.len()) + s + fn padded(max: uint, s: &str) -> StrBuf { + format!("{}{}", " ".repeat(max - s.len()), s) } println!("\nAvailable lint checks:\n"); println!(" {} {:7.7s} {}", @@ -154,7 +154,7 @@ Available lint options: for (spec, name) in lint_dict.move_iter() { let name = name.replace("_", "-"); println!(" {} {:7.7s} {}", - padded(max_key, name), + padded(max_key, name.as_slice()), lint::level_to_str(spec.default), spec.desc); } @@ -400,11 +400,12 @@ fn monitor(f: proc():Send) { let xs = [ "the compiler hit an unexpected failure path. this is a bug.".to_owned(), - "we would appreciate a bug report: " + BUG_REPORT_URL, + format!("we would appreciate a bug report: {}", + BUG_REPORT_URL), "run with `RUST_BACKTRACE=1` for a backtrace".to_owned(), ]; for note in xs.iter() { - emitter.emit(None, *note, diagnostic::Note) + emitter.emit(None, note.as_slice(), diagnostic::Note) } match r.read_to_str() { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 607db8e63c8..a0742669cc0 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -602,7 +602,7 @@ fn encode_visibility(ebml_w: &mut Encoder, visibility: Visibility) { Public => 'y', Inherited => 'i', }; - ebml_w.wr_str(str::from_char(ch)); + ebml_w.wr_str(str::from_char(ch).as_slice()); ebml_w.end_tag(); } @@ -848,7 +848,7 @@ fn encode_sized(ebml_w: &mut Encoder, sized: Sized) { DynSize => 'd', StaticSize => 's', }; - ebml_w.wr_str(str::from_char(ch)); + ebml_w.wr_str(str::from_char(ch).as_slice()); ebml_w.end_tag(); } @@ -1885,5 +1885,5 @@ pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> StrBuf { tcx: tcx, abbrevs: &RefCell::new(HashMap::new()) }, t); - str::from_utf8_owned(wr.get_ref().to_owned()).unwrap().to_strbuf() + str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_strbuf() } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index bcaa3f4c31f..9a63aad893f 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -552,7 +552,7 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result abi::Abi { assert_eq!(next(st), '['); scan(st, |c| c == ']', |bytes| { let abi_str = str::from_utf8(bytes).unwrap().to_owned(); - abi::lookup(abi_str).expect(abi_str) + abi::lookup(abi_str.as_slice()).expect(abi_str) }) } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 0d94fdb6e00..3d69e84b63c 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -37,7 +37,8 @@ fn replace_newline_with_backslash_l(s: StrBuf) -> StrBuf { // \l, not the line that follows; so, add \l at end of string // if not already present, ensuring last line gets left-aligned // as well. - let mut last_two : Vec<_> = s.chars().rev().take(2).collect(); + let mut last_two: Vec<_> = + s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); if last_two.as_slice() != ['\\', 'l'] { s = s.append("\\l"); diff --git a/src/librustc/middle/trans/asm.rs b/src/librustc/middle/trans/asm.rs index e6004b4cb71..fa299dc0503 100644 --- a/src/librustc/middle/trans/asm.rs +++ b/src/librustc/middle/trans/asm.rs @@ -67,7 +67,8 @@ pub fn trans_inline_asm<'a>(bcx: &'a Block<'a>, ia: &ast::InlineAsm) StrBuf::from_str(constraints.iter() .map(|s| s.get().to_strbuf()) .collect::>() - .connect(",")); + .connect(",") + .as_slice()); let mut clobbers = getClobbers(); if !ia.clobbers.get().is_empty() && !clobbers.is_empty() { diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index b1b684ca371..c103a44aa75 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -454,7 +454,10 @@ pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info { fn declare_generic_glue(ccx: &CrateContext, t: ty::t, llfnty: Type, name: &str) -> ValueRef { let _icx = push_ctxt("declare_generic_glue"); - let fn_nm = mangle_internal_name_by_type_and_seq(ccx, t, "glue_".to_owned() + name); + let fn_nm = mangle_internal_name_by_type_and_seq( + ccx, + t, + format!("glue_{}", name).as_slice()); debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t)); let llfn = decl_cdecl_fn(ccx.llmod, fn_nm.as_slice(), diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index 206fc07cd86..a0184e2cbe3 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -87,7 +87,8 @@ impl<'a, 'b> Reflector<'a, 'b> { pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) { let fcx = self.bcx.fcx; let tcx = self.bcx.tcx(); - let mth_idx = ty::method_idx(token::str_to_ident("visit_".to_owned() + ty_name), + let mth_idx = ty::method_idx(token::str_to_ident(format!( + "visit_{}", ty_name).as_slice()), self.visitor_methods.as_slice()).expect( format!("couldn't find visit method for {}", ty_name)); let mth_ty = @@ -154,7 +155,7 @@ impl<'a, 'b> Reflector<'a, 'b> { ty::ty_vec(ref mt, Some(sz)) => { let extra = (vec!(self.c_uint(sz))).append(self.c_size_and_align(t).as_slice()); let extra = extra.append(self.c_mt(mt).as_slice()); - self.visit("evec_fixed".to_owned(), extra.as_slice()) + self.visit("evec_fixed", extra.as_slice()) } ty::ty_vec(..) | ty::ty_str => fail!("unexpected unsized type"), // Should remove mt from box and uniq. @@ -170,9 +171,9 @@ impl<'a, 'b> Reflector<'a, 'b> { ty::ty_vec(ref mt, None) => { let extra = Vec::new(); let extra = extra.append(self.c_mt(mt).as_slice()); - self.visit("evec_uniq".to_owned(), extra.as_slice()) + self.visit("evec_uniq", extra.as_slice()) } - ty::ty_str => self.visit("estr_uniq".to_owned(), &[]), + ty::ty_str => self.visit("estr_uniq", &[]), _ => { let extra = self.c_mt(&ty::mt { ty: typ, @@ -191,9 +192,10 @@ impl<'a, 'b> Reflector<'a, 'b> { ty::ty_vec(ref mt, None) => { let (name, extra) = ("slice".to_owned(), Vec::new()); let extra = extra.append(self.c_mt(mt).as_slice()); - self.visit("evec_".to_owned() + name, extra.as_slice()) + self.visit(format!("evec_{}", name).as_slice(), + extra.as_slice()) } - ty::ty_str => self.visit("estr_slice".to_owned(), &[]), + ty::ty_str => self.visit("estr_slice", &[]), _ => { let extra = self.c_mt(mt); self.visit("rptr", extra.as_slice()) diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 982ccceb5ee..087a4e58d49 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -327,7 +327,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> StrBuf { sig: &ty::FnSig) { s.push_char(bra); let strs: Vec = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect(); - s.push_str(strs.connect(", ")); + s.push_str(strs.connect(", ").as_slice()); if sig.variadic { s.push_str(", ..."); } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 422914b1405..e6f46ea7159 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -425,7 +425,9 @@ impl<'a> ::Encoder for Encoder<'a> { } fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) } - fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) } + fn emit_char(&mut self, v: char) -> EncodeResult { + self.emit_str(str::from_char(v).as_slice()) + } fn emit_str(&mut self, v: &str) -> EncodeResult { write!(self.wr, "{}", escape_str(v)) } @@ -614,9 +616,13 @@ impl<'a> ::Encoder for PrettyEncoder<'a> { fn emit_f64(&mut self, v: f64) -> EncodeResult { write!(self.wr, "{}", f64::to_str_digits(v, 6u)) } - fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) } + fn emit_f32(&mut self, v: f32) -> EncodeResult { + self.emit_f64(v as f64) + } - fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) } + fn emit_char(&mut self, v: char) -> EncodeResult { + self.emit_str(str::from_char(v).as_slice()) + } fn emit_str(&mut self, v: &str) -> EncodeResult { write!(self.wr, "{}", escape_str(v)) } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 8240211a839..0b3dd414967 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -419,8 +419,8 @@ unsafe fn str_map_bytes(string: StrBuf, map: &'static [u8]) -> StrBuf { #[inline] 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() { + let mut s = string.to_strbuf(); + for b in s.as_mut_bytes().mut_iter() { *b = map[*b as uint]; } s.into_strbuf() diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index 0c529ee4d96..4622c0934fe 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -323,29 +323,6 @@ impl<'a> ToCStr for &'a str { } } -impl ToCStr for ~str { - #[inline] - fn to_c_str(&self) -> CString { - self.as_bytes().to_c_str() - } - - #[inline] - unsafe fn to_c_str_unchecked(&self) -> CString { - self.as_bytes().to_c_str_unchecked() - } - - #[inline] - fn with_c_str(&self, f: |*libc::c_char| -> T) -> T { - self.as_bytes().with_c_str(f) - } - - #[inline] - unsafe fn with_c_str_unchecked(&self, f: |*libc::c_char| -> T) -> T { - self.as_bytes().with_c_str_unchecked(f) - } -} - - impl ToCStr for StrBuf { #[inline] fn to_c_str(&self) -> CString { diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index b9181793051..22ac397c702 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -47,9 +47,9 @@ //! for which the [`slice`](slice/index.html) module defines many //! methods. //! -//! UTF-8 strings, `~str` and `&str`, are built-in types, and the -//! standard library defines methods for them on a variety of traits -//! in the [`str`](str/index.html) module. Rust strings are immutable; +//! `&str`, a UTF-8 string, is a built-in type, and the standard library +//! defines methods for it on a variety of traits in the +//! [`str`](str/index.html) module. Rust strings are immutable; //! use the `StrBuf` type defined in [`strbuf`](strbuf/index.html) //! for a mutable string builder. //! diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 0b4db05545c..f406cc9532f 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -17,37 +17,29 @@ Unicode string manipulation (`str` type) Rust's string type is one of the core primitive types of the language. While represented by the name `str`, the name `str` is not actually a valid type in Rust. Each string must also be decorated with its ownership. This means that -there are two common kinds of strings in Rust: - -* `~str` - This is an owned string. This type obeys all of the normal semantics - of the `Box` types, meaning that it has one, and only one, - owner. This type cannot be implicitly copied, and is moved out of - when passed to other functions. +there is one common kind of string in Rust: * `&str` - This is the borrowed string type. This type of string can only be created from the other kind of string. As the name "borrowed" implies, this type of string is owned elsewhere, and this string cannot be moved out of. -As an example, here's a few different kinds of strings. +As an example, here's the one kind of string. ```rust fn main() { - let owned_string = "I am an owned string".to_owned(); - let borrowed_string1 = "This string is borrowed with the 'static lifetime"; - let borrowed_string2: &str = owned_string; // owned strings can be borrowed + let borrowed_string = "This string is borrowed with the 'static lifetime"; } ``` -From the example above, you can see that Rust has 2 different kinds of string -literals. The owned literals correspond to the owned string types, but the -"borrowed literal" is actually more akin to C's concept of a static string. +From the example above, you can see that Rust has 1 different kind of string +literal. The "borrowed literal" is akin to C's concept of a static string. -When a string is declared without a `~` sigil, then the string is allocated -statically in the rodata of the executable/library. The string then has the -type `&'static str` meaning that the string is valid for the `'static` -lifetime, otherwise known as the lifetime of the entire program. As can be -inferred from the type, these static strings are not mutable. +String literals are allocated statically in the rodata of the +executable/library. The string then has the type `&'static str` meaning that +the string is valid for the `'static` lifetime, otherwise known as the +lifetime of the entire program. As can be inferred from the type, these static +strings are not mutable. # Mutability @@ -67,10 +59,8 @@ stream of UTF-8 bytes. All safely-created strings are guaranteed to be validly encoded UTF-8 sequences. Additionally, strings are not null-terminated and can contain null codepoints. -The actual representation of strings have direct mappings to vectors: - -* `~str` is the same as `~[u8]` -* `&str` is the same as `&[u8]` +The actual representation of strings have direct mappings to vectors: `&str` +is the same as `&[u8]`. */ @@ -81,13 +71,12 @@ use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv, Ordering}; use container::Container; use default::Default; use fmt; -use from_str::FromStr; use io::Writer; use iter::{Iterator, range, AdditiveIterator}; use mem::transmute; use mem; use option::{None, Option, Some}; -use result::{Result, Ok, Err}; +use result::Result; use slice::Vector; use slice::{ImmutableVector, MutableVector, CloneableVector}; use strbuf::StrBuf; @@ -109,17 +98,8 @@ Section: Creating a string /// /// Returns `Err` with the original vector if the vector contains invalid /// UTF-8. -pub fn from_utf8_owned(vv: ~[u8]) -> Result<~str, ~[u8]> { - if is_utf8(vv) { - Ok(unsafe { raw::from_utf8_owned(vv) }) - } else { - Err(vv) - } -} - -impl FromStr for ~str { - #[inline] - fn from_str(s: &str) -> Option<~str> { Some(s.to_owned()) } +pub fn from_utf8_owned(vv: Vec) -> Result> { + StrBuf::from_utf8(vv) } /// Convert a byte to a UTF-8 string @@ -127,35 +107,37 @@ impl FromStr for ~str { /// # Failure /// /// Fails if invalid UTF-8 -pub fn from_byte(b: u8) -> ~str { +pub fn from_byte(b: u8) -> StrBuf { assert!(b < 128u8); - unsafe { ::mem::transmute(box [b]) } + StrBuf::from_char(1, b as char) } /// Convert a char to a string -pub fn from_char(ch: char) -> ~str { +pub fn from_char(ch: char) -> StrBuf { let mut buf = StrBuf::new(); buf.push_char(ch); - buf.into_owned() + buf } /// Convert a vector of chars to a string -pub fn from_chars(chs: &[char]) -> ~str { +pub fn from_chars(chs: &[char]) -> StrBuf { chs.iter().map(|c| *c).collect() } /// Methods for vectors of strings pub trait StrVector { /// Concatenate a vector of strings. - fn concat(&self) -> ~str; + fn concat(&self) -> StrBuf; /// Concatenate a vector of strings, placing a given separator between each. - fn connect(&self, sep: &str) -> ~str; + fn connect(&self, sep: &str) -> StrBuf; } impl<'a, S: Str> StrVector for &'a [S] { - fn concat(&self) -> ~str { - if self.is_empty() { return "".to_owned(); } + fn concat(&self) -> StrBuf { + if self.is_empty() { + return StrBuf::new(); + } // `len` calculation may overflow but push_str but will check boundaries let len = self.iter().map(|s| s.as_slice().len()).sum(); @@ -166,14 +148,18 @@ impl<'a, S: Str> StrVector for &'a [S] { result.push_str(s.as_slice()) } - result.into_owned() + result } - fn connect(&self, sep: &str) -> ~str { - if self.is_empty() { return "".to_owned(); } + fn connect(&self, sep: &str) -> StrBuf { + if self.is_empty() { + return StrBuf::new(); + } // concat is faster - if sep.is_empty() { return self.concat(); } + if sep.is_empty() { + return self.concat(); + } // this is wrong without the guarantee that `self` is non-empty // `len` calculation may overflow but push_str but will check boundaries @@ -190,18 +176,18 @@ impl<'a, S: Str> StrVector for &'a [S] { } result.push_str(s.as_slice()); } - result.into_owned() + result } } impl<'a, S: Str> StrVector for Vec { #[inline] - fn concat(&self) -> ~str { + fn concat(&self) -> StrBuf { self.as_slice().concat() } #[inline] - fn connect(&self, sep: &str) -> ~str { + fn connect(&self, sep: &str) -> StrBuf { self.as_slice().connect(sep) } } @@ -317,7 +303,7 @@ impl<'a> Iterator for Decompositions<'a> { /// # Return value /// /// The original string with all occurrences of `from` replaced with `to` -pub fn replace(s: &str, from: &str, to: &str) -> ~str { +pub fn replace(s: &str, from: &str, to: &str) -> StrBuf { let mut result = StrBuf::new(); let mut last_end = 0; for (start, end) in s.match_indices(from) { @@ -326,7 +312,7 @@ pub fn replace(s: &str, from: &str, to: &str) -> ~str { last_end = end; } result.push_str(unsafe{raw::slice_bytes(s, last_end, s.len())}); - result.into_owned() + result } /* @@ -350,7 +336,7 @@ Section: Misc /// v[4] = 0xD800; /// assert_eq!(str::from_utf16(v), None); /// ``` -pub fn from_utf16(v: &[u16]) -> Option<~str> { +pub fn from_utf16(v: &[u16]) -> Option { let mut s = StrBuf::with_capacity(v.len() / 2); for c in utf16_items(v) { match c { @@ -358,7 +344,7 @@ pub fn from_utf16(v: &[u16]) -> Option<~str> { LoneSurrogate(_) => return None } } - Some(s.into_owned()) + Some(s) } /// Decode a UTF-16 encoded vector `v` into a string, replacing @@ -376,7 +362,7 @@ pub fn from_utf16(v: &[u16]) -> Option<~str> { /// assert_eq!(str::from_utf16_lossy(v), /// "𝄞mus\uFFFDic\uFFFD".to_owned()); /// ``` -pub fn from_utf16_lossy(v: &[u16]) -> ~str { +pub fn from_utf16_lossy(v: &[u16]) -> StrBuf { utf16_items(v).map(|c| c.to_char_lossy()).collect() } @@ -523,14 +509,14 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> { Section: MaybeOwned */ -/// A MaybeOwned is a string that can hold either a ~str or a &str. +/// A MaybeOwned is a string that can hold either a StrBuf or a &str. /// This can be useful as an optimization when an allocation is sometimes /// needed but not always. pub enum MaybeOwned<'a> { /// A borrowed string Slice(&'a str), /// An owned string - Owned(~str) + Owned(StrBuf) } /// SendStr is a specialization of `MaybeOwned` to be sendable @@ -562,15 +548,10 @@ pub trait IntoMaybeOwned<'a> { fn into_maybe_owned(self) -> MaybeOwned<'a>; } -impl<'a> IntoMaybeOwned<'a> for ~str { - #[inline] - fn into_maybe_owned(self) -> MaybeOwned<'a> { Owned(self) } -} - impl<'a> IntoMaybeOwned<'a> for StrBuf { #[inline] fn into_maybe_owned(self) -> MaybeOwned<'a> { - Owned(self.into_owned()) + Owned(self) } } @@ -626,7 +607,7 @@ impl<'a> Str for MaybeOwned<'a> { impl<'a> StrAllocating for MaybeOwned<'a> { #[inline] - fn into_owned(self) -> ~str { + fn into_owned(self) -> StrBuf { match self { Slice(s) => s.to_owned(), Owned(s) => s @@ -676,58 +657,37 @@ impl<'a> fmt::Show for MaybeOwned<'a> { /// Unsafe operations pub mod raw { + use c_str::CString; use libc; use mem; - use ptr::RawPtr; - use raw::Slice; - use slice::CloneableVector; - use str::{is_utf8, StrAllocating}; + use strbuf::StrBuf; + use vec::Vec; pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes}; pub use core::str::raw::{slice_unchecked}; /// Create a Rust string from a *u8 buffer of the given length - pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str { - let v = Slice { data: buf, len: len }; - let bytes: &[u8] = ::mem::transmute(v); - assert!(is_utf8(bytes)); - let s: &str = ::mem::transmute(bytes); - s.to_owned() - } - - #[lang="strdup_uniq"] - #[cfg(not(test))] - #[inline] - unsafe fn strdup_uniq(ptr: *u8, len: uint) -> ~str { - from_buf_len(ptr, len) + pub unsafe fn from_buf_len(buf: *u8, len: uint) -> StrBuf { + StrBuf::from_raw_parts(len, len, mem::transmute(buf)) } /// Create a Rust string from a null-terminated C string - pub unsafe fn from_c_str(buf: *libc::c_char) -> ~str { - let mut curr = buf; - let mut i = 0; - while *curr != 0 { - i += 1; - curr = buf.offset(i); - } - from_buf_len(buf as *u8, i as uint) + pub unsafe fn from_c_str(c_string: *libc::c_char) -> StrBuf { + let mut buf = StrBuf::new(); + buf.push_bytes(CString::new(c_string, false).as_bytes_no_nul()); + buf } /// Converts an owned vector of bytes to a new owned string. This assumes /// that the utf-8-ness of the vector has already been validated #[inline] - pub unsafe fn from_utf8_owned(v: ~[u8]) -> ~str { + pub unsafe fn from_utf8_owned(v: Vec) -> StrBuf { mem::transmute(v) } /// Converts a byte to a string. - pub unsafe fn from_byte(u: u8) -> ~str { from_utf8_owned(box [u]) } - - /// Access the str in its vector representation. - /// The caller must preserve the valid UTF-8 property when modifying. - #[inline] - pub unsafe fn as_owned_vec<'a>(s: &'a mut ~str) -> &'a mut ~[u8] { - mem::transmute(s) + pub unsafe fn from_byte(u: u8) -> StrBuf { + from_utf8_owned(vec![u]) } /// Sets the length of a string @@ -755,8 +715,8 @@ Section: Trait implementations /// Any string that can be represented as a slice pub trait StrAllocating: Str { - /// Convert `self` into a ~str, not making a copy if possible. - fn into_owned(self) -> ~str; + /// Convert `self` into a `StrBuf`, not making a copy if possible. + fn into_owned(self) -> StrBuf; /// Convert `self` into a `StrBuf`. #[inline] @@ -767,27 +727,27 @@ pub trait StrAllocating: Str { /// Convert `self` into a `StrBuf`, not making a copy if possible. #[inline] fn into_strbuf(self) -> StrBuf { - StrBuf::from_owned_str(self.into_owned()) + self.into_owned() } /// Escape each char in `s` with `char::escape_default`. - fn escape_default(&self) -> ~str { + fn escape_default(&self) -> StrBuf { let me = self.as_slice(); let mut out = StrBuf::with_capacity(me.len()); for c in me.chars() { c.escape_default(|c| out.push_char(c)); } - out.into_owned() + out } /// Escape each char in `s` with `char::escape_unicode`. - fn escape_unicode(&self) -> ~str { + fn escape_unicode(&self) -> StrBuf { let me = self.as_slice(); let mut out = StrBuf::with_capacity(me.len()); for c in me.chars() { c.escape_unicode(|c| out.push_char(c)); } - out.into_owned() + out } /// Replace all occurrences of one string with another. @@ -814,7 +774,7 @@ pub trait StrAllocating: Str { /// // not found, so no change. /// assert_eq!(s.replace("cookie monster", "little lamb"), s); /// ``` - fn replace(&self, from: &str, to: &str) -> ~str { + fn replace(&self, from: &str, to: &str) -> StrBuf { let me = self.as_slice(); let mut result = StrBuf::new(); let mut last_end = 0; @@ -824,16 +784,16 @@ pub trait StrAllocating: Str { last_end = end; } result.push_str(unsafe{raw::slice_bytes(me, last_end, me.len())}); - result.into_owned() + result } - /// Copy a slice into a new owned str. + /// Copy a slice into a new `StrBuf`. #[inline] - fn to_owned(&self) -> ~str { + fn to_owned(&self) -> StrBuf { use slice::Vector; unsafe { - ::mem::transmute(self.as_slice().as_bytes().to_owned()) + ::mem::transmute(Vec::from_slice(self.as_slice().as_bytes())) } } @@ -850,13 +810,13 @@ pub trait StrAllocating: Str { } /// Given a string, make a new string with repeated copies of it. - fn repeat(&self, nn: uint) -> ~str { + fn repeat(&self, nn: uint) -> StrBuf { let me = self.as_slice(); let mut ret = StrBuf::with_capacity(nn * me.len()); for _ in range(0, nn) { ret.push_str(me); } - ret.into_owned() + ret } /// Levenshtein Distance between two strings. @@ -921,12 +881,9 @@ pub trait StrAllocating: Str { impl<'a> StrAllocating for &'a str { #[inline] - fn into_owned(self) -> ~str { self.to_owned() } -} - -impl<'a> StrAllocating for ~str { - #[inline] - fn into_owned(self) -> ~str { self } + fn into_owned(self) -> StrBuf { + self.to_owned() + } } /// Methods for owned strings @@ -934,23 +891,23 @@ pub trait OwnedStr { /// Consumes the string, returning the underlying byte buffer. /// /// The buffer does not have a null terminator. - fn into_bytes(self) -> ~[u8]; + fn into_bytes(self) -> Vec; /// Pushes the given string onto this string, returning the concatenation of the two strings. - fn append(self, rhs: &str) -> ~str; + fn append(self, rhs: &str) -> StrBuf; } -impl OwnedStr for ~str { +impl OwnedStr for StrBuf { #[inline] - fn into_bytes(self) -> ~[u8] { + fn into_bytes(self) -> Vec { unsafe { mem::transmute(self) } } #[inline] - fn append(self, rhs: &str) -> ~str { + fn append(self, rhs: &str) -> StrBuf { let mut new_str = StrBuf::from_owned_str(self); new_str.push_str(rhs); - new_str.into_owned() + new_str } } @@ -1027,10 +984,10 @@ mod tests { #[test] fn test_collect() { let empty = "".to_owned(); - let s: ~str = empty.chars().collect(); + let s: StrBuf = empty.chars().collect(); assert_eq!(empty, s); let data = "ประเทศไทย中".to_owned(); - let s: ~str = data.chars().collect(); + let s: StrBuf = data.chars().collect(); assert_eq!(data, s); } @@ -1086,25 +1043,25 @@ mod tests { #[test] fn test_concat() { - fn t(v: &[~str], s: &str) { + fn t(v: &[StrBuf], s: &str) { assert_eq!(v.concat(), s.to_str().into_owned()); } t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(), "no".to_owned(), "good".to_owned()], "youknowI'mnogood"); - let v: &[~str] = []; + let v: &[StrBuf] = []; t(v, ""); t(["hi".to_owned()], "hi"); } #[test] fn test_connect() { - fn t(v: &[~str], sep: &str, s: &str) { + fn t(v: &[StrBuf], sep: &str, s: &str) { assert_eq!(v.connect(sep), s.to_str().into_owned()); } t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(), "no".to_owned(), "good".to_owned()], " ", "you know I'm no good"); - let v: &[~str] = []; + let v: &[StrBuf] = []; t(v, " ", ""); t(["hi".to_owned()], " ", "hi"); } @@ -1145,23 +1102,23 @@ mod tests { assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)}); assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)}); assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)}); - fn a_million_letter_a() -> ~str { + fn a_million_letter_a() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("aaaaaaaaaa"); i += 1; } - rs.into_owned() + rs } - fn half_a_million_letter_a() -> ~str { + fn half_a_million_letter_a() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("aaaaa"); i += 1; } - rs.into_owned() + rs } let letters = a_million_letter_a(); assert!(half_a_million_letter_a() == @@ -1260,23 +1217,23 @@ mod tests { assert_eq!("", data.slice(3, 3)); assert_eq!("华", data.slice(30, 33)); - fn a_million_letter_X() -> ~str { + fn a_million_letter_X() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("华华华华华华华华华华"); i += 1; } - rs.into_owned() + rs } - fn half_a_million_letter_X() -> ~str { + fn half_a_million_letter_X() -> StrBuf { let mut i = 0; let mut rs = StrBuf::new(); while i < 100000 { rs.push_str("华华华华华"); i += 1; } - rs.into_owned() + rs } let letters = a_million_letter_X(); assert!(half_a_million_letter_X() == @@ -1573,10 +1530,10 @@ mod tests { #[test] fn vec_str_conversions() { - let s1: ~str = "All mimsy were the borogoves".to_owned(); + let s1: StrBuf = "All mimsy were the borogoves".to_strbuf(); - let v: ~[u8] = s1.as_bytes().to_owned(); - let s2: ~str = from_utf8(v).unwrap().to_owned(); + let v: Vec = Vec::from_slice(s1.as_bytes()); + let s2: StrBuf = from_utf8(v).unwrap().to_strbuf(); let mut i: uint = 0u; let n1: uint = s1.len(); let n2: uint = v.len(); @@ -2027,30 +1984,30 @@ mod tests { #[test] fn test_nfd_chars() { - assert_eq!("abc".nfd_chars().collect::<~str>(), "abc".to_owned()); - assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<~str>(), "d\u0307\u01c4".to_owned()); - assert_eq!("\u2026".nfd_chars().collect::<~str>(), "\u2026".to_owned()); - assert_eq!("\u2126".nfd_chars().collect::<~str>(), "\u03a9".to_owned()); - assert_eq!("\u1e0b\u0323".nfd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("\u1e0d\u0307".nfd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("a\u0301".nfd_chars().collect::<~str>(), "a\u0301".to_owned()); - assert_eq!("\u0301a".nfd_chars().collect::<~str>(), "\u0301a".to_owned()); - assert_eq!("\ud4db".nfd_chars().collect::<~str>(), "\u1111\u1171\u11b6".to_owned()); - assert_eq!("\uac1c".nfd_chars().collect::<~str>(), "\u1100\u1162".to_owned()); + assert_eq!("abc".nfd_chars().collect::(), "abc".to_strbuf()); + assert_eq!("\u1e0b\u01c4".nfd_chars().collect::(), "d\u0307\u01c4".to_strbuf()); + assert_eq!("\u2026".nfd_chars().collect::(), "\u2026".to_strbuf()); + assert_eq!("\u2126".nfd_chars().collect::(), "\u03a9".to_strbuf()); + assert_eq!("\u1e0b\u0323".nfd_chars().collect::(), "d\u0323\u0307".to_strbuf()); + assert_eq!("\u1e0d\u0307".nfd_chars().collect::(), "d\u0323\u0307".to_strbuf()); + assert_eq!("a\u0301".nfd_chars().collect::(), "a\u0301".to_strbuf()); + assert_eq!("\u0301a".nfd_chars().collect::(), "\u0301a".to_strbuf()); + assert_eq!("\ud4db".nfd_chars().collect::(), "\u1111\u1171\u11b6".to_strbuf()); + assert_eq!("\uac1c".nfd_chars().collect::(), "\u1100\u1162".to_strbuf()); } #[test] fn test_nfkd_chars() { - assert_eq!("abc".nfkd_chars().collect::<~str>(), "abc".to_owned()); - assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<~str>(), "d\u0307DZ\u030c".to_owned()); - assert_eq!("\u2026".nfkd_chars().collect::<~str>(), "...".to_owned()); - assert_eq!("\u2126".nfkd_chars().collect::<~str>(), "\u03a9".to_owned()); - assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<~str>(), "d\u0323\u0307".to_owned()); - assert_eq!("a\u0301".nfkd_chars().collect::<~str>(), "a\u0301".to_owned()); - assert_eq!("\u0301a".nfkd_chars().collect::<~str>(), "\u0301a".to_owned()); - assert_eq!("\ud4db".nfkd_chars().collect::<~str>(), "\u1111\u1171\u11b6".to_owned()); - assert_eq!("\uac1c".nfkd_chars().collect::<~str>(), "\u1100\u1162".to_owned()); + assert_eq!("abc".nfkd_chars().collect::(), "abc".to_strbuf()); + assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::(), "d\u0307DZ\u030c".to_strbuf()); + assert_eq!("\u2026".nfkd_chars().collect::(), "...".to_strbuf()); + assert_eq!("\u2126".nfkd_chars().collect::(), "\u03a9".to_strbuf()); + assert_eq!("\u1e0b\u0323".nfkd_chars().collect::(), "d\u0323\u0307".to_strbuf()); + assert_eq!("\u1e0d\u0307".nfkd_chars().collect::(), "d\u0323\u0307".to_strbuf()); + assert_eq!("a\u0301".nfkd_chars().collect::(), "a\u0301".to_strbuf()); + assert_eq!("\u0301a".nfkd_chars().collect::(), "\u0301a".to_strbuf()); + assert_eq!("\ud4db".nfkd_chars().collect::(), "\u1111\u1171\u11b6".to_strbuf()); + assert_eq!("\uac1c".nfkd_chars().collect::(), "\u1100\u1162".to_strbuf()); } #[test] @@ -2095,7 +2052,7 @@ mod tests { } t::<&str>(); - t::<~str>(); + t::(); } #[test] @@ -2169,8 +2126,8 @@ mod tests { #[test] fn test_from_str() { - let owned: Option<~str> = from_str("string"); - assert_eq!(owned, Some("string".to_owned())); + let owned: Option = from_str("string"); + assert_eq!(owned, Some("string".to_strbuf())); } #[test] diff --git a/src/libstd/strbuf.rs b/src/libstd/strbuf.rs index bb5b94d86fa..8f5d8340526 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -15,6 +15,7 @@ use char::Char; use cmp::Equiv; use container::{Container, Mutable}; use fmt; +use from_str::FromStr; use io::Writer; use iter::{Extendable, FromIterator, Iterator, range}; use mem; @@ -22,8 +23,8 @@ use option::{None, Option, Some}; use ptr::RawPtr; use ptr; use result::{Result, Ok, Err}; -use slice::{OwnedVector, Vector, CloneableVector}; -use str::{CharRange, OwnedStr, Str, StrSlice, StrAllocating}; +use slice::Vector; +use str::{CharRange, Str, StrSlice, StrAllocating}; use str; use vec::Vec; @@ -68,10 +69,8 @@ impl StrBuf { /// Creates a new string buffer from the given owned string, taking care not to copy it. #[inline] - pub fn from_owned_str(string: ~str) -> StrBuf { - StrBuf { - vec: string.into_bytes().move_iter().collect(), - } + pub fn from_owned_str(string: StrBuf) -> StrBuf { + string } /// Returns the vector as a string buffer, if possible, taking care not to @@ -192,6 +191,13 @@ impl StrBuf { self.vec.as_slice() } + /// Works with the underlying buffer as a mutable byte slice. Unsafe + /// because this can be used to violate the UTF-8 property. + #[inline] + pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] { + self.vec.as_mut_slice() + } + /// Shorten a string to the specified length (which must be <= the current length) #[inline] pub fn truncate(&mut self, len: uint) { @@ -315,14 +321,14 @@ impl Str for StrBuf { impl StrAllocating for StrBuf { #[inline] - fn into_owned(self) -> ~str { - unsafe { - mem::transmute(self.vec.as_slice().to_owned()) - } + fn into_owned(self) -> StrBuf { + self } #[inline] - fn into_strbuf(self) -> StrBuf { self } + fn into_strbuf(self) -> StrBuf { + self + } } impl fmt::Show for StrBuf { @@ -345,6 +351,13 @@ impl<'a, S: Str> Equiv for StrBuf { } } +impl FromStr for StrBuf { + #[inline] + fn from_str(s: &str) -> Option { + Some(s.to_strbuf()) + } +} + #[cfg(test)] mod tests { extern crate test; diff --git a/src/libsyntax/crateid.rs b/src/libsyntax/crateid.rs index c2b5804ecee..dc699bb9850 100644 --- a/src/libsyntax/crateid.rs +++ b/src/libsyntax/crateid.rs @@ -54,12 +54,14 @@ impl FromStr for CrateId { let pieces: Vec<&str> = s.splitn('#', 1).collect(); let path = pieces.get(0).to_owned(); - if path.starts_with("/") || path.ends_with("/") || - path.starts_with(".") || path.is_empty() { + if path.as_slice().starts_with("/") || path.as_slice().ends_with("/") || + path.as_slice().starts_with(".") || path.is_empty() { return None; } - let path_pieces: Vec<&str> = path.rsplitn('/', 1).collect(); + let path_pieces: Vec<&str> = path.as_slice() + .rsplitn('/', 1) + .collect(); let inferred_name = *path_pieces.get(0); let (name, version) = if pieces.len() == 1 { diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index aa8f397f747..446a8f93753 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -106,7 +106,7 @@ impl SpanHandler { fail!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { - self.span_bug(sp, "unimplemented ".to_owned() + msg); + self.span_bug(sp, format!("unimplemented {}", msg).as_slice()); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler @@ -162,7 +162,7 @@ impl Handler { fail!(ExplicitBug); } pub fn unimpl(&self, msg: &str) -> ! { - self.bug("unimplemented ".to_owned() + msg); + self.bug(format!("unimplemented {}", msg).as_slice()); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, @@ -434,7 +434,8 @@ fn highlight_lines(err: &mut EmitterWriter, s.push_char('~'); } } - try!(print_maybe_styled(err, s.into_owned() + "\n", + try!(print_maybe_styled(err, + format!("{}\n", s).as_slice(), term::attr::ForegroundColor(lvl.color()))); } Ok(()) @@ -479,7 +480,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, s.push_char('^'); s.push_char('\n'); print_maybe_styled(w, - s.into_owned(), + s.as_slice(), term::attr::ForegroundColor(lvl.color())) } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index 2fa1c13f5d7..f9f5322625f 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -217,7 +217,7 @@ pub fn expand_asm(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) node: ast::ExprInlineAsm(ast::InlineAsm { asm: token::intern_and_get_ident(asm.get()), asm_str_style: asm_str_style.unwrap(), - clobbers: token::intern_and_get_ident(cons), + clobbers: token::intern_and_get_ident(cons.as_slice()), inputs: inputs, outputs: outputs, volatile: volatile, diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 314d63c2d3b..b2baff8d286 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -59,5 +59,5 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, } base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(accumulator.into_owned()))) + token::intern_and_get_ident(accumulator.as_slice()))) } diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 0e168e7b33b..24478358d79 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -42,7 +42,7 @@ pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } } } - let res = str_to_ident(res_str.into_owned()); + let res = str_to_ident(res_str.as_slice()); let e = @ast::Expr { id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index b3eec136c7d..bb3a88f44e4 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -436,7 +436,7 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> @ast::Expr { ast::TyI32 => "TyI32".to_owned(), ast::TyI64 => "TyI64".to_owned() }; - let e_ity = cx.expr_ident(sp, id_ext(s_ity)); + let e_ity = cx.expr_ident(sp, id_ext(s_ity.as_slice())); let e_i64 = cx.expr_lit(sp, ast::LitInt(i, ast::TyI64)); @@ -453,7 +453,7 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> @ast::Expr { ast::TyU32 => "TyU32".to_owned(), ast::TyU64 => "TyU64".to_owned() }; - let e_uty = cx.expr_ident(sp, id_ext(s_uty)); + let e_uty = cx.expr_ident(sp, id_ext(s_uty.as_slice())); let e_u64 = cx.expr_lit(sp, ast::LitUint(u, ast::TyU64)); @@ -476,7 +476,7 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> @ast::Expr { ast::TyF64 => "TyF64".to_owned(), ast::TyF128 => "TyF128".to_owned() }; - let e_fty = cx.expr_ident(sp, id_ext(s_fty)); + let e_fty = cx.expr_ident(sp, id_ext(s_fty.as_slice())); let e_fident = mk_ident(cx, sp, fident); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 52f262b052b..452719d2dd8 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -76,7 +76,9 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) .map(|x| token::get_ident(*x).get().to_strbuf()) .collect::>() .connect("::"); - base::MacExpr::new(cx.expr_str(sp, token::intern_and_get_ident(string))) + base::MacExpr::new(cx.expr_str( + sp, + token::intern_and_get_ident(string.as_slice()))) } // include! : parse the given file as an expr diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 89e8d48425f..54308536ab2 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -455,6 +455,9 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { res } "matchers" => token::NtMatchers(p.parse_matchers()), - _ => p.fatal("unsupported builtin nonterminal parser: ".to_owned() + name) + _ => { + p.fatal(format!("unsupported builtin nonterminal parser: {}", + name).as_slice()) + } } } diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index c78d2aaf3a7..5a7a816dbb3 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -589,13 +589,13 @@ fn scan_number(c: char, rdr: &mut StringReader) -> token::Token { bump(rdr); bump(rdr); check_float_base(rdr, start_bpos, rdr.last_pos, base); - return token::LIT_FLOAT(str_to_ident(num_str.into_owned()), + return token::LIT_FLOAT(str_to_ident(num_str.as_slice()), ast::TyF32); } else if c == '6' && n == '4' { bump(rdr); bump(rdr); check_float_base(rdr, start_bpos, rdr.last_pos, base); - return token::LIT_FLOAT(str_to_ident(num_str.into_owned()), + return token::LIT_FLOAT(str_to_ident(num_str.as_slice()), ast::TyF64); /* FIXME (#2252): if this is out of range for either a 32-bit or 64-bit float, it won't be noticed till the @@ -612,8 +612,7 @@ fn scan_number(c: char, rdr: &mut StringReader) -> token::Token { } if is_float { check_float_base(rdr, start_bpos, rdr.last_pos, base); - return token::LIT_FLOAT_UNSUFFIXED(str_to_ident( - num_str.into_owned())); + return token::LIT_FLOAT_UNSUFFIXED(str_to_ident(num_str.as_slice())); } else { if num_str.len() == 0u { fatal_span(rdr, start_bpos, rdr.last_pos, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 6bddb45201c..7d0276ae16f 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -4242,8 +4242,8 @@ impl<'a> Parser<'a> { Some(d) => (dir_path.join(d), true), None => { let mod_name = mod_string.get().to_owned(); - let default_path_str = mod_name + ".rs"; - let secondary_path_str = mod_name + "/mod.rs"; + let default_path_str = format!("{}.rs", mod_name); + let secondary_path_str = format!("{}/mod.rs", mod_name); let default_path = dir_path.join(default_path_str.as_slice()); let secondary_path = dir_path.join(secondary_path_str.as_slice()); let default_exists = default_path.exists(); @@ -4310,7 +4310,7 @@ impl<'a> Parser<'a> { err.push_str(" -> "); } err.push_str(path.display().as_maybe_owned().as_slice()); - self.span_fatal(id_sp, err.into_owned()); + self.span_fatal(id_sp, err.as_slice()); } None => () } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 785ab6be0dd..60cf7a67cbe 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -141,7 +141,8 @@ pub fn to_str(f: |&mut State| -> IoResult<()>) -> StrBuf { // that we "know" to be a `MemWriter` that works around the lack of checked // downcasts. let (_, wr): (uint, Box) = mem::transmute_copy(&s.s.out); - let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap(); + let result = + str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap(); mem::forget(wr); result.to_strbuf() } @@ -2234,7 +2235,7 @@ impl<'a> State<'a> { let mut res = StrBuf::from_str("'"); ch.escape_default(|c| res.push_char(c)); res.push_char('\''); - word(&mut self.s, res.into_owned()) + word(&mut self.s, res.as_slice()) } ast::LitInt(i, t) => { word(&mut self.s, diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 5a1c8ea02e2..687e27f4282 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -221,7 +221,8 @@ pub fn parse(file: &mut io::Reader, longnames: bool) None => return Err("input not utf-8".to_strbuf()), }; - let term_names: Vec = names_str.split('|') + let term_names: Vec = names_str.as_slice() + .split('|') .map(|s| s.to_strbuf()) .collect(); -- cgit 1.4.1-3-g733a5 From e878721d70349e2055f0ef854085de92e9498fde Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 19 May 2014 23:19:56 -0700 Subject: libcore: Remove all uses of `~str` from `libcore`. [breaking-change] --- src/compiletest/compiletest.rs | 8 +- src/compiletest/errors.rs | 2 +- src/compiletest/procsrv.rs | 3 +- src/compiletest/runtest.rs | 19 +- src/doc/complement-cheatsheet.md | 4 +- src/liballoc/heap.rs | 12 +- src/liballoc/util.rs | 17 ++ src/libcollections/bitv.rs | 2 +- src/libcore/any.rs | 14 +- src/libcore/bool.rs | 6 +- src/libcore/cell.rs | 5 +- src/libcore/char.rs | 69 ++++-- src/libcore/cmp.rs | 2 +- src/libcore/fmt/mod.rs | 8 +- src/libcore/fmt/num.rs | 230 +++++++++--------- src/libcore/mem.rs | 3 +- src/libcore/option.rs | 24 +- src/libcore/ptr.rs | 5 +- src/libcore/raw.rs | 1 - src/libcore/result.rs | 113 ++++----- src/libcore/should_not_exist.rs | 112 +-------- src/libcore/str.rs | 50 +--- src/libcore/tuple.rs | 13 +- src/libglob/lib.rs | 8 +- src/libnative/io/file_win32.rs | 4 +- src/libnative/io/process.rs | 8 +- src/libnum/bigint.rs | 259 +++++++++++++++++---- src/libnum/rational.rs | 2 +- src/libregex/parse/mod.rs | 6 +- src/libregex/test/bench.rs | 26 ++- src/libregex_macros/lib.rs | 2 +- src/librustc/back/link.rs | 6 +- src/librustc/back/rpath.rs | 7 +- src/librustc/driver/config.rs | 4 +- src/librustc/front/feature_gate.rs | 4 +- src/librustc/middle/trans/foreign.rs | 3 +- src/librustc/middle/trans/reflect.rs | 4 +- src/librustc/middle/weak_lang_items.rs | 4 +- src/librustdoc/clean.rs | 5 +- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/markdown.rs | 7 +- src/librustdoc/html/render.rs | 4 +- src/librustdoc/passes.rs | 10 +- src/librustdoc/test.rs | 4 +- src/libserialize/hex.rs | 12 +- src/libserialize/json.rs | 2 +- src/libstd/ascii.rs | 6 +- src/libstd/io/fs.rs | 9 +- src/libstd/io/process.rs | 6 +- src/libstd/os.rs | 61 ++--- src/libstd/rt/args.rs | 44 ++-- src/libstd/rt/util.rs | 1 + src/libstd/str.rs | 146 ++++++------ src/libstd/strbuf.rs | 7 + src/libstd/unstable/dynamic_lib.rs | 5 +- src/libsyntax/ext/asm.rs | 4 +- src/libsyntax/ext/tt/macro_parser.rs | 4 +- src/libsyntax/parse/parser.rs | 6 +- src/libsyntax/print/pprust.rs | 5 +- src/libtest/lib.rs | 8 +- src/libtime/lib.rs | 7 - src/libuuid/lib.rs | 10 +- src/test/bench/core-map.rs | 2 +- src/test/bench/core-set.rs | 2 +- src/test/bench/core-uint-to-str.rs | 2 +- src/test/bench/msgsend-ring-mutex-arcs.rs | 4 +- src/test/bench/msgsend-ring-rw-arcs.rs | 4 +- src/test/bench/rt-messaging-ping-pong.rs | 4 +- src/test/bench/rt-parfib.rs | 2 +- src/test/bench/rt-spawn-rate.rs | 2 +- src/test/bench/shootout-ackermann.rs | 2 +- src/test/bench/shootout-binarytrees.rs | 2 +- src/test/bench/shootout-chameneos-redux.rs | 7 +- src/test/bench/shootout-fannkuch-redux.rs | 5 +- src/test/bench/shootout-fasta-redux.rs | 2 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-fibo.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 8 +- src/test/bench/shootout-k-nucleotide.rs | 4 +- src/test/bench/shootout-mandelbrot.rs | 2 +- src/test/bench/shootout-nbody.rs | 2 +- src/test/bench/shootout-pidigits.rs | 2 +- src/test/bench/shootout-regex-dna.rs | 2 +- src/test/bench/shootout-spectralnorm.rs | 2 +- src/test/bench/shootout-threadring.rs | 6 +- src/test/bench/std-smallintmap.rs | 4 +- src/test/bench/sudoku.rs | 5 +- src/test/bench/task-perf-jargon-metal-smoke.rs | 2 +- src/test/bench/task-perf-spawnalot.rs | 2 +- src/test/compile-fail/closure-reform-bad.rs | 2 +- src/test/compile-fail/lint-heap-memory.rs | 1 - src/test/compile-fail/regions-glb-free-free.rs | 6 +- .../compile-fail/trait-coercion-generic-regions.rs | 2 +- src/test/compile-fail/unsafe-modifying-str.rs | 18 -- src/test/pretty/match-naked-expr-long.rs | 25 -- src/test/run-fail/issue-3029.rs | 1 - src/test/run-make/unicode-input/multiple_files.rs | 6 +- src/test/run-make/unicode-input/span_length.rs | 10 +- src/test/run-pass/auto-ref-slice-plus-ref.rs | 1 - src/test/run-pass/issue-3574.rs | 12 +- src/test/run-pass/let-assignability.rs | 4 +- src/test/run-pass/let-destruct-ref.rs | 4 +- src/test/run-pass/linear-for-loop.rs | 2 +- src/test/run-pass/log-err-phi.rs | 6 +- src/test/run-pass/option-ext.rs | 2 +- src/test/run-pass/regions-borrow-estr-uniq.rs | 23 -- src/test/run-pass/str-idx.rs | 2 +- src/test/run-pass/super-fast-paren-parsing.rs | 2 +- src/test/run-pass/syntax-extension-source-utils.rs | 10 +- src/test/run-pass/task-comm-16.rs | 8 +- 110 files changed, 876 insertions(+), 800 deletions(-) delete mode 100644 src/test/compile-fail/unsafe-modifying-str.rs delete mode 100644 src/test/pretty/match-naked-expr-long.rs delete mode 100644 src/test/run-pass/regions-borrow-estr-uniq.rs (limited to 'src/libsyntax/parse') diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index de764d02064..fa5d85111da 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -323,11 +323,15 @@ pub fn is_test(config: &Config, testfile: &Path) -> bool { let mut valid = false; for ext in valid_extensions.iter() { - if name.ends_with(*ext) { valid = true; } + if name.ends_with(ext.as_slice()) { + valid = true; + } } for pre in invalid_prefixes.iter() { - if name.starts_with(*pre) { valid = false; } + if name.starts_with(pre.as_slice()) { + valid = false; + } } return valid; diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index 408206b16e9..534e04ccb2d 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -24,7 +24,7 @@ pub fn load_errors(re: &Regex, testfile: &Path) -> Vec { let mut rdr = BufferedReader::new(File::open(testfile).unwrap()); rdr.lines().enumerate().filter_map(|(line_no, ln)| { - parse_expected(line_no + 1, ln.unwrap(), re) + parse_expected(line_no + 1, ln.unwrap().as_slice(), re) }).collect() } diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index 6b273c2d463..2622cf0e5f1 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -15,7 +15,8 @@ use std::unstable::dynamic_lib::DynamicLibrary; fn target_env(lib_path: &str, prog: &str) -> Vec<(StrBuf, StrBuf)> { let prog = if cfg!(windows) {prog.slice_to(prog.len() - 4)} else {prog}; - let aux_path = prog + ".libaux"; + let mut aux_path = prog.to_strbuf(); + aux_path.push_str(".libaux"); // Need to be sure to put both the lib_path and the aux path in the dylib // search path for the child. diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index d8ca94ab464..c591c477563 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -351,7 +351,10 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { cmds, "quit".to_strbuf()].connect("\n"); debug!("script_str = {}", script_str); - dump_output_file(config, testfile, script_str, "debugger.script"); + dump_output_file(config, + testfile, + script_str.as_slice(), + "debugger.script"); procsrv::run("", @@ -459,7 +462,10 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { "quit\n".to_strbuf() ].connect("\n"); debug!("script_str = {}", script_str); - dump_output_file(config, testfile, script_str, "debugger.script"); + dump_output_file(config, + testfile, + script_str.as_slice(), + "debugger.script"); // run debugger script with gdb #[cfg(windows)] @@ -553,7 +559,10 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) // Write the script into a file debug!("script_str = {}", script_str); - dump_output_file(config, testfile, script_str.into_owned(), "debugger.script"); + dump_output_file(config, + testfile, + script_str.as_slice(), + "debugger.script"); let debugger_script = make_out_name(config, testfile, "debugger.script"); // Let LLDB execute the script via lldb_batchmode.py @@ -610,8 +619,8 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str) -> DebuggerCommands { use std::io::{BufferedReader, File}; - let command_directive = debugger_prefix + "-command"; - let check_directive = debugger_prefix + "-check"; + let command_directive = format!("{}-command", debugger_prefix); + let check_directive = format!("{}-check", debugger_prefix); let mut breakpoint_lines = vec!(); let mut commands = vec!(); diff --git a/src/doc/complement-cheatsheet.md b/src/doc/complement-cheatsheet.md index 4670a2922cf..99f7c229d4e 100644 --- a/src/doc/complement-cheatsheet.md +++ b/src/doc/complement-cheatsheet.md @@ -60,8 +60,8 @@ To return an Owned String (StrBuf) use the str helper function [`from_utf8_owned ~~~ use std::str; -let x: Result = - str::from_utf8_owned(~[104u8,105u8]).map(|x| x.to_strbuf()); +let x: Option = + str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_strbuf()); let y: StrBuf = x.unwrap(); ~~~ diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index 631b72cb897..8376fc578db 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -116,18 +116,18 @@ pub fn stats_print() { } } +// The compiler never calls `exchange_free` on ~ZeroSizeType, so zero-size +// allocations can point to this `static`. It would be incorrect to use a null +// pointer, due to enums assuming types like unique pointers are never null. +pub static mut EMPTY: uint = 12345; + /// The allocator for unique pointers. #[cfg(not(test))] #[lang="exchange_malloc"] #[inline] unsafe fn exchange_malloc(size: uint, align: uint) -> *mut u8 { - // The compiler never calls `exchange_free` on ~ZeroSizeType, so zero-size - // allocations can point to this `static`. It would be incorrect to use a null - // pointer, due to enums assuming types like unique pointers are never null. - static EMPTY: () = (); - if size == 0 { - &EMPTY as *() as *mut u8 + &EMPTY as *uint as *mut u8 } else { allocate(size, align) } diff --git a/src/liballoc/util.rs b/src/liballoc/util.rs index 7e35af79eab..64d62035890 100644 --- a/src/liballoc/util.rs +++ b/src/liballoc/util.rs @@ -28,3 +28,20 @@ fn align_to(size: uint, align: uint) -> uint { assert!(align != 0); (size + align - 1) & !(align - 1) } + +// FIXME(#14344): When linking liballoc with libstd, this library will be linked +// as an rlib (it only exists as an rlib). It turns out that an +// optimized standard library doesn't actually use *any* symbols +// from this library. Everything is inlined and optimized away. +// This means that linkers will actually omit the object for this +// file, even though it may be needed in the future. +// +// To get around this for now, we define a dummy symbol which +// will never get inlined so the stdlib can call it. The stdlib's +// reference to this symbol will cause this library's object file +// to get linked in to libstd successfully (the linker won't +// optimize it out). +#[deprecated] +#[doc(hidden)] +pub fn make_stdlib_link_work() {} + diff --git a/src/libcollections/bitv.rs b/src/libcollections/bitv.rs index 1c9940c5b1f..82cca507c4d 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bitv.rs @@ -1330,7 +1330,7 @@ mod tests { #[test] fn test_from_bytes() { let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); - let str = "10110110".to_owned() + "00000000" + "11111111"; + let str = format!("{}{}{}", "10110110", "00000000", "11111111"); assert_eq!(bitv.to_str(), str); } diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 61c1193e515..94ac344db34 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -119,7 +119,7 @@ mod tests { use prelude::*; use super::*; use realstd::owned::{Box, AnyOwnExt}; - use realstd::str::StrAllocating; + use realstd::str::{Str, StrAllocating}; #[deriving(Eq, Show)] struct Test; @@ -249,13 +249,17 @@ mod tests { use realstd::to_str::ToStr; let a = box 8u as Box<::realstd::any::Any>; let b = box Test as Box<::realstd::any::Any>; - assert_eq!(a.to_str(), "Box".to_owned()); - assert_eq!(b.to_str(), "Box".to_owned()); + let a_str = a.to_str(); + let b_str = b.to_str(); + assert_eq!(a_str.as_slice(), "Box"); + assert_eq!(b_str.as_slice(), "Box"); let a = &8u as &Any; let b = &Test as &Any; - assert_eq!(format!("{}", a), "&Any".to_owned()); - assert_eq!(format!("{}", b), "&Any".to_owned()); + let s = format!("{}", a); + assert_eq!(s.as_slice(), "&Any"); + let s = format!("{}", b); + assert_eq!(s.as_slice(), "&Any"); } } diff --git a/src/libcore/bool.rs b/src/libcore/bool.rs index 2a44d141719..ddfdbca196c 100644 --- a/src/libcore/bool.rs +++ b/src/libcore/bool.rs @@ -242,8 +242,10 @@ mod tests { #[test] fn test_to_str() { - assert_eq!(false.to_str(), "false".to_owned()); - assert_eq!(true.to_str(), "true".to_owned()); + let s = false.to_str(); + assert_eq!(s.as_slice(), "false"); + let s = true.to_str(); + assert_eq!(s.as_slice(), "true"); } #[test] diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 093b3f57047..3ad2ebb9f0a 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -404,12 +404,13 @@ mod test { #[test] fn cell_has_sensible_show() { use str::StrSlice; + use realstd::str::Str; let x = Cell::new("foo bar"); - assert!(format!("{}", x).contains(x.get())); + assert!(format!("{}", x).as_slice().contains(x.get())); x.set("baz qux"); - assert!(format!("{}", x).contains(x.get())); + assert!(format!("{}", x).as_slice().contains(x.get())); } #[test] diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 6e9d4c9bafb..f3942dfd753 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -637,7 +637,7 @@ mod test { use slice::ImmutableVector; use option::{Some, None}; use realstd::strbuf::StrBuf; - use realstd::str::StrAllocating; + use realstd::str::{Str, StrAllocating}; #[test] fn test_is_lowercase() { @@ -742,46 +742,65 @@ mod test { #[test] fn test_escape_default() { - fn string(c: char) -> ~str { + fn string(c: char) -> StrBuf { let mut result = StrBuf::new(); escape_default(c, |c| { result.push_char(c); }); - return result.into_owned(); + return result; } - assert_eq!(string('\n'), "\\n".to_owned()); - assert_eq!(string('\r'), "\\r".to_owned()); - assert_eq!(string('\''), "\\'".to_owned()); - assert_eq!(string('"'), "\\\"".to_owned()); - assert_eq!(string(' '), " ".to_owned()); - assert_eq!(string('a'), "a".to_owned()); - assert_eq!(string('~'), "~".to_owned()); - assert_eq!(string('\x00'), "\\x00".to_owned()); - assert_eq!(string('\x1f'), "\\x1f".to_owned()); - assert_eq!(string('\x7f'), "\\x7f".to_owned()); - assert_eq!(string('\xff'), "\\xff".to_owned()); - assert_eq!(string('\u011b'), "\\u011b".to_owned()); - assert_eq!(string('\U0001d4b6'), "\\U0001d4b6".to_owned()); + let s = string('\n'); + assert_eq!(s.as_slice(), "\\n"); + let s = string('\r'); + assert_eq!(s.as_slice(), "\\r"); + let s = string('\''); + assert_eq!(s.as_slice(), "\\'"); + let s = string('"'); + assert_eq!(s.as_slice(), "\\\""); + let s = string(' '); + assert_eq!(s.as_slice(), " "); + let s = string('a'); + assert_eq!(s.as_slice(), "a"); + let s = string('~'); + assert_eq!(s.as_slice(), "~"); + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\x1f'); + assert_eq!(s.as_slice(), "\\x1f"); + let s = string('\x7f'); + assert_eq!(s.as_slice(), "\\x7f"); + let s = string('\xff'); + assert_eq!(s.as_slice(), "\\xff"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); } #[test] fn test_escape_unicode() { - fn string(c: char) -> ~str { + fn string(c: char) -> StrBuf { let mut result = StrBuf::new(); escape_unicode(c, |c| { result.push_char(c); }); - return result.into_owned(); + return result; } - assert_eq!(string('\x00'), "\\x00".to_owned()); - assert_eq!(string('\n'), "\\x0a".to_owned()); - assert_eq!(string(' '), "\\x20".to_owned()); - assert_eq!(string('a'), "\\x61".to_owned()); - assert_eq!(string('\u011b'), "\\u011b".to_owned()); - assert_eq!(string('\U0001d4b6'), "\\U0001d4b6".to_owned()); + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\n'); + assert_eq!(s.as_slice(), "\\x0a"); + let s = string(' '); + assert_eq!(s.as_slice(), "\\x20"); + let s = string('a'); + assert_eq!(s.as_slice(), "\\x61"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); } #[test] fn test_to_str() { use realstd::to_str::ToStr; let s = 't'.to_str(); - assert_eq!(s, "t".to_owned()); + assert_eq!(s.as_slice(), "t"); } #[test] diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index a50108607ce..bf1f3ee310c 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -171,7 +171,7 @@ pub trait Ord: Eq { /// The equivalence relation. Two values may be equivalent even if they are /// of different types. The most common use case for this relation is /// container types; e.g. it is often desirable to be able to use `&str` -/// values to look up entries in a container with `~str` keys. +/// values to look up entries in a container with `StrBuf` keys. pub trait Equiv { /// Implement this function to decide equivalent values. fn equiv(&self, other: &T) -> bool; diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index af492dc295a..cc965bc6eed 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -594,7 +594,7 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, } #[cfg(test)] -pub fn format(args: &Arguments) -> ~str { +pub fn format(args: &Arguments) -> ::realstd::strbuf::StrBuf { use str; use realstd::str::StrAllocating; use realstd::io::MemWriter; @@ -613,7 +613,10 @@ pub fn format(args: &Arguments) -> ~str { let mut i = MemWriter::new(); let _ = write(&mut i, args); - str::from_utf8(i.get_ref()).unwrap().to_owned() + + let mut result = ::realstd::strbuf::StrBuf::new(); + result.push_str(str::from_utf8(i.get_ref()).unwrap()); + result } /// When the compiler determines that the type of an argument *must* be a string @@ -761,7 +764,6 @@ macro_rules! delegate(($ty:ty to $other:ident) => { } } }) -delegate!(~str to string) delegate!(&'a str to string) delegate!(bool to bool) delegate!(char to char) diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index d9a32713781..75f67c3df65 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -194,7 +194,7 @@ mod tests { use fmt::radix; use super::{Binary, Octal, Decimal, LowerHex, UpperHex}; use super::{GenericRadix, Radix}; - use realstd::str::StrAllocating; + use realstd::str::{Str, StrAllocating}; #[test] fn test_radix_base() { @@ -246,143 +246,143 @@ mod tests { // Formatting integers should select the right implementation based off // the type of the argument. Also, hex/octal/binary should be defined // for integers, but they shouldn't emit the negative sign. - assert_eq!(format!("{}", 1i), "1".to_owned()); - assert_eq!(format!("{}", 1i8), "1".to_owned()); - assert_eq!(format!("{}", 1i16), "1".to_owned()); - assert_eq!(format!("{}", 1i32), "1".to_owned()); - assert_eq!(format!("{}", 1i64), "1".to_owned()); - assert_eq!(format!("{:d}", -1i), "-1".to_owned()); - assert_eq!(format!("{:d}", -1i8), "-1".to_owned()); - assert_eq!(format!("{:d}", -1i16), "-1".to_owned()); - assert_eq!(format!("{:d}", -1i32), "-1".to_owned()); - assert_eq!(format!("{:d}", -1i64), "-1".to_owned()); - assert_eq!(format!("{:t}", 1i), "1".to_owned()); - assert_eq!(format!("{:t}", 1i8), "1".to_owned()); - assert_eq!(format!("{:t}", 1i16), "1".to_owned()); - assert_eq!(format!("{:t}", 1i32), "1".to_owned()); - assert_eq!(format!("{:t}", 1i64), "1".to_owned()); - assert_eq!(format!("{:x}", 1i), "1".to_owned()); - assert_eq!(format!("{:x}", 1i8), "1".to_owned()); - assert_eq!(format!("{:x}", 1i16), "1".to_owned()); - assert_eq!(format!("{:x}", 1i32), "1".to_owned()); - assert_eq!(format!("{:x}", 1i64), "1".to_owned()); - assert_eq!(format!("{:X}", 1i), "1".to_owned()); - assert_eq!(format!("{:X}", 1i8), "1".to_owned()); - assert_eq!(format!("{:X}", 1i16), "1".to_owned()); - assert_eq!(format!("{:X}", 1i32), "1".to_owned()); - assert_eq!(format!("{:X}", 1i64), "1".to_owned()); - assert_eq!(format!("{:o}", 1i), "1".to_owned()); - assert_eq!(format!("{:o}", 1i8), "1".to_owned()); - assert_eq!(format!("{:o}", 1i16), "1".to_owned()); - assert_eq!(format!("{:o}", 1i32), "1".to_owned()); - assert_eq!(format!("{:o}", 1i64), "1".to_owned()); - - assert_eq!(format!("{}", 1u), "1".to_owned()); - assert_eq!(format!("{}", 1u8), "1".to_owned()); - assert_eq!(format!("{}", 1u16), "1".to_owned()); - assert_eq!(format!("{}", 1u32), "1".to_owned()); - assert_eq!(format!("{}", 1u64), "1".to_owned()); - assert_eq!(format!("{:u}", 1u), "1".to_owned()); - assert_eq!(format!("{:u}", 1u8), "1".to_owned()); - assert_eq!(format!("{:u}", 1u16), "1".to_owned()); - assert_eq!(format!("{:u}", 1u32), "1".to_owned()); - assert_eq!(format!("{:u}", 1u64), "1".to_owned()); - assert_eq!(format!("{:t}", 1u), "1".to_owned()); - assert_eq!(format!("{:t}", 1u8), "1".to_owned()); - assert_eq!(format!("{:t}", 1u16), "1".to_owned()); - assert_eq!(format!("{:t}", 1u32), "1".to_owned()); - assert_eq!(format!("{:t}", 1u64), "1".to_owned()); - assert_eq!(format!("{:x}", 1u), "1".to_owned()); - assert_eq!(format!("{:x}", 1u8), "1".to_owned()); - assert_eq!(format!("{:x}", 1u16), "1".to_owned()); - assert_eq!(format!("{:x}", 1u32), "1".to_owned()); - assert_eq!(format!("{:x}", 1u64), "1".to_owned()); - assert_eq!(format!("{:X}", 1u), "1".to_owned()); - assert_eq!(format!("{:X}", 1u8), "1".to_owned()); - assert_eq!(format!("{:X}", 1u16), "1".to_owned()); - assert_eq!(format!("{:X}", 1u32), "1".to_owned()); - assert_eq!(format!("{:X}", 1u64), "1".to_owned()); - assert_eq!(format!("{:o}", 1u), "1".to_owned()); - assert_eq!(format!("{:o}", 1u8), "1".to_owned()); - assert_eq!(format!("{:o}", 1u16), "1".to_owned()); - assert_eq!(format!("{:o}", 1u32), "1".to_owned()); - assert_eq!(format!("{:o}", 1u64), "1".to_owned()); + assert!(format!("{}", 1i).as_slice() == "1"); + assert!(format!("{}", 1i8).as_slice() == "1"); + assert!(format!("{}", 1i16).as_slice() == "1"); + assert!(format!("{}", 1i32).as_slice() == "1"); + assert!(format!("{}", 1i64).as_slice() == "1"); + assert!(format!("{:d}", -1i).as_slice() == "-1"); + assert!(format!("{:d}", -1i8).as_slice() == "-1"); + assert!(format!("{:d}", -1i16).as_slice() == "-1"); + assert!(format!("{:d}", -1i32).as_slice() == "-1"); + assert!(format!("{:d}", -1i64).as_slice() == "-1"); + assert!(format!("{:t}", 1i).as_slice() == "1"); + assert!(format!("{:t}", 1i8).as_slice() == "1"); + assert!(format!("{:t}", 1i16).as_slice() == "1"); + assert!(format!("{:t}", 1i32).as_slice() == "1"); + assert!(format!("{:t}", 1i64).as_slice() == "1"); + assert!(format!("{:x}", 1i).as_slice() == "1"); + assert!(format!("{:x}", 1i8).as_slice() == "1"); + assert!(format!("{:x}", 1i16).as_slice() == "1"); + assert!(format!("{:x}", 1i32).as_slice() == "1"); + assert!(format!("{:x}", 1i64).as_slice() == "1"); + assert!(format!("{:X}", 1i).as_slice() == "1"); + assert!(format!("{:X}", 1i8).as_slice() == "1"); + assert!(format!("{:X}", 1i16).as_slice() == "1"); + assert!(format!("{:X}", 1i32).as_slice() == "1"); + assert!(format!("{:X}", 1i64).as_slice() == "1"); + assert!(format!("{:o}", 1i).as_slice() == "1"); + assert!(format!("{:o}", 1i8).as_slice() == "1"); + assert!(format!("{:o}", 1i16).as_slice() == "1"); + assert!(format!("{:o}", 1i32).as_slice() == "1"); + assert!(format!("{:o}", 1i64).as_slice() == "1"); + + assert!(format!("{}", 1u).as_slice() == "1"); + assert!(format!("{}", 1u8).as_slice() == "1"); + assert!(format!("{}", 1u16).as_slice() == "1"); + assert!(format!("{}", 1u32).as_slice() == "1"); + assert!(format!("{}", 1u64).as_slice() == "1"); + assert!(format!("{:u}", 1u).as_slice() == "1"); + assert!(format!("{:u}", 1u8).as_slice() == "1"); + assert!(format!("{:u}", 1u16).as_slice() == "1"); + assert!(format!("{:u}", 1u32).as_slice() == "1"); + assert!(format!("{:u}", 1u64).as_slice() == "1"); + assert!(format!("{:t}", 1u).as_slice() == "1"); + assert!(format!("{:t}", 1u8).as_slice() == "1"); + assert!(format!("{:t}", 1u16).as_slice() == "1"); + assert!(format!("{:t}", 1u32).as_slice() == "1"); + assert!(format!("{:t}", 1u64).as_slice() == "1"); + assert!(format!("{:x}", 1u).as_slice() == "1"); + assert!(format!("{:x}", 1u8).as_slice() == "1"); + assert!(format!("{:x}", 1u16).as_slice() == "1"); + assert!(format!("{:x}", 1u32).as_slice() == "1"); + assert!(format!("{:x}", 1u64).as_slice() == "1"); + assert!(format!("{:X}", 1u).as_slice() == "1"); + assert!(format!("{:X}", 1u8).as_slice() == "1"); + assert!(format!("{:X}", 1u16).as_slice() == "1"); + assert!(format!("{:X}", 1u32).as_slice() == "1"); + assert!(format!("{:X}", 1u64).as_slice() == "1"); + assert!(format!("{:o}", 1u).as_slice() == "1"); + assert!(format!("{:o}", 1u8).as_slice() == "1"); + assert!(format!("{:o}", 1u16).as_slice() == "1"); + assert!(format!("{:o}", 1u32).as_slice() == "1"); + assert!(format!("{:o}", 1u64).as_slice() == "1"); // Test a larger number - assert_eq!(format!("{:t}", 55), "110111".to_owned()); - assert_eq!(format!("{:o}", 55), "67".to_owned()); - assert_eq!(format!("{:d}", 55), "55".to_owned()); - assert_eq!(format!("{:x}", 55), "37".to_owned()); - assert_eq!(format!("{:X}", 55), "37".to_owned()); + assert!(format!("{:t}", 55).as_slice() == "110111"); + assert!(format!("{:o}", 55).as_slice() == "67"); + assert!(format!("{:d}", 55).as_slice() == "55"); + assert!(format!("{:x}", 55).as_slice() == "37"); + assert!(format!("{:X}", 55).as_slice() == "37"); } #[test] fn test_format_int_zero() { - assert_eq!(format!("{}", 0i), "0".to_owned()); - assert_eq!(format!("{:d}", 0i), "0".to_owned()); - assert_eq!(format!("{:t}", 0i), "0".to_owned()); - assert_eq!(format!("{:o}", 0i), "0".to_owned()); - assert_eq!(format!("{:x}", 0i), "0".to_owned()); - assert_eq!(format!("{:X}", 0i), "0".to_owned()); - - assert_eq!(format!("{}", 0u), "0".to_owned()); - assert_eq!(format!("{:u}", 0u), "0".to_owned()); - assert_eq!(format!("{:t}", 0u), "0".to_owned()); - assert_eq!(format!("{:o}", 0u), "0".to_owned()); - assert_eq!(format!("{:x}", 0u), "0".to_owned()); - assert_eq!(format!("{:X}", 0u), "0".to_owned()); + assert!(format!("{}", 0i).as_slice() == "0"); + assert!(format!("{:d}", 0i).as_slice() == "0"); + assert!(format!("{:t}", 0i).as_slice() == "0"); + assert!(format!("{:o}", 0i).as_slice() == "0"); + assert!(format!("{:x}", 0i).as_slice() == "0"); + assert!(format!("{:X}", 0i).as_slice() == "0"); + + assert!(format!("{}", 0u).as_slice() == "0"); + assert!(format!("{:u}", 0u).as_slice() == "0"); + assert!(format!("{:t}", 0u).as_slice() == "0"); + assert!(format!("{:o}", 0u).as_slice() == "0"); + assert!(format!("{:x}", 0u).as_slice() == "0"); + assert!(format!("{:X}", 0u).as_slice() == "0"); } #[test] fn test_format_int_flags() { - assert_eq!(format!("{:3d}", 1), " 1".to_owned()); - assert_eq!(format!("{:>3d}", 1), " 1".to_owned()); - assert_eq!(format!("{:>+3d}", 1), " +1".to_owned()); - assert_eq!(format!("{:<3d}", 1), "1 ".to_owned()); - assert_eq!(format!("{:#d}", 1), "1".to_owned()); - assert_eq!(format!("{:#x}", 10), "0xa".to_owned()); - assert_eq!(format!("{:#X}", 10), "0xA".to_owned()); - assert_eq!(format!("{:#5x}", 10), " 0xa".to_owned()); - assert_eq!(format!("{:#o}", 10), "0o12".to_owned()); - assert_eq!(format!("{:08x}", 10), "0000000a".to_owned()); - assert_eq!(format!("{:8x}", 10), " a".to_owned()); - assert_eq!(format!("{:<8x}", 10), "a ".to_owned()); - assert_eq!(format!("{:>8x}", 10), " a".to_owned()); - assert_eq!(format!("{:#08x}", 10), "0x00000a".to_owned()); - assert_eq!(format!("{:08d}", -10), "-0000010".to_owned()); - assert_eq!(format!("{:x}", -1u8), "ff".to_owned()); - assert_eq!(format!("{:X}", -1u8), "FF".to_owned()); - assert_eq!(format!("{:t}", -1u8), "11111111".to_owned()); - assert_eq!(format!("{:o}", -1u8), "377".to_owned()); - assert_eq!(format!("{:#x}", -1u8), "0xff".to_owned()); - assert_eq!(format!("{:#X}", -1u8), "0xFF".to_owned()); - assert_eq!(format!("{:#t}", -1u8), "0b11111111".to_owned()); - assert_eq!(format!("{:#o}", -1u8), "0o377".to_owned()); + assert!(format!("{:3d}", 1).as_slice() == " 1"); + assert!(format!("{:>3d}", 1).as_slice() == " 1"); + assert!(format!("{:>+3d}", 1).as_slice() == " +1"); + assert!(format!("{:<3d}", 1).as_slice() == "1 "); + assert!(format!("{:#d}", 1).as_slice() == "1"); + assert!(format!("{:#x}", 10).as_slice() == "0xa"); + assert!(format!("{:#X}", 10).as_slice() == "0xA"); + assert!(format!("{:#5x}", 10).as_slice() == " 0xa"); + assert!(format!("{:#o}", 10).as_slice() == "0o12"); + assert!(format!("{:08x}", 10).as_slice() == "0000000a"); + assert!(format!("{:8x}", 10).as_slice() == " a"); + assert!(format!("{:<8x}", 10).as_slice() == "a "); + assert!(format!("{:>8x}", 10).as_slice() == " a"); + assert!(format!("{:#08x}", 10).as_slice() == "0x00000a"); + assert!(format!("{:08d}", -10).as_slice() == "-0000010"); + assert!(format!("{:x}", -1u8).as_slice() == "ff"); + assert!(format!("{:X}", -1u8).as_slice() == "FF"); + assert!(format!("{:t}", -1u8).as_slice() == "11111111"); + assert!(format!("{:o}", -1u8).as_slice() == "377"); + assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); + assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); + assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); + assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); } #[test] fn test_format_int_sign_padding() { - assert_eq!(format!("{:+5d}", 1), " +1".to_owned()); - assert_eq!(format!("{:+5d}", -1), " -1".to_owned()); - assert_eq!(format!("{:05d}", 1), "00001".to_owned()); - assert_eq!(format!("{:05d}", -1), "-0001".to_owned()); - assert_eq!(format!("{:+05d}", 1), "+0001".to_owned()); - assert_eq!(format!("{:+05d}", -1), "-0001".to_owned()); + assert!(format!("{:+5d}", 1).as_slice() == " +1"); + assert!(format!("{:+5d}", -1).as_slice() == " -1"); + assert!(format!("{:05d}", 1).as_slice() == "00001"); + assert!(format!("{:05d}", -1).as_slice() == "-0001"); + assert!(format!("{:+05d}", 1).as_slice() == "+0001"); + assert!(format!("{:+05d}", -1).as_slice() == "-0001"); } #[test] fn test_format_int_twos_complement() { use {i8, i16, i32, i64}; - assert_eq!(format!("{}", i8::MIN), "-128".to_owned()); - assert_eq!(format!("{}", i16::MIN), "-32768".to_owned()); - assert_eq!(format!("{}", i32::MIN), "-2147483648".to_owned()); - assert_eq!(format!("{}", i64::MIN), "-9223372036854775808".to_owned()); + assert!(format!("{}", i8::MIN).as_slice() == "-128"); + assert!(format!("{}", i16::MIN).as_slice() == "-32768"); + assert!(format!("{}", i32::MIN).as_slice() == "-2147483648"); + assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808"); } #[test] fn test_format_radix() { - assert_eq!(format!("{:04}", radix(3, 2)), "0011".to_owned()); - assert_eq!(format!("{}", radix(55, 36)), "1j".to_owned()); + assert!(format!("{:04}", radix(3, 2)).as_slice() == "0011"); + assert!(format!("{}", radix(55, 36)).as_slice() == "1j"); } #[test] diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index aa7a8f0f8b6..b72eebe85c5 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -469,6 +469,7 @@ mod tests { use option::{Some,None}; use realstd::str::StrAllocating; use realstd::owned::Box; + use realstd::vec::Vec; use raw; #[test] @@ -568,7 +569,7 @@ mod tests { } unsafe { - assert_eq!(box [76u8], transmute("L".to_owned())); + assert!(Vec::from_slice([76u8]) == transmute("L".to_owned())); } } } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 00f21ee4c9c..adea8ac630e 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -188,14 +188,14 @@ impl Option { /// /// # Example /// - /// Convert an `Option<~str>` into an `Option`, preserving the original. + /// Convert an `Option` into an `Option`, preserving the original. /// The `map` method takes the `self` argument by value, consuming the original, /// so this technique uses `as_ref` to first take an `Option` to a reference /// to the value inside the original. /// /// ``` - /// let num_as_str: Option<~str> = Some("10".to_owned()); - /// // First, cast `Option<~str>` to `Option<&~str>` with `as_ref`, + /// let num_as_str: Option = Some("10".to_strbuf()); + /// // First, cast `Option` to `Option<&StrBuf>` with `as_ref`, /// // then consume *that* with `map`, leaving `num_as_str` on the stack. /// let num_as_int: Option = num_as_str.as_ref().map(|n| n.len()); /// println!("still can print num_as_str: {}", num_as_str); @@ -278,10 +278,10 @@ impl Option { /// /// # Example /// - /// Convert an `Option<~str>` into an `Option`, consuming the original: + /// Convert an `Option` into an `Option`, consuming the original: /// /// ``` - /// let num_as_str: Option<~str> = Some("10".to_owned()); + /// let num_as_str: Option = Some("10".to_strbuf()); /// // `Option::map` takes self *by value*, consuming `num_as_str` /// let num_as_int: Option = num_as_str.map(|n| n.len()); /// ``` @@ -596,9 +596,10 @@ pub fn collect>, V: FromIterator>(iter: Iter) -> #[cfg(test)] mod tests { use realstd::vec::Vec; - use realstd::str::StrAllocating; + use realstd::strbuf::StrBuf; use option::collect; use prelude::*; + use realstd::str::{Str, StrAllocating}; use iter::range; use str::StrSlice; @@ -619,11 +620,11 @@ mod tests { #[test] fn test_get_str() { - let x = "test".to_owned(); - let addr_x = x.as_ptr(); + let x = "test".to_strbuf(); + let addr_x = x.as_slice().as_ptr(); let opt = Some(x); let y = opt.unwrap(); - let addr_y = y.as_ptr(); + let addr_y = y.as_slice().as_ptr(); assert_eq!(addr_x, addr_y); } @@ -745,7 +746,8 @@ mod tests { #[test] fn test_unwrap() { assert_eq!(Some(1).unwrap(), 1); - assert_eq!(Some("hello".to_owned()).unwrap(), "hello".to_owned()); + let s = Some("hello".to_strbuf()).unwrap(); + assert_eq!(s.as_slice(), "hello"); } #[test] @@ -758,7 +760,7 @@ mod tests { #[test] #[should_fail] fn test_unwrap_fail2() { - let x: Option<~str> = None; + let x: Option = None; x.unwrap(); } diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 870fa0ec53f..90b5b0d8753 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -486,6 +486,7 @@ pub mod ptr_tests { use mem; use libc; use realstd::str; + use realstd::str::Str; use slice::{ImmutableVector, MutableVector}; #[test] @@ -660,7 +661,7 @@ pub mod ptr_tests { let expected = expected_arr[ctr].with_ref(|buf| { str::raw::from_c_str(buf) }); - assert_eq!(actual, expected); + assert_eq!(actual.as_slice(), expected.as_slice()); ctr += 1; iteration_count += 1; }); @@ -693,7 +694,7 @@ pub mod ptr_tests { let expected = expected_arr[ctr].with_ref(|buf| { str::raw::from_c_str(buf) }); - assert_eq!(actual, expected); + assert_eq!(actual.as_slice(), expected.as_slice()); ctr += 1; iteration_count += 1; }); diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index 25f40b358ab..979eeb657b6 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -81,7 +81,6 @@ impl<'a, T> Repr> for &'a [T] {} impl<'a> Repr> for &'a str {} impl Repr<*Box> for @T {} impl Repr<*Vec> for ~[T] {} -impl Repr<*String> for ~str {} #[cfg(test)] mod tests { diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 46f4427e838..98d1782f20f 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -169,20 +169,24 @@ //! ~~~ //! use std::io::{File, Open, Write, IoError}; //! -//! struct Info { name: ~str, age: int, rating: int } +//! struct Info { +//! name: StrBuf, +//! age: int, +//! rating: int +//! } //! //! fn write_info(info: &Info) -> Result<(), IoError> { //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write); //! // Early return on error -//! match file.write_line(format!("name: {}", info.name)) { +//! match file.write_line(format!("name: {}", info.name).as_slice()) { //! Ok(_) => (), //! Err(e) => return Err(e) //! } -//! match file.write_line(format!("age: {}", info.age)) { +//! match file.write_line(format!("age: {}", info.age).as_slice()) { //! Ok(_) => (), //! Err(e) => return Err(e) //! } -//! return file.write_line(format!("rating: {}", info.rating)); +//! return file.write_line(format!("rating: {}", info.rating).as_slice()); //! } //! ~~~ //! @@ -191,14 +195,18 @@ //! ~~~ //! use std::io::{File, Open, Write, IoError}; //! -//! struct Info { name: ~str, age: int, rating: int } +//! struct Info { +//! name: StrBuf, +//! age: int, +//! rating: int +//! } //! //! fn write_info(info: &Info) -> Result<(), IoError> { //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write); //! // Early return on error -//! try!(file.write_line(format!("name: {}", info.name))); -//! try!(file.write_line(format!("age: {}", info.age))); -//! try!(file.write_line(format!("rating: {}", info.rating))); +//! try!(file.write_line(format!("name: {}", info.name).as_slice())); +//! try!(file.write_line(format!("age: {}", info.age).as_slice())); +//! try!(file.write_line(format!("rating: {}", info.rating).as_slice())); //! return Ok(()); //! } //! ~~~ @@ -421,10 +429,10 @@ impl Result { /// let mut sum = 0; /// /// while !reader.eof() { - /// let line: IoResult<~str> = reader.read_line(); + /// let line: IoResult = reader.read_line(); /// // Convert the string line to a number using `map` and `from_str` /// let val: IoResult = line.map(|line| { - /// from_str::(line).unwrap_or(0) + /// from_str::(line.as_slice()).unwrap_or(0) /// }); /// // Add the value if there were no errors, otherwise add 0 /// sum += val.ok().unwrap_or(0); @@ -629,69 +637,68 @@ pub fn fold_>>(iterator: Iter) -> Result<(),E> { #[cfg(test)] mod tests { use realstd::vec::Vec; - use realstd::str::StrAllocating; + use realstd::strbuf::StrBuf; use result::{collect, fold, fold_}; use prelude::*; + use realstd::str::{Str, StrAllocating}; use iter::range; - pub fn op1() -> Result { Ok(666) } - pub fn op2() -> Result { Err("sadface".to_owned()) } + pub fn op1() -> Result { Ok(666) } + pub fn op2() -> Result { Err("sadface") } #[test] pub fn test_and() { assert_eq!(op1().and(Ok(667)).unwrap(), 667); - assert_eq!(op1().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "bad".to_owned()); + assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), + "bad"); - assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface".to_owned()); - assert_eq!(op2().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "sadface".to_owned()); + assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface"); + assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), + "sadface"); } #[test] pub fn test_and_then() { - assert_eq!(op1().and_then(|i| Ok::(i + 1)).unwrap(), 667); - assert_eq!(op1().and_then(|_| Err::("bad".to_owned())).unwrap_err(), - "bad".to_owned()); - - assert_eq!(op2().and_then(|i| Ok::(i + 1)).unwrap_err(), - "sadface".to_owned()); - assert_eq!(op2().and_then(|_| Err::("bad".to_owned())).unwrap_err(), - "sadface".to_owned()); + assert_eq!(op1().and_then(|i| Ok::(i + 1)).unwrap(), 667); + assert_eq!(op1().and_then(|_| Err::("bad")).unwrap_err(), + "bad"); + + assert_eq!(op2().and_then(|i| Ok::(i + 1)).unwrap_err(), + "sadface"); + assert_eq!(op2().and_then(|_| Err::("bad")).unwrap_err(), + "sadface"); } #[test] pub fn test_or() { assert_eq!(op1().or(Ok(667)).unwrap(), 666); - assert_eq!(op1().or(Err("bad".to_owned())).unwrap(), 666); + assert_eq!(op1().or(Err("bad")).unwrap(), 666); assert_eq!(op2().or(Ok(667)).unwrap(), 667); - assert_eq!(op2().or(Err("bad".to_owned())).unwrap_err(), "bad".to_owned()); + assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad"); } #[test] pub fn test_or_else() { - assert_eq!(op1().or_else(|_| Ok::(667)).unwrap(), 666); - assert_eq!(op1().or_else(|e| Err::(e + "!")).unwrap(), 666); + assert_eq!(op1().or_else(|_| Ok::(667)).unwrap(), 666); + assert_eq!(op1().or_else(|e| Err::(e)).unwrap(), 666); - assert_eq!(op2().or_else(|_| Ok::(667)).unwrap(), 667); - assert_eq!(op2().or_else(|e| Err::(e + "!")).unwrap_err(), - "sadface!".to_owned()); + assert_eq!(op2().or_else(|_| Ok::(667)).unwrap(), 667); + assert_eq!(op2().or_else(|e| Err::(e)).unwrap_err(), + "sadface"); } #[test] pub fn test_impl_map() { - assert_eq!(Ok::<~str, ~str>("a".to_owned()).map(|x| x + "b"), - Ok("ab".to_owned())); - assert_eq!(Err::<~str, ~str>("a".to_owned()).map(|x| x + "b"), - Err("a".to_owned())); + assert!(Ok::(1).map(|x| x + 1) == Ok(2)); + assert!(Err::(1).map(|x| x + 1) == Err(1)); } #[test] pub fn test_impl_map_err() { - assert_eq!(Ok::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), - Ok("a".to_owned())); - assert_eq!(Err::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), - Err("ab".to_owned())); + assert!(Ok::(1).map_err(|x| x + 1) == Ok(1)); + assert!(Err::(1).map_err(|x| x + 1) == Err(2)); } #[test] @@ -736,17 +743,19 @@ mod tests { #[test] pub fn test_fmt_default() { - let ok: Result = Ok(100); - let err: Result = Err("Err".to_owned()); + let ok: Result = Ok(100); + let err: Result = Err("Err"); - assert_eq!(format!("{}", ok), "Ok(100)".to_owned()); - assert_eq!(format!("{}", err), "Err(Err)".to_owned()); + let s = format!("{}", ok); + assert_eq!(s.as_slice(), "Ok(100)"); + let s = format!("{}", err); + assert_eq!(s.as_slice(), "Err(Err)"); } #[test] pub fn test_unwrap_or() { - let ok: Result = Ok(100); - let ok_err: Result = Err("Err".to_owned()); + let ok: Result = Ok(100); + let ok_err: Result = Err("Err"); assert_eq!(ok.unwrap_or(50), 100); assert_eq!(ok_err.unwrap_or(50), 50); @@ -754,16 +763,16 @@ mod tests { #[test] pub fn test_unwrap_or_else() { - fn handler(msg: ~str) -> int { - if msg == "I got this.".to_owned() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { 50 } else { fail!("BadBad") } } - let ok: Result = Ok(100); - let ok_err: Result = Err("I got this.".to_owned()); + let ok: Result = Ok(100); + let ok_err: Result = Err("I got this."); assert_eq!(ok.unwrap_or_else(handler), 100); assert_eq!(ok_err.unwrap_or_else(handler), 50); @@ -772,15 +781,15 @@ mod tests { #[test] #[should_fail] pub fn test_unwrap_or_else_failure() { - fn handler(msg: ~str) -> int { - if msg == "I got this.".to_owned() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { 50 } else { fail!("BadBad") } } - let bad_err: Result = Err("Unrecoverable mess.".to_owned()); + let bad_err: Result = Err("Unrecoverable mess."); let _ : int = bad_err.unwrap_or_else(handler); } } diff --git a/src/libcore/should_not_exist.rs b/src/libcore/should_not_exist.rs index 2046017869d..9a0e3ad7ca4 100644 --- a/src/libcore/should_not_exist.rs +++ b/src/libcore/should_not_exist.rs @@ -10,9 +10,9 @@ // As noted by this file name, this file should not exist. This file should not // exist because it performs allocations which libcore is not allowed to do. The -// reason for this file's existence is that the `~[T]` and `~str` types are -// language-defined types. Traits are defined in libcore, such as `Clone`, which -// these types need to implement, but the implementation can only be found in +// reason for this file's existence is that the `~[T]` type is a language- +// defined type. Traits are defined in libcore, such as `Clone`, which these +// types need to implement, but the implementation can only be found in // libcore. // // Plan of attack for solving this problem: @@ -24,13 +24,11 @@ // // Currently, no progress has been made on this list. -use char::Char; use clone::Clone; use container::Container; -use default::Default; use finally::try_finally; use intrinsics; -use iter::{range, Iterator, FromIterator}; +use iter::{range, Iterator}; use mem; use num::{CheckedMul, CheckedAdd}; use option::{Some, None}; @@ -38,9 +36,6 @@ use ptr::RawPtr; use ptr; use raw::Vec; use slice::ImmutableVector; -use str::StrSlice; - -#[cfg(not(test))] use ops::Add; #[allow(ctypes)] extern { @@ -60,105 +55,6 @@ unsafe fn alloc(cap: uint) -> *mut Vec<()> { ret } -// Strings - -impl Default for ~str { - fn default() -> ~str { - unsafe { - // Get some memory - let ptr = alloc(0); - - // Initialize the memory - (*ptr).fill = 0; - (*ptr).alloc = 0; - - mem::transmute(ptr) - } - } -} - -impl Clone for ~str { - fn clone(&self) -> ~str { - // Don't use the clone() implementation above because it'll start - // requiring the eh_personality lang item (no fun) - unsafe { - let bytes = self.as_bytes().as_ptr(); - let len = self.len(); - - let ptr = alloc(len) as *mut Vec; - ptr::copy_nonoverlapping_memory(&mut (*ptr).data, bytes, len); - (*ptr).fill = len; - (*ptr).alloc = len; - - mem::transmute(ptr) - } - } -} - -impl FromIterator for ~str { - #[inline] - fn from_iter>(mut iterator: T) -> ~str { - let (lower, _) = iterator.size_hint(); - let mut cap = if lower == 0 {16} else {lower}; - let mut len = 0; - let mut tmp = [0u8, ..4]; - - unsafe { - let mut ptr = alloc(cap) as *mut Vec; - let mut ret = mem::transmute(ptr); - for ch in iterator { - let amt = ch.encode_utf8(tmp); - - if len + amt > cap { - cap = cap.checked_mul(&2).unwrap(); - if cap < len + amt { - cap = len + amt; - } - let ptr2 = alloc(cap) as *mut Vec; - ptr::copy_nonoverlapping_memory(&mut (*ptr2).data, - &(*ptr).data, - len); - // FIXME: #13994: port to the sized deallocation API when available - rust_deallocate(ptr as *u8, 0, 8); - mem::forget(ret); - ret = mem::transmute(ptr2); - ptr = ptr2; - } - - let base = &mut (*ptr).data as *mut u8; - for byte in tmp.slice_to(amt).iter() { - *base.offset(len as int) = *byte; - len += 1; - } - (*ptr).fill = len; - } - ret - } - } -} - -#[cfg(not(test))] -impl<'a> Add<&'a str,~str> for &'a str { - #[inline] - fn add(&self, rhs: & &'a str) -> ~str { - let amt = self.len().checked_add(&rhs.len()).unwrap(); - unsafe { - let ptr = alloc(amt) as *mut Vec; - let base = &mut (*ptr).data as *mut _; - ptr::copy_nonoverlapping_memory(base, - self.as_bytes().as_ptr(), - self.len()); - let base = base.offset(self.len() as int); - ptr::copy_nonoverlapping_memory(base, - rhs.as_bytes().as_ptr(), - rhs.len()); - (*ptr).fill = amt; - (*ptr).alloc = amt; - mem::transmute(ptr) - } - } -} - // Arrays impl Clone for ~[A] { diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 19be2fd3169..0b264b1724d 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -25,7 +25,7 @@ use iter::range; use num::Saturating; use option::{None, Option, Some}; use raw::Repr; -use slice::{ImmutableVector, Vector}; +use slice::ImmutableVector; use slice; use uint; @@ -596,20 +596,6 @@ pub fn eq_slice(a: &str, b: &str) -> bool { eq_slice_(a, b) } -/// Bytewise string equality -#[cfg(not(test))] -#[lang="uniq_str_eq"] -#[inline] -pub fn eq(a: &~str, b: &~str) -> bool { - eq_slice(*a, *b) -} - -#[cfg(test)] -#[inline] -pub fn eq(a: &~str, b: &~str) -> bool { - eq_slice(*a, *b) -} - /* Section: Misc */ @@ -976,11 +962,6 @@ pub mod traits { } } - impl TotalOrd for ~str { - #[inline] - fn cmp(&self, other: &~str) -> Ordering { self.as_slice().cmp(&other.as_slice()) } - } - impl<'a> Eq for &'a str { #[inline] fn eq(&self, other: & &'a str) -> bool { @@ -990,36 +971,17 @@ pub mod traits { fn ne(&self, other: & &'a str) -> bool { !(*self).eq(other) } } - impl Eq for ~str { - #[inline] - fn eq(&self, other: &~str) -> bool { - eq_slice((*self), (*other)) - } - } - impl<'a> TotalEq for &'a str {} - impl TotalEq for ~str {} - impl<'a> Ord for &'a str { #[inline] fn lt(&self, other: & &'a str) -> bool { self.cmp(other) == Less } } - impl Ord for ~str { - #[inline] - fn lt(&self, other: &~str) -> bool { self.cmp(other) == Less } - } - impl<'a, S: Str> Equiv for &'a str { #[inline] fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) } } - - impl<'a, S: Str> Equiv for ~str { - #[inline] - fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) } - } } #[cfg(test)] @@ -1036,11 +998,6 @@ impl<'a> Str for &'a str { fn as_slice<'a>(&'a self) -> &'a str { *self } } -impl<'a> Str for ~str { - #[inline] - fn as_slice<'a>(&'a self) -> &'a str { let s: &'a str = *self; s } -} - impl<'a> Container for &'a str { #[inline] fn len(&self) -> uint { @@ -1048,11 +1005,6 @@ impl<'a> Container for &'a str { } } -impl Container for ~str { - #[inline] - fn len(&self) -> uint { self.as_slice().len() } -} - /// Methods for string slices pub trait StrSlice<'a> { /// Returns true if one string contains another diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index b73d85489a3..0e21c95807d 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -246,11 +246,11 @@ mod tests { use super::*; use clone::Clone; use cmp::*; - use realstd::str::StrAllocating; + use realstd::str::{Str, StrAllocating}; #[test] fn test_clone() { - let a = (1, "2".to_owned()); + let a = (1, "2"); let b = a.clone(); assert_eq!(a, b); } @@ -323,8 +323,11 @@ mod tests { #[test] fn test_show() { - assert_eq!(format!("{}", (1,)), "(1,)".to_owned()); - assert_eq!(format!("{}", (1, true)), "(1, true)".to_owned()); - assert_eq!(format!("{}", (1, "hi".to_owned(), true)), "(1, hi, true)".to_owned()); + let s = format!("{}", (1,)); + assert_eq!(s.as_slice(), "(1,)"); + let s = format!("{}", (1, true)); + assert_eq!(s.as_slice(), "(1, true)"); + let s = format!("{}", (1, "hi", true)); + assert_eq!(s.as_slice(), "(1, hi, true)"); } } diff --git a/src/libglob/lib.rs b/src/libglob/lib.rs index 7b9260c7eb9..e4b1278f3d9 100644 --- a/src/libglob/lib.rs +++ b/src/libglob/lib.rs @@ -690,13 +690,13 @@ mod test { let pat = Pattern::new("a[0-9]b"); for i in range(0, 10) { - assert!(pat.matches(format!("a{}b", i))); + assert!(pat.matches(format!("a{}b", i).as_slice())); } assert!(!pat.matches("a_b")); let pat = Pattern::new("a[!0-9]b"); for i in range(0, 10) { - assert!(!pat.matches(format!("a{}b", i))); + assert!(!pat.matches(format!("a{}b", i).as_slice())); } assert!(pat.matches("a_b")); @@ -704,11 +704,11 @@ mod test { for &p in pats.iter() { let pat = Pattern::new(p); for c in "abcdefghijklmnopqrstuvwxyz".chars() { - assert!(pat.matches(c.to_str())); + assert!(pat.matches(c.to_str().as_slice())); } for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() { let options = MatchOptions {case_sensitive: false, .. MatchOptions::new()}; - assert!(pat.matches_with(c.to_str(), options)); + assert!(pat.matches_with(c.to_str().as_slice(), options)); } assert!(pat.matches("1")); assert!(pat.matches("2")); diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index 9693f772170..f320aca2bfc 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -450,7 +450,9 @@ pub fn readlink(p: &CString) -> IoResult { libc::VOLUME_NAME_DOS) }); let ret = match ret { - Some(ref s) if s.starts_with(r"\\?\") => Ok(Path::new(s.slice_from(4))), + Some(ref s) if s.as_slice().starts_with(r"\\?\") => { + Ok(Path::new(s.as_slice().slice_from(4))) + } Some(s) => Ok(Path::new(s)), None => Err(super::last_error()), }; diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index 04911bc5f1b..80b00dfb3fe 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -323,7 +323,7 @@ fn spawn_process_os(cfg: ProcessConfig, in_fd: c_int, out_fd: c_int, err_fd: c_i with_envp(cfg.env, |envp| { with_dirp(cfg.cwd, |dirp| { - os::win32::as_mut_utf16_p(cmd_str, |cmdp| { + os::win32::as_mut_utf16_p(cmd_str.as_slice(), |cmdp| { let created = CreateProcessW(ptr::null(), cmdp, ptr::mut_null(), @@ -396,7 +396,7 @@ fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMA } #[cfg(windows)] -fn make_command_line(prog: &CString, args: &[CString]) -> ~str { +fn make_command_line(prog: &CString, args: &[CString]) -> StrBuf { let mut cmd = StrBuf::new(); append_arg(&mut cmd, prog.as_str() .expect("expected program name to be utf-8 encoded")); @@ -405,7 +405,7 @@ fn make_command_line(prog: &CString, args: &[CString]) -> ~str { append_arg(&mut cmd, arg.as_str() .expect("expected argument to be utf-8 encoded")); } - return cmd.into_owned(); + return cmd; fn append_arg(cmd: &mut StrBuf, arg: &str) { let quote = arg.chars().any(|c| c == ' ' || c == '\t'); @@ -1093,7 +1093,7 @@ mod tests { use std::c_str::CString; use super::make_command_line; - fn test_wrapper(prog: &str, args: &[&str]) -> ~str { + fn test_wrapper(prog: &str, args: &[&str]) -> StrBuf { make_command_line(&prog.to_c_str(), args.iter() .map(|a| a.to_c_str()) diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 748eea2ea93..9267aea01b4 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -634,7 +634,7 @@ impl ToStrRadix for BigUint { let mut s = StrBuf::with_capacity(v.len() * l); for n in v.iter().rev() { let ss = (*n as uint).to_str_radix(radix); - s.push_str("0".repeat(l - ss.len())); + s.push_str("0".repeat(l - ss.len()).as_slice()); s.push_str(ss.as_slice()); } s.as_slice().trim_left_chars('0').to_strbuf() @@ -1478,29 +1478,112 @@ mod biguint_tests { check("0", 3, "0"); check("1", 3, "8"); - check("1" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 3, - "8" + "0000" + "0000" + "0000" + "0008" + "0000" + "0000" + "0000" + "0008"); - check("1" + "0000" + "0001" + "0000" + "0001", 2, - "4" + "0000" + "0004" + "0000" + "0004"); - check("1" + "0001" + "0001", 1, - "2" + "0002" + "0002"); - - check("" + "4000" + "0000" + "0000" + "0000", 3, - "2" + "0000" + "0000" + "0000" + "0000"); - check("" + "4000" + "0000", 2, - "1" + "0000" + "0000"); - check("" + "4000", 2, - "1" + "0000"); - - check("" + "4000" + "0000" + "0000" + "0000", 67, - "2" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000"); - check("" + "4000" + "0000", 35, - "2" + "0000" + "0000" + "0000" + "0000"); - check("" + "4000", 19, - "2" + "0000" + "0000"); - - check("" + "fedc" + "ba98" + "7654" + "3210" + "fedc" + "ba98" + "7654" + "3210", 4, - "f" + "edcb" + "a987" + "6543" + "210f" + "edcb" + "a987" + "6543" + "2100"); + check("1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "8\ + 0000\ + 0000\ + 0000\ + 0008\ + 0000\ + 0000\ + 0000\ + 0008"); + check("1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4\ + 0000\ + 0004\ + 0000\ + 0004"); + check("1\ + 0001\ + 0001", + 1, + "2\ + 0002\ + 0002"); + + check("\ + 4000\ + 0000\ + 0000\ + 0000", + 3, + "2\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000\ + 0000", + 2, + "1\ + 0000\ + 0000"); + check("4000", + 2, + "1\ + 0000"); + + check("4000\ + 0000\ + 0000\ + 0000", + 67, + "2\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000\ + 0000", + 35, + "2\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000", + 19, + "2\ + 0000\ + 0000"); + + check("fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210", + 4, + "f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100"); check("88887777666655554444333322221111", 16, "888877776666555544443333222211110000"); } @@ -1517,28 +1600,107 @@ mod biguint_tests { check("0", 3, "0"); check("f", 3, "1"); - check("1" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 3, - "" + "2000" + "0000" + "0000" + "0000" + "2000" + "0000" + "0000" + "0000"); - check("1" + "0000" + "0001" + "0000" + "0001", 2, - "" + "4000" + "0000" + "4000" + "0000"); - check("1" + "0001" + "0001", 1, - "" + "8000" + "8000"); - - check("2" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 67, - "" + "4000" + "0000" + "0000" + "0000"); - check("2" + "0000" + "0001" + "0000" + "0001", 35, - "" + "4000" + "0000"); - check("2" + "0001" + "0001", 19, - "" + "4000"); - - check("1" + "0000" + "0000" + "0000" + "0000", 1, - "" + "8000" + "0000" + "0000" + "0000"); - check("1" + "0000" + "0000", 1, - "" + "8000" + "0000"); - check("1" + "0000", 1, - "" + "8000"); - check("f" + "edcb" + "a987" + "6543" + "210f" + "edcb" + "a987" + "6543" + "2100", 4, - "" + "fedc" + "ba98" + "7654" + "3210" + "fedc" + "ba98" + "7654" + "3210"); + check("1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "2000\ + 0000\ + 0000\ + 0000\ + 2000\ + 0000\ + 0000\ + 0000"); + check("1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4000\ + 0000\ + 4000\ + 0000"); + check("1\ + 0001\ + 0001", + 1, + "8000\ + 8000"); + + check("2\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 67, + "4000\ + 0000\ + 0000\ + 0000"); + check("2\ + 0000\ + 0001\ + 0000\ + 0001", + 35, + "4000\ + 0000"); + check("2\ + 0001\ + 0001", + 19, + "4000"); + + check("1\ + 0000\ + 0000\ + 0000\ + 0000", + 1, + "8000\ + 0000\ + 0000\ + 0000"); + check("1\ + 0000\ + 0000", + 1, + "8000\ + 0000"); + check("1\ + 0000", + 1, + "8000"); + check("f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100", + 4, + "fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210"); check("888877776666555544443333222211110000", 16, "88887777666655554444333322221111"); @@ -2545,7 +2707,7 @@ mod bigint_tests { fn test_to_str_radix() { fn check(n: int, ans: &str) { let n: BigInt = FromPrimitive::from_int(n).unwrap(); - assert!(ans == n.to_str_radix(10)); + assert!(ans == n.to_str_radix(10).as_slice()); } check(10, "10"); check(1, "1"); @@ -2574,7 +2736,8 @@ mod bigint_tests { // issue 10522, this hit an edge case that caused it to // attempt to allocate a vector of size (-1u) == huge. - let x: BigInt = from_str("1" + "0".repeat(36)).unwrap(); + let x: BigInt = + from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap(); let _y = x.to_str(); } diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index ac1982c3735..6191b93ff8f 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -584,7 +584,7 @@ mod test { #[test] fn test_to_from_str_radix() { fn test(r: Rational, s: StrBuf, n: uint) { - assert_eq!(FromStrRadix::from_str_radix(s.to_owned(), n), + assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n), Some(r)); assert_eq!(r.to_str_radix(n).to_strbuf(), s); } diff --git a/src/libregex/parse/mod.rs b/src/libregex/parse/mod.rs index 1356cef8768..beefda07f0a 100644 --- a/src/libregex/parse/mod.rs +++ b/src/libregex/parse/mod.rs @@ -513,11 +513,11 @@ impl<'a> Parser<'a> { // Parse the min and max values from the regex. let (mut min, mut max): (uint, Option); - if !inner.contains(",") { - min = try!(self.parse_uint(inner)); + if !inner.as_slice().contains(",") { + min = try!(self.parse_uint(inner.as_slice())); max = Some(min); } else { - let pieces: Vec<&str> = inner.splitn(',', 1).collect(); + let pieces: Vec<&str> = inner.as_slice().splitn(',', 1).collect(); let (smin, smax) = (*pieces.get(0), *pieces.get(1)); if smin.len() == 0 { return self.err("Max repetitions cannot be specified \ diff --git a/src/libregex/test/bench.rs b/src/libregex/test/bench.rs index 4c4ba8dd6bf..6fcbcbd265a 100644 --- a/src/libregex/test/bench.rs +++ b/src/libregex/test/bench.rs @@ -20,38 +20,40 @@ fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { #[bench] fn no_exponential(b: &mut Bencher) { let n = 100; - let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap(); + let re = Regex::new(format!("{}{}", + "a?".repeat(n), + "a".repeat(n)).as_slice()).unwrap(); let text = "a".repeat(n); - bench_assert_match(b, re, text); + bench_assert_match(b, re, text.as_slice()); } #[bench] fn literal(b: &mut Bencher) { let re = regex!("y"); - let text = "x".repeat(50) + "y"; - bench_assert_match(b, re, text); + let text = format!("{}y", "x".repeat(50)); + bench_assert_match(b, re, text.as_slice()); } #[bench] fn not_literal(b: &mut Bencher) { let re = regex!(".y"); - let text = "x".repeat(50) + "y"; - bench_assert_match(b, re, text); + let text = format!("{}y", "x".repeat(50)); + bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class(b: &mut Bencher) { let re = regex!("[abcdw]"); - let text = "xxxx".repeat(20) + "w"; - bench_assert_match(b, re, text); + let text = format!("{}w", "xxxx".repeat(20)); + bench_assert_match(b, re, text.as_slice()); } #[bench] fn match_class_in_range(b: &mut Bencher) { // 'b' is between 'a' and 'c', so the class range checking doesn't help. let re = regex!("[ac]"); - let text = "bbbb".repeat(20) + "c"; - bench_assert_match(b, re, text); + let text = format!("{}c", "bbbb".repeat(20)); + bench_assert_match(b, re, text.as_slice()); } #[bench] @@ -75,7 +77,7 @@ fn anchored_literal_short_non_match(b: &mut Bencher) { fn anchored_literal_long_non_match(b: &mut Bencher) { let re = regex!("^zbc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); - b.iter(|| re.is_match(text)); + b.iter(|| re.is_match(text.as_slice())); } #[bench] @@ -89,7 +91,7 @@ fn anchored_literal_short_match(b: &mut Bencher) { fn anchored_literal_long_match(b: &mut Bencher) { let re = regex!("^.bc(d|e)"); let text = "abcdefghijklmnopqrstuvwxyz".repeat(15); - b.iter(|| re.is_match(text)); + b.iter(|| re.is_match(text.as_slice())); } #[bench] diff --git a/src/libregex_macros/lib.rs b/src/libregex_macros/lib.rs index 300562e04f2..68320e8edd3 100644 --- a/src/libregex_macros/lib.rs +++ b/src/libregex_macros/lib.rs @@ -82,7 +82,7 @@ fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) // error is logged in 'parse' with cx.span_err None => return DummyResult::any(sp), }; - let re = match Regex::new(regex.to_owned()) { + let re = match Regex::new(regex.as_slice()) { Ok(re) => re, Err(err) => { cx.span_err(sp, err.to_str().as_slice()); diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 9d7c07498ff..57f3824ecc5 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -62,7 +62,9 @@ pub fn llvm_err(sess: &Session, msg: StrBuf) -> ! { } else { let err = CString::new(cstr, true); let err = str::from_utf8_lossy(err.as_bytes()); - sess.fatal((msg.as_slice() + ": " + err.as_slice())); + sess.fatal(format!("{}: {}", + msg.as_slice(), + err.as_slice()).as_slice()); } } } @@ -647,7 +649,7 @@ pub fn sanitize(s: &str) -> StrBuf { if result.len() > 0u && result.as_slice()[0] != '_' as u8 && ! char::is_XID_start(result.as_slice()[0] as char) { - return ("_" + result.as_slice()).to_strbuf(); + return format!("_{}", result.as_slice()).to_strbuf(); } return result; diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 8557cfc0bc2..8258fb5762b 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -59,7 +59,7 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec { pub fn rpaths_to_flags(rpaths: &[StrBuf]) -> Vec { let mut ret = Vec::new(); for rpath in rpaths.iter() { - ret.push(("-Wl,-rpath," + (*rpath).as_slice()).to_strbuf()); + ret.push(format!("-Wl,-rpath,{}", (*rpath).as_slice())); } return ret; } @@ -132,8 +132,9 @@ pub fn get_rpath_relative_to_output(os: abi::Os, let relative = lib.path_relative_from(&output); let relative = relative.expect("could not create rpath relative to output"); // FIXME (#9639): This needs to handle non-utf8 paths - (prefix + "/" + relative.as_str() - .expect("non-utf8 component in path")).to_strbuf() + format!("{}/{}", + prefix, + relative.as_str().expect("non-utf8 component in path")) } pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> StrBuf { diff --git a/src/librustc/driver/config.rs b/src/librustc/driver/config.rs index e8e970150fd..d80cf72bb46 100644 --- a/src/librustc/driver/config.rs +++ b/src/librustc/driver/config.rs @@ -469,8 +469,8 @@ pub fn build_target_config(sopts: &Options) -> Config { let arch = match get_arch(sopts.target_triple.as_slice()) { Some(arch) => arch, None => { - early_error("unknown architecture: " + - sopts.target_triple.as_slice()) + early_error(format!("unknown architecture: {}", + sopts.target_triple.as_slice()).as_slice()) } }; let (int_type, uint_type) = match arch { diff --git a/src/librustc/front/feature_gate.rs b/src/librustc/front/feature_gate.rs index ac863d82c9b..21a7fc8d150 100644 --- a/src/librustc/front/feature_gate.rs +++ b/src/librustc/front/feature_gate.rs @@ -259,7 +259,9 @@ impl<'a> Visitor<()> for Context<'a> { else { for "e in quotes.iter() { if id == token::str_to_ident(quote) { - self.gate_feature("quote", path.span, quote + msg); + self.gate_feature("quote", + path.span, + format!("{}{}", quote, msg).as_slice()); } } } diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 46c987270e3..e08ab33808a 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -163,7 +163,8 @@ pub fn register_static(ccx: &CrateContext, }); lib::llvm::SetLinkage(g1, linkage); - let real_name = "_rust_extern_with_linkage_" + ident.get(); + let mut real_name = "_rust_extern_with_linkage_".to_strbuf(); + real_name.push_str(ident.get()); let g2 = real_name.with_c_str(|buf| { llvm::LLVMAddGlobal(ccx.llmod, llty.to_ref(), buf) }); diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index a0184e2cbe3..a65802d2c36 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -117,9 +117,9 @@ impl<'a, 'b> Reflector<'a, 'b> { bracket_name: &str, extra: &[ValueRef], inner: |&mut Reflector|) { - self.visit("enter_" + bracket_name, extra); + self.visit(format!("enter_{}", bracket_name).as_slice(), extra); inner(self); - self.visit("leave_" + bracket_name, extra); + self.visit(format!("leave_{}", bracket_name).as_slice(), extra); } pub fn leaf(&mut self, name: &str) { diff --git a/src/librustc/middle/weak_lang_items.rs b/src/librustc/middle/weak_lang_items.rs index cbe04e4fcda..19233f0a59f 100644 --- a/src/librustc/middle/weak_lang_items.rs +++ b/src/librustc/middle/weak_lang_items.rs @@ -85,7 +85,7 @@ fn verify(sess: &Session, items: &lang_items::LanguageItems) { $( if missing.contains(&lang_items::$item) && items.$name().is_none() { sess.err(format!("language item required, but not found: `{}`", - stringify!($name))); + stringify!($name)).as_slice()); } )* @@ -100,7 +100,7 @@ impl<'a> Context<'a> { } else)* { self.sess.span_err(span, format!("unknown external lang item: `{}`", - name)); + name).as_slice()); } } } diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index 236c98b72e6..fb2a80333e8 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -1015,7 +1015,10 @@ impl Clean for ty::t { let fqn: Vec = fqn.move_iter().map(|i| { i.to_str().to_strbuf() }).collect(); - let mut path = external_path(fqn.last().unwrap().to_str()); + let mut path = external_path(fqn.last() + .unwrap() + .to_str() + .as_slice()); let kind = match ty::get(*self).sty { ty::ty_struct(..) => TypeStruct, ty::ty_trait(..) => TypeTrait, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 133e8c64042..65bc9f544f6 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -206,7 +206,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool, let amt = path.segments.len() - 1; match rel_root { Some(root) => { - let mut root = StrBuf::from_str(root); + let mut root = StrBuf::from_str(root.as_slice()); for seg in path.segments.slice_to(amt).iter() { if "super" == seg.name.as_slice() || "self" == seg.name.as_slice() { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index b64e77615e1..5f3c19d5754 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -177,8 +177,9 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { }; if !rendered { - let output = highlight::highlight(text, None).as_slice() - .to_c_str(); + let output = highlight::highlight(text.as_slice(), + None).as_slice() + .to_c_str(); output.with_ref(|r| { hoedown_buffer_puts(ob, r) }) @@ -202,7 +203,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { }; // Transform the contents of the header into a hyphenated string - let id = (s.words().map(|s| { + let id = (s.as_slice().words().map(|s| { match s.to_ascii_opt() { Some(s) => s.to_lower().into_str().to_strbuf(), None => s.to_strbuf() diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 94bd4d818b4..8744553955a 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -971,7 +971,7 @@ impl Context { // does make formatting *a lot* nicer. current_location_key.replace(Some(cx.current.clone())); - let mut title = StrBuf::from_str(cx.current.connect("::")); + let mut title = cx.current.connect("::"); if pushname { if title.len() > 0 { title.push_str("::"); @@ -1141,7 +1141,7 @@ fn item_path(item: &clean::Item) -> StrBuf { } fn full_path(cx: &Context, item: &clean::Item) -> StrBuf { - let mut s = StrBuf::from_str(cx.current.connect("::")); + let mut s = cx.current.connect("::"); s.push_str("::"); s.push_str(item.name.get_ref().as_slice()); return s diff --git a/src/librustdoc/passes.rs b/src/librustdoc/passes.rs index a0d993dfe7d..da18b7e8e92 100644 --- a/src/librustdoc/passes.rs +++ b/src/librustdoc/passes.rs @@ -346,14 +346,14 @@ mod unindent_tests { #[test] fn should_unindent() { let s = " line1\n line2".to_owned(); - let r = unindent(s); + let r = unindent(s.as_slice()); assert_eq!(r.as_slice(), "line1\nline2"); } #[test] fn should_unindent_multiple_paragraphs() { let s = " line1\n\n line2".to_owned(); - let r = unindent(s); + let r = unindent(s.as_slice()); assert_eq!(r.as_slice(), "line1\n\nline2"); } @@ -362,7 +362,7 @@ mod unindent_tests { // Line 2 is indented another level beyond the // base indentation and should be preserved let s = " line1\n\n line2".to_owned(); - let r = unindent(s); + let r = unindent(s.as_slice()); assert_eq!(r.as_slice(), "line1\n\n line2"); } @@ -374,14 +374,14 @@ mod unindent_tests { // #[doc = "Start way over here // and continue here"] let s = "line1\n line2".to_owned(); - let r = unindent(s); + let r = unindent(s.as_slice()); assert_eq!(r.as_slice(), "line1\nline2"); } #[test] fn should_not_ignore_first_line_indent_in_a_single_line_para() { let s = "line1\n\n line2".to_owned(); - let r = unindent(s); + let r = unindent(s.as_slice()); assert_eq!(r.as_slice(), "line1\n\n line2"); } } diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 949cd17fe9a..63e6b7e3664 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -171,7 +171,7 @@ fn runtest(test: &str, cratename: &str, libs: HashSet, should_fail: bool, // Remove the previous dylib search path var let var = DynamicLibrary::envvar(); - let mut env: Vec<(~str,~str)> = os::env().move_iter().collect(); + let mut env: Vec<(StrBuf,StrBuf)> = os::env().move_iter().collect(); match env.iter().position(|&(ref k, _)| k.as_slice() == var) { Some(i) => { env.remove(i); } None => {} @@ -276,7 +276,7 @@ impl Collector { }, testfn: testing::DynTestFn(proc() { runtest(test.as_slice(), - cratename, + cratename.as_slice(), libs, should_fail, no_run, diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 3b8500753cb..82ab5fd5b04 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -182,8 +182,16 @@ mod tests { #[test] pub fn test_from_hex_all_bytes() { for i in range(0, 256) { - assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap().as_slice(), &[i as u8]); - assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap().as_slice(), &[i as u8]); + assert_eq!(format!("{:02x}", i as uint).as_slice() + .from_hex() + .unwrap() + .as_slice(), + &[i as u8]); + assert_eq!(format!("{:02X}", i as uint).as_slice() + .from_hex() + .unwrap() + .as_slice(), + &[i as u8]); } } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index e6f46ea7159..92e3d5a2688 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -2483,7 +2483,7 @@ mod tests { // We can't compare the strings directly because the object fields be // printed in a different order. - assert_eq!(a.clone(), from_str(a.to_str()).unwrap()); + assert_eq!(a.clone(), from_str(a.to_str().as_slice()).unwrap()); assert_eq!(a.clone(), from_str(a.to_pretty_str().as_slice()).unwrap()); } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 0b3dd414967..e5689158601 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -656,7 +656,7 @@ mod tests { 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(), + assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_upper(), from_char(from_u32(upper).unwrap()).to_strbuf()) i += 1; } @@ -672,7 +672,7 @@ mod tests { 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(), + assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_lower(), from_char(from_u32(lower).unwrap()).to_strbuf()) i += 1; } @@ -730,7 +730,7 @@ mod tests { .eq_ignore_ascii_case( from_char( from_u32(lower) - .unwrap()))); + .unwrap()).as_slice())); i += 1; } } diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 6feaf10d5c5..d8edd6517d5 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -855,7 +855,7 @@ mod test { } check!(unlink(filename)); let read_str = str::from_utf8(read_mem).unwrap(); - assert!(read_str == final_msg.to_owned()); + assert!(read_str.as_slice() == final_msg.as_slice()); }) iotest!(fn file_test_io_seek_shakedown() { @@ -955,9 +955,8 @@ mod test { for n in range(0,3) { let f = dir.join(format_strbuf!("{}.txt", n)); let mut w = check!(File::create(&f)); - let msg_str = - (prefix + n.to_str().into_owned()).to_owned(); - let msg = msg_str.as_bytes(); + let msg_str = format!("{}{}", prefix, n.to_str()); + let msg = msg_str.as_slice().as_bytes(); check!(w.write(msg)); } let files = check!(readdir(dir)); @@ -969,7 +968,7 @@ mod test { let read_str = str::from_utf8(mem).unwrap(); let expected = match n { None|Some("") => fail!("really shouldn't happen.."), - Some(n) => prefix+n + Some(n) => format!("{}{}", prefix, n), }; assert_eq!(expected.as_slice(), read_str); } diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index f1f3e0a468a..7d84530282f 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -827,10 +827,12 @@ mod tests { for &(ref k, ref v) in r.iter() { // don't check android RANDOM variables if *k != "RANDOM".to_strbuf() { - assert!(output.contains(format!("{}={}", + assert!(output.as_slice() + .contains(format!("{}={}", *k, *v).as_slice()) || - output.contains(format!("{}=\'{}\'", + output.as_slice() + .contains(format!("{}=\'{}\'", *k, *v).as_slice())); } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 349f50b8ac7..493dd86b276 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -41,7 +41,7 @@ use path::{Path, GenericPath}; use ptr::RawPtr; use ptr; use result::{Err, Ok, Result}; -use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector}; +use slice::{Vector, ImmutableVector, MutableVector, OwnedVector}; use str::{Str, StrSlice, StrAllocating}; use str; use strbuf::StrBuf; @@ -104,6 +104,7 @@ pub mod win32 { use option; use os::TMPBUF_SZ; use slice::{MutableVector, ImmutableVector}; + use strbuf::StrBuf; use str::{StrSlice, StrAllocating}; use str; use vec::Vec; @@ -177,18 +178,18 @@ fn with_env_lock(f: || -> T) -> T { /// for details. pub fn env() -> Vec<(StrBuf,StrBuf)> { env_as_bytes().move_iter().map(|(k,v)| { - let k = str::from_utf8_lossy(k).to_strbuf(); - let v = str::from_utf8_lossy(v).to_strbuf(); + let k = str::from_utf8_lossy(k.as_slice()).to_strbuf(); + let v = str::from_utf8_lossy(v.as_slice()).to_strbuf(); (k,v) }).collect() } /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. -pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { +pub fn env_as_bytes() -> Vec<(Vec,Vec)> { unsafe { #[cfg(windows)] - unsafe fn get_env_pairs() -> Vec<~[u8]> { + unsafe fn get_env_pairs() -> Vec> { use slice::raw; use libc::funcs::extra::kernel32::{ @@ -228,7 +229,7 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { result } #[cfg(unix)] - unsafe fn get_env_pairs() -> Vec<~[u8]> { + unsafe fn get_env_pairs() -> Vec> { use c_str::CString; extern { @@ -241,18 +242,19 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { } let mut result = Vec::new(); ptr::array_each(environ, |e| { - let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned(); + let env_pair = + Vec::from_slice(CString::new(e, false).as_bytes_no_nul()); result.push(env_pair); }); result } - fn env_convert(input: Vec<~[u8]>) -> Vec<(~[u8], ~[u8])> { + fn env_convert(input: Vec>) -> Vec<(Vec, Vec)> { let mut pairs = Vec::new(); for p in input.iter() { - let mut it = p.splitn(1, |b| *b == '=' as u8); - let key = it.next().unwrap().to_owned(); - let val = it.next().unwrap_or(&[]).to_owned(); + let mut it = p.as_slice().splitn(1, |b| *b == '=' as u8); + let key = Vec::from_slice(it.next().unwrap()); + let val = Vec::from_slice(it.next().unwrap_or(&[])); pairs.push((key, val)); } pairs @@ -275,7 +277,7 @@ pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> { /// /// Fails if `n` has any interior NULs. pub fn getenv(n: &str) -> Option { - getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v).to_strbuf()) + getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_strbuf()) } #[cfg(unix)] @@ -285,7 +287,7 @@ pub fn getenv(n: &str) -> Option { /// # Failure /// /// Fails if `n` has any interior NULs. -pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { +pub fn getenv_as_bytes(n: &str) -> Option> { use c_str::CString; unsafe { @@ -294,7 +296,8 @@ pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { if s.is_null() { None } else { - Some(CString::new(s, false).as_bytes_no_nul().to_owned()) + Some(Vec::from_slice(CString::new(s, + false).as_bytes_no_nul())) } }) } @@ -319,7 +322,7 @@ pub fn getenv(n: &str) -> Option { #[cfg(windows)] /// Fetches the environment variable `n` byte vector from the current process, /// returning None if the variable isn't set. -pub fn getenv_as_bytes(n: &str) -> Option<~[u8]> { +pub fn getenv_as_bytes(n: &str) -> Option> { getenv(n).map(|s| s.into_bytes()) } @@ -528,7 +531,7 @@ pub fn self_exe_path() -> Option { * Otherwise, homedir returns option::none. */ pub fn homedir() -> Option { - // FIXME (#7188): getenv needs a ~[u8] variant + // FIXME (#7188): getenv needs a Vec variant return match getenv("HOME") { Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()), _ => secondary() @@ -817,11 +820,12 @@ pub fn get_exit_status() -> int { } #[cfg(target_os = "macos")] -unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<~[u8]> { +unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec> { use c_str::CString; Vec::from_fn(argc as uint, |i| { - CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned() + Vec::from_slice(CString::new(*argv.offset(i as int), + false).as_bytes_no_nul()) }) } @@ -831,7 +835,7 @@ unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<~[u8]> { * Returns a list of the command line arguments. */ #[cfg(target_os = "macos")] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec> { unsafe { let (argc, argv) = (*_NSGetArgc() as int, *_NSGetArgv() as **c_char); @@ -842,7 +846,7 @@ fn real_args_as_bytes() -> Vec<~[u8]> { #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "freebsd")] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec> { use rt; match rt::args::clone() { @@ -854,8 +858,9 @@ fn real_args_as_bytes() -> Vec<~[u8]> { #[cfg(not(windows))] fn real_args() -> Vec { real_args_as_bytes().move_iter() - .map(|v| str::from_utf8_lossy(v).into_strbuf()) - .collect() + .map(|v| { + str::from_utf8_lossy(v.as_slice()).into_strbuf() + }).collect() } #[cfg(windows)] @@ -889,7 +894,7 @@ fn real_args() -> Vec { } #[cfg(windows)] -fn real_args_as_bytes() -> Vec<~[u8]> { +fn real_args_as_bytes() -> Vec> { real_args().move_iter().map(|s| s.into_bytes()).collect() } @@ -926,7 +931,7 @@ pub fn args() -> ::realstd::vec::Vec<::realstd::strbuf::StrBuf> { /// Returns the arguments which this program was started with (normally passed /// via the command line) as byte vectors. -pub fn args_as_bytes() -> Vec<~[u8]> { +pub fn args_as_bytes() -> Vec> { real_args_as_bytes() } @@ -1680,8 +1685,12 @@ mod tests { setenv("USERPROFILE", "/home/PaloAlto"); assert!(os::homedir() == Some(Path::new("/home/MountainView"))); - for s in oldhome.iter() { setenv("HOME", *s) } - for s in olduserprofile.iter() { setenv("USERPROFILE", *s) } + for s in oldhome.iter() { + setenv("HOME", s.as_slice()) + } + for s in olduserprofile.iter() { + setenv("USERPROFILE", s.as_slice()) + } } #[test] diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index 95d0eabd336..cde20521c2f 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -37,8 +37,8 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) } #[cfg(test)] pub unsafe fn cleanup() { realargs::cleanup() } /// Take the global arguments from global storage. -#[cfg(not(test))] pub fn take() -> Option> { imp::take() } -#[cfg(test)] pub fn take() -> Option> { +#[cfg(not(test))] pub fn take() -> Option>> { imp::take() } +#[cfg(test)] pub fn take() -> Option>> { match realargs::take() { realstd::option::Some(v) => Some(unsafe{ ::mem::transmute(v) }), realstd::option::None => None, @@ -48,12 +48,16 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) } /// Give the global arguments to global storage. /// /// It is an error if the arguments already exist. -#[cfg(not(test))] pub fn put(args: Vec<~[u8]>) { imp::put(args) } -#[cfg(test)] pub fn put(args: Vec<~[u8]>) { realargs::put(unsafe { ::mem::transmute(args) }) } +#[cfg(not(test))] pub fn put(args: Vec>) { imp::put(args) } +#[cfg(test)] pub fn put(args: Vec>) { + realargs::put(unsafe { + ::mem::transmute(args) + }) +} /// Make a clone of the global arguments. -#[cfg(not(test))] pub fn clone() -> Option> { imp::clone() } -#[cfg(test)] pub fn clone() -> Option> { +#[cfg(not(test))] pub fn clone() -> Option>> { imp::clone() } +#[cfg(test)] pub fn clone() -> Option>> { match realargs::clone() { realstd::option::Some(v) => Some(unsafe { ::mem::transmute(v) }), realstd::option::None => None, @@ -88,15 +92,15 @@ mod imp { lock.destroy(); } - pub fn take() -> Option> { + pub fn take() -> Option>> { with_lock(|| unsafe { let ptr = get_global_ptr(); let val = mem::replace(&mut *ptr, None); - val.as_ref().map(|s: &Box>| (**s).clone()) + val.as_ref().map(|s: &Box>>| (**s).clone()) }) } - pub fn put(args: Vec<~[u8]>) { + pub fn put(args: Vec>) { with_lock(|| unsafe { let ptr = get_global_ptr(); rtassert!((*ptr).is_none()); @@ -104,10 +108,10 @@ mod imp { }) } - pub fn clone() -> Option> { + pub fn clone() -> Option>> { with_lock(|| unsafe { let ptr = get_global_ptr(); - (*ptr).as_ref().map(|s: &Box>| (**s).clone()) + (*ptr).as_ref().map(|s: &Box>>| (**s).clone()) }) } @@ -118,22 +122,21 @@ mod imp { } } - fn get_global_ptr() -> *mut Option>> { + fn get_global_ptr() -> *mut Option>>> { unsafe { mem::transmute(&global_args_ptr) } } // Copied from `os`. #[cfg(not(test))] - unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<~[u8]> { + unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec> { use c_str::CString; use ptr::RawPtr; use libc; - use slice::CloneableVector; use vec::Vec; Vec::from_fn(argc as uint, |i| { let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false); - cs.as_bytes_no_nul().to_owned() + Vec::from_slice(cs.as_bytes_no_nul()) }) } @@ -148,7 +151,10 @@ mod imp { // Preserve the actual global state. let saved_value = take(); - let expected = vec![bytes!("happy").to_owned(), bytes!("today?").to_owned()]; + let expected = vec![ + Vec::from_slice(bytes!("happy")), + Vec::from_slice(bytes!("today?")), + ]; put(expected.clone()); assert!(clone() == Some(expected.clone())); @@ -179,15 +185,15 @@ mod imp { pub fn cleanup() { } - pub fn take() -> Option> { + pub fn take() -> Option>> { fail!() } - pub fn put(_args: Vec<~[u8]>) { + pub fn put(_args: Vec>) { fail!() } - pub fn clone() -> Option> { + pub fn clone() -> Option>> { fail!() } } diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 7aebb6e4796..1ab9ac1b11e 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -145,6 +145,7 @@ which at the time convulsed us with joy, yet which are now partly lost to my memory and partly incapable of presentation to others.", _ => "You've met with a terrible fate, haven't you?" }; + ::alloc::util::make_stdlib_link_work(); // see comments in liballoc rterrln!("{}", ""); rterrln!("{}", quote); rterrln!("{}", ""); diff --git a/src/libstd/str.rs b/src/libstd/str.rs index f406cc9532f..4ba711c4611 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -85,7 +85,7 @@ use vec::Vec; pub use core::str::{from_utf8, CharEq, Chars, CharOffsets, RevChars}; pub use core::str::{RevCharOffsets, Bytes, RevBytes, CharSplits, RevCharSplits}; pub use core::str::{CharSplitsN, Words, AnyLines, MatchIndices, StrSplits}; -pub use core::str::{eq_slice, eq, is_utf8, is_utf16, UTF16Items}; +pub use core::str::{eq_slice, is_utf8, is_utf16, UTF16Items}; pub use core::str::{UTF16Item, ScalarValue, LoneSurrogate, utf16_items}; pub use core::str::{truncate_utf16_at_nul, utf8_char_width, CharRange}; pub use core::str::{Str, StrSlice}; @@ -660,6 +660,7 @@ pub mod raw { use c_str::CString; use libc; use mem; + use raw::Slice; use strbuf::StrBuf; use vec::Vec; @@ -668,7 +669,12 @@ pub mod raw { /// Create a Rust string from a *u8 buffer of the given length pub unsafe fn from_buf_len(buf: *u8, len: uint) -> StrBuf { - StrBuf::from_raw_parts(len, len, mem::transmute(buf)) + let mut result = StrBuf::new(); + result.push_bytes(mem::transmute(Slice { + data: buf, + len: len, + })); + result } /// Create a Rust string from a null-terminated C string @@ -919,13 +925,6 @@ mod tests { use str::*; use strbuf::StrBuf; - #[test] - fn test_eq() { - assert!((eq(&"".to_owned(), &"".to_owned()))); - assert!((eq(&"foo".to_owned(), &"foo".to_owned()))); - assert!((!eq(&"foo".to_owned(), &"bar".to_owned()))); - } - #[test] fn test_eq_slice() { assert!((eq_slice("foobar".slice(0, 3), "foo"))); @@ -984,10 +983,10 @@ mod tests { #[test] fn test_collect() { let empty = "".to_owned(); - let s: StrBuf = empty.chars().collect(); + let s: StrBuf = empty.as_slice().chars().collect(); assert_eq!(empty, s); let data = "ประเทศไทย中".to_owned(); - let s: StrBuf = data.chars().collect(); + let s: StrBuf = data.as_slice().chars().collect(); assert_eq!(data, s); } @@ -1009,23 +1008,24 @@ mod tests { assert_eq!(data.slice(2u, 6u).find_str("ab"), Some(3u - 2u)); assert!(data.slice(2u, 4u).find_str("ab").is_none()); - let mut data = "ประเทศไทย中华Việt Nam".to_owned(); - data = data + data; - assert!(data.find_str("ไท华").is_none()); - assert_eq!(data.slice(0u, 43u).find_str(""), Some(0u)); - assert_eq!(data.slice(6u, 43u).find_str(""), Some(6u - 6u)); + let string = "ประเทศไทย中华Việt Nam"; + let mut data = string.to_strbuf(); + data.push_str(string); + assert!(data.as_slice().find_str("ไท华").is_none()); + assert_eq!(data.as_slice().slice(0u, 43u).find_str(""), Some(0u)); + assert_eq!(data.as_slice().slice(6u, 43u).find_str(""), Some(6u - 6u)); - assert_eq!(data.slice(0u, 43u).find_str("ประ"), Some( 0u)); - assert_eq!(data.slice(0u, 43u).find_str("ทศไ"), Some(12u)); - assert_eq!(data.slice(0u, 43u).find_str("ย中"), Some(24u)); - assert_eq!(data.slice(0u, 43u).find_str("iệt"), Some(34u)); - assert_eq!(data.slice(0u, 43u).find_str("Nam"), Some(40u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ประ"), Some( 0u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ทศไ"), Some(12u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("ย中"), Some(24u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("iệt"), Some(34u)); + assert_eq!(data.as_slice().slice(0u, 43u).find_str("Nam"), Some(40u)); - assert_eq!(data.slice(43u, 86u).find_str("ประ"), Some(43u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("ย中"), Some(67u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("iệt"), Some(77u - 43u)); - assert_eq!(data.slice(43u, 86u).find_str("Nam"), Some(83u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ประ"), Some(43u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("ย中"), Some(67u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("iệt"), Some(77u - 43u)); + assert_eq!(data.as_slice().slice(43u, 86u).find_str("Nam"), Some(83u - 43u)); } #[test] @@ -1122,7 +1122,9 @@ mod tests { } let letters = a_million_letter_a(); assert!(half_a_million_letter_a() == - unsafe {raw::slice_bytes(letters, 0u, 500000)}.to_owned()); + unsafe {raw::slice_bytes(letters.as_slice(), + 0u, + 500000)}.to_owned()); } #[test] @@ -1167,41 +1169,41 @@ mod tests { #[test] fn test_replace_2a() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let a = "ประเ".to_owned(); - let a2 = "دولة الكويتทศไทย中华".to_owned(); - assert_eq!(data.replace(a, repl), a2); + let a = "ประเ"; + let a2 = "دولة الكويتทศไทย中华"; + assert_eq!(data.replace(a, repl).as_slice(), a2); } #[test] fn test_replace_2b() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let b = "ะเ".to_owned(); - let b2 = "ปรدولة الكويتทศไทย中华".to_owned(); - assert_eq!(data.replace(b, repl), b2); + let b = "ะเ"; + let b2 = "ปรدولة الكويتทศไทย中华"; + assert_eq!(data.replace(b, repl).as_slice(), b2); } #[test] fn test_replace_2c() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let c = "中华".to_owned(); - let c2 = "ประเทศไทยدولة الكويت".to_owned(); - assert_eq!(data.replace(c, repl), c2); + let c = "中华"; + let c2 = "ประเทศไทยدولة الكويت"; + assert_eq!(data.replace(c, repl).as_slice(), c2); } #[test] fn test_replace_2d() { - let data = "ประเทศไทย中华".to_owned(); - let repl = "دولة الكويت".to_owned(); + let data = "ประเทศไทย中华"; + let repl = "دولة الكويت"; - let d = "ไท华".to_owned(); - assert_eq!(data.replace(d, repl), data); + let d = "ไท华"; + assert_eq!(data.replace(d, repl).as_slice(), data); } #[test] @@ -1237,7 +1239,7 @@ mod tests { } let letters = a_million_letter_X(); assert!(half_a_million_letter_X() == - letters.slice(0u, 3u * 500000u).to_owned()); + letters.as_slice().slice(0u, 3u * 500000u).to_owned()); } #[test] @@ -1533,14 +1535,14 @@ mod tests { let s1: StrBuf = "All mimsy were the borogoves".to_strbuf(); let v: Vec = Vec::from_slice(s1.as_bytes()); - let s2: StrBuf = from_utf8(v).unwrap().to_strbuf(); + let s2: StrBuf = from_utf8(v.as_slice()).unwrap().to_strbuf(); let mut i: uint = 0u; let n1: uint = s1.len(); let n2: uint = v.len(); assert_eq!(n1, n2); while i < n1 { - let a: u8 = s1[i]; - let b: u8 = s2[i]; + let a: u8 = s1.as_slice()[i]; + let b: u8 = s2.as_slice()[i]; debug!("{}", a); debug!("{}", b); assert_eq!(a, b); @@ -1558,7 +1560,7 @@ mod tests { assert!(!"abcde".contains("def")); assert!(!"".contains("a")); - let data = "ประเทศไทย中华Việt Nam".to_owned(); + let data = "ประเทศไทย中华Việt Nam"; assert!(data.contains("ประเ")); assert!(data.contains("ะเ")); assert!(data.contains("中华")); @@ -1678,7 +1680,7 @@ mod tests { #[test] fn test_char_at() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; for ch in v.iter() { @@ -1689,7 +1691,7 @@ mod tests { #[test] fn test_char_at_reverse() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = s.len(); for ch in v.iter().rev() { @@ -1734,7 +1736,7 @@ mod tests { #[test] fn test_char_range_at() { - let data = "b¢€𤭢𤭢€¢b".to_owned(); + let data = "b¢€𤭢𤭢€¢b"; assert_eq!('b', data.char_range_at(0).ch); assert_eq!('¢', data.char_range_at(1).ch); assert_eq!('€', data.char_range_at(3).ch); @@ -1750,29 +1752,10 @@ mod tests { assert_eq!("abc".char_range_at_reverse(0).next, 0); } - #[test] - fn test_add() { - #![allow(unnecessary_allocation)] - macro_rules! t ( - ($s1:expr, $s2:expr, $e:expr) => { { - let s1 = $s1; - let s2 = $s2; - let e = $e; - assert_eq!(s1 + s2, e.to_owned()); - assert_eq!(s1.to_owned() + s2, e.to_owned()); - } } - ); - - t!("foo", "bar", "foobar"); - t!("foo", "bar".to_owned(), "foobar"); - t!("ศไทย中", "华Việt Nam", "ศไทย中华Việt Nam"); - t!("ศไทย中", "华Việt Nam".to_owned(), "ศไทย中华Việt Nam"); - } - #[test] fn test_iterator() { use iter::*; - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; @@ -1788,7 +1771,7 @@ mod tests { #[test] fn test_rev_iterator() { use iter::*; - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = box ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ']; let mut pos = 0; @@ -1811,7 +1794,7 @@ mod tests { #[test] fn test_bytesator() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = [ 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, @@ -1827,7 +1810,7 @@ mod tests { #[test] fn test_bytes_revator() { - let s = "ศไทย中华Việt Nam".to_owned(); + let s = "ศไทย中华Việt Nam"; let v = [ 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, @@ -2081,14 +2064,15 @@ mod tests { #[test] fn test_str_from_utf8_owned() { - let xs = bytes!("hello").to_owned(); + let xs = Vec::from_slice(bytes!("hello")); assert_eq!(from_utf8_owned(xs), Ok("hello".to_owned())); - let xs = bytes!("ศไทย中华Việt Nam").to_owned(); + let xs = Vec::from_slice(bytes!("ศไทย中华Việt Nam")); assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_owned())); - let xs = bytes!("hello", 0xff).to_owned(); - assert_eq!(from_utf8_owned(xs), Err(bytes!("hello", 0xff).to_owned())); + let xs = Vec::from_slice(bytes!("hello", 0xff)); + assert_eq!(from_utf8_owned(xs), + Err(Vec::from_slice(bytes!("hello", 0xff)))); } #[test] diff --git a/src/libstd/strbuf.rs b/src/libstd/strbuf.rs index 8f5d8340526..dd462ff5ab5 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -14,6 +14,7 @@ use c_vec::CVec; use char::Char; use cmp::Equiv; use container::{Container, Mutable}; +use default::Default; use fmt; use from_str::FromStr; use io::Writer; @@ -331,6 +332,12 @@ impl StrAllocating for StrBuf { } } +impl Default for StrBuf { + fn default() -> StrBuf { + StrBuf::new() + } +} + impl fmt::Show for StrBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) diff --git a/src/libstd/unstable/dynamic_lib.rs b/src/libstd/unstable/dynamic_lib.rs index f73ebc2255b..8e85283ee55 100644 --- a/src/libstd/unstable/dynamic_lib.rs +++ b/src/libstd/unstable/dynamic_lib.rs @@ -119,7 +119,9 @@ impl DynamicLibrary { let mut ret = Vec::new(); match os::getenv_as_bytes(DynamicLibrary::envvar()) { Some(env) => { - for portion in env.split(|a| *a == DynamicLibrary::separator()) { + for portion in + env.as_slice() + .split(|a| *a == DynamicLibrary::separator()) { ret.push(Path::new(portion)); } } @@ -274,6 +276,7 @@ pub mod dl { use os; use ptr; use result::{Ok, Err, Result}; + use strbuf::StrBuf; use str; use c_str::ToCStr; diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index f9f5322625f..822084df2f6 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -107,7 +107,9 @@ pub fn expand_asm(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) (Some('+'), operand) => { // Save a reference to the output read_write_operands.push((outputs.len(), out)); - Some(token::intern_and_get_ident("=" + operand)) + Some(token::intern_and_get_ident(format!( + "={}", + operand).as_slice())) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 54308536ab2..ce1c7da585f 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -188,7 +188,9 @@ pub fn nameize(p_s: &ParseSess, ms: &[Matcher], res: &[Rc]) if ret_val.contains_key(&bind_name) { let string = token::get_ident(bind_name); p_s.span_diagnostic - .span_fatal(span, "duplicated bind name: " + string.get()) + .span_fatal(span, + format!("duplicated bind name: {}", + string.get()).as_slice()) } ret_val.insert(bind_name, res[idx].clone()); } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 7d0276ae16f..4897fed6928 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -4259,12 +4259,14 @@ impl<'a> Parser<'a> { self.span_note(id_sp, format!("maybe move this module `{0}` \ to its own directory via \ - `{0}/mod.rs`", this_module)); + `{0}/mod.rs`", + this_module).as_slice()); if default_exists || secondary_exists { self.span_note(id_sp, format!("... or maybe `use` the module \ `{}` instead of possibly \ - redeclaring it", mod_name)); + redeclaring it", + mod_name).as_slice()); } self.abort_if_errors(); } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 60cf7a67cbe..5500ca45753 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2252,7 +2252,10 @@ impl<'a> State<'a> { } ast::LitFloat(ref f, t) => { word(&mut self.s, - f.get() + ast_util::float_ty_to_str(t).as_slice()) + format!( + "{}{}", + f.get(), + ast_util::float_ty_to_str(t).as_slice()).as_slice()) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitNil => word(&mut self.s, "()"), diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 80517328c26..1f10956b380 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -623,7 +623,9 @@ impl ConsoleTestState { fail_out.push_str(format!("---- {} stdout ----\n\t", f.name.as_slice()).as_slice()); let output = str::from_utf8_lossy(stdout.as_slice()); - fail_out.push_str(output.as_slice().replace("\n", "\n\t")); + fail_out.push_str(output.as_slice() + .replace("\n", "\n\t") + .as_slice()); fail_out.push_str("\n"); } } @@ -776,7 +778,9 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec ) -> io::IoR let MetricMap(mm) = mm; for (k,v) in mm.iter() { st.metrics - .insert_metric(tname + "." + k.as_slice(), + .insert_metric(format!("{}.{}", + tname, + k).as_slice(), v.value, v.noise); } diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index b7dc585fc26..8f47a7ce2cb 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -1432,13 +1432,6 @@ mod tests { assert_eq!(local.strftime("%z"), "-0800".to_strbuf()); assert_eq!(local.strftime("%%"), "%".to_strbuf()); - // FIXME (#2350): We should probably standardize on the timezone - // abbreviation. - let rfc822 = local.rfc822(); - let prefix = "Fri, 13 Feb 2009 15:31:30 ".to_strbuf(); - assert!(rfc822 == format_strbuf!("{}PST", prefix) || - rfc822 == format_strbuf!("{}Pacific Standard Time", prefix)); - assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_strbuf()); assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_strbuf()); assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_strbuf()); diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index b546935939f..de9d6ef7c89 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -426,14 +426,16 @@ impl Uuid { // At this point, we know we have a valid hex string, without hyphens assert!(vs.len() == 32); - assert!(vs.chars().all(|c| c.is_digit_radix(16))); + assert!(vs.as_slice().chars().all(|c| c.is_digit_radix(16))); // Allocate output UUID buffer let mut ub = [0u8, ..16]; // Extract each hex digit from the string for i in range(0u, 16u) { - ub[i] = FromStrRadix::from_str_radix(vs.slice(i*2, (i+1)*2), 16).unwrap(); + ub[i] = FromStrRadix::from_str_radix(vs.as_slice() + .slice(i*2, (i+1)*2), + 16).unwrap(); } Ok(Uuid::from_bytes(ub).unwrap()) @@ -624,7 +626,7 @@ mod test { // Round-trip let uuid_orig = Uuid::new_v4(); let orig_str = uuid_orig.to_str(); - let uuid_out = Uuid::parse_string(orig_str).unwrap(); + let uuid_out = Uuid::parse_string(orig_str.as_slice()).unwrap(); assert!(uuid_orig == uuid_out); // Test error reporting @@ -706,7 +708,7 @@ mod test { assert!(uuid_hs == uuid); let ss = uuid.to_str(); - let uuid_ss = Uuid::parse_string(ss).unwrap(); + let uuid_ss = Uuid::parse_string(ss.as_slice()).unwrap(); assert!(uuid_ss == uuid); } diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index 6a8a56b4f1f..d7acd82092f 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -93,7 +93,7 @@ fn main() { let args = args.as_slice(); let n_keys = { if args.len() == 2 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 1000000 } diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 757d61f2857..ffc2fdffba4 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -158,7 +158,7 @@ fn main() { let args = args.as_slice(); let num_keys = { if args.len() == 2 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 100 // woefully inadequate for any real measurement } diff --git a/src/test/bench/core-uint-to-str.rs b/src/test/bench/core-uint-to-str.rs index d954b0c12e3..381527763c9 100644 --- a/src/test/bench/core-uint-to-str.rs +++ b/src/test/bench/core-uint-to-str.rs @@ -21,7 +21,7 @@ fn main() { args.move_iter().collect() }; - let n = from_str::(*args.get(1)).unwrap(); + let n = from_str::(args.get(1).as_slice()).unwrap(); for i in range(0u, n) { let x = i.to_str(); diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 2779ec06e9f..633ac6ebcdf 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -70,8 +70,8 @@ fn main() { args.clone().move_iter().collect() }; - let num_tasks = from_str::(*args.get(1)).unwrap(); - let msg_per_task = from_str::(*args.get(2)).unwrap(); + let num_tasks = from_str::(args.get(1).as_slice()).unwrap(); + let msg_per_task = from_str::(args.get(2).as_slice()).unwrap(); let (mut num_chan, num_port) = init(); diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index 70b31017223..a324f10fb33 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -71,8 +71,8 @@ fn main() { args.clone().move_iter().collect() }; - let num_tasks = from_str::(*args.get(1)).unwrap(); - let msg_per_task = from_str::(*args.get(2)).unwrap(); + let num_tasks = from_str::(args.get(1).as_slice()).unwrap(); + let msg_per_task = from_str::(args.get(2).as_slice()).unwrap(); let (mut num_chan, num_port) = init(); diff --git a/src/test/bench/rt-messaging-ping-pong.rs b/src/test/bench/rt-messaging-ping-pong.rs index bbe6b6c23f0..34e0742b632 100644 --- a/src/test/bench/rt-messaging-ping-pong.rs +++ b/src/test/bench/rt-messaging-ping-pong.rs @@ -63,13 +63,13 @@ fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() == 3 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 10000 }; let m = if args.len() == 3 { - from_str::(args[2]).unwrap() + from_str::(args[2].as_slice()).unwrap() } else { 4 }; diff --git a/src/test/bench/rt-parfib.rs b/src/test/bench/rt-parfib.rs index 29cee668389..4072dc0064a 100644 --- a/src/test/bench/rt-parfib.rs +++ b/src/test/bench/rt-parfib.rs @@ -33,7 +33,7 @@ fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() == 2 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 10 }; diff --git a/src/test/bench/rt-spawn-rate.rs b/src/test/bench/rt-spawn-rate.rs index 48d4a41c1a3..a091c6be9f8 100644 --- a/src/test/bench/rt-spawn-rate.rs +++ b/src/test/bench/rt-spawn-rate.rs @@ -30,7 +30,7 @@ fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() == 2 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 100000 }; diff --git a/src/test/bench/shootout-ackermann.rs b/src/test/bench/shootout-ackermann.rs index 46ea188a271..e0116931538 100644 --- a/src/test/bench/shootout-ackermann.rs +++ b/src/test/bench/shootout-ackermann.rs @@ -31,6 +31,6 @@ fn main() { } else { args.move_iter().collect() }; - let n = from_str::(*args.get(1)).unwrap(); + let n = from_str::(args.get(1).as_slice()).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); } diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 181d19ade3a..eab8b66b90d 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -46,7 +46,7 @@ fn main() { } else if args.len() <= 1u { 8 } else { - from_str(args[1]).unwrap() + from_str(args[1].as_slice()).unwrap() }; let min_depth = 4; let max_depth = if min_depth + 2 > n {min_depth + 2} else {n}; diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index f0bc0204fd2..181fe29c891 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -48,7 +48,7 @@ fn show_color_list(set: Vec) -> StrBuf { let mut out = StrBuf::new(); for col in set.iter() { out.push_char(' '); - out.push_str(col.to_str()); + out.push_str(col.to_str().as_slice()); } out } @@ -198,7 +198,10 @@ fn main() { let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { - std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(600) + std::os::args().as_slice() + .get(1) + .and_then(|arg| from_str(arg.as_slice())) + .unwrap_or(600) }; print_complements(); diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 3525b90d3f6..9cc8f2f23ff 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -53,7 +53,10 @@ fn fannkuch(n: uint, i: uint) -> (int, int) { } fn main() { - let n = std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(2u); + let n = std::os::args().as_slice() + .get(1) + .and_then(|arg| from_str(arg.as_slice())) + .unwrap_or(2u); let (tx, rx) = channel(); for i in range(0, n) { diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index 3f8d3275b64..adec9d31afe 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -179,7 +179,7 @@ fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() > 1 { - from_str::(args[1]).unwrap() + from_str::(args[1].as_slice()).unwrap() } else { 5 }; diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index c526ef54caf..4126fda00bc 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -80,7 +80,7 @@ fn run(writer: &mut W) { } else if args.len() <= 1u { 1000 } else { - from_str(args[1]).unwrap() + from_str(args[1].as_slice()).unwrap() }; let rng = &mut MyRandom::new(); diff --git a/src/test/bench/shootout-fibo.rs b/src/test/bench/shootout-fibo.rs index a453ddccde5..76f96f8d43b 100644 --- a/src/test/bench/shootout-fibo.rs +++ b/src/test/bench/shootout-fibo.rs @@ -27,6 +27,6 @@ fn main() { } else { args.move_iter().collect() }; - let n = from_str::(*args.get(1)).unwrap(); + let n = from_str::(args.get(1).as_slice()).unwrap(); println!("{}\n", fib(n)); } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 250562a095e..6f8c44f4bdf 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -64,7 +64,7 @@ fn sort_and_fmt(mm: &HashMap , uint>, total: uint) -> StrBuf { k.as_slice() .to_ascii() .to_upper() - .into_str(), v)); + .into_str(), v).as_slice()); } return buffer @@ -179,15 +179,15 @@ fn main() { let mut proc_mode = false; for line in rdr.lines() { - let line = line.unwrap().trim().to_owned(); + let line = line.unwrap().as_slice().trim().to_owned(); if line.len() == 0u { continue; } - match (line[0] as char, proc_mode) { + match (line.as_slice()[0] as char, proc_mode) { // start processing if this is the one ('>', false) => { - match line.slice_from(1).find_str("THREE") { + match line.as_slice().slice_from(1).find_str("THREE") { option::Some(_) => { proc_mode = true; } option::None => { } } diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 1434838e59b..e46f27a9f41 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -252,9 +252,9 @@ fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) { fn get_sequence(r: &mut R, key: &str) -> Vec { let mut res = Vec::new(); for l in r.lines().map(|l| l.ok().unwrap()) - .skip_while(|l| key != l.slice_to(key.len())).skip(1) + .skip_while(|l| key != l.as_slice().slice_to(key.len())).skip(1) { - res.push_all(l.trim().as_bytes()); + res.push_all(l.as_slice().trim().as_bytes()); } for b in res.mut_iter() { *b = b.to_ascii().to_upper().to_byte(); diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index debd12874da..6b3079b8fc8 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -169,7 +169,7 @@ fn main() { which interferes with the test runner."); mandelbrot(1000, io::util::NullWriter) } else { - mandelbrot(from_str(args[1]).unwrap(), io::stdout()) + mandelbrot(from_str(args[1].as_slice()).unwrap(), io::stdout()) }; res.unwrap(); } diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index f9a84f276bf..5a077b37747 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -141,7 +141,7 @@ fn main() { 5000000 } else { std::os::args().as_slice().get(1) - .and_then(|arg| from_str(*arg)) + .and_then(|arg| from_str(arg.as_slice())) .unwrap_or(1000) }; let mut bodies = BODIES; diff --git a/src/test/bench/shootout-pidigits.rs b/src/test/bench/shootout-pidigits.rs index 49356e6e645..8b522f362b3 100644 --- a/src/test/bench/shootout-pidigits.rs +++ b/src/test/bench/shootout-pidigits.rs @@ -92,7 +92,7 @@ fn main() { let n = if args.len() < 2 { 512 } else { - FromStr::from_str(args[1]).unwrap() + FromStr::from_str(args[1].as_slice()).unwrap() }; pidigits(n); } diff --git a/src/test/bench/shootout-regex-dna.rs b/src/test/bench/shootout-regex-dna.rs index f5409688bc6..002eaf2bbf9 100644 --- a/src/test/bench/shootout-regex-dna.rs +++ b/src/test/bench/shootout-regex-dna.rs @@ -38,7 +38,7 @@ fn main() { } else { box io::stdin() as Box }; - let mut seq = StrBuf::from_str(rdr.read_to_str().unwrap()); + let mut seq = rdr.read_to_str().unwrap(); let ilen = seq.len(); seq = regex!(">[^\n]*\n|\n").replace_all(seq.as_slice(), NoExpand("")); diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index 70a0e7a957c..c6a678828c1 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -100,7 +100,7 @@ fn main() { } else if args.len() < 2 { 2000 } else { - FromStr::from_str(args[1]).unwrap() + FromStr::from_str(args[1].as_slice()).unwrap() }; let u = Arc::new(RWLock::new(Vec::from_elem(n, 1.))); let v = Arc::new(RWLock::new(Vec::from_elem(n, 1.))); diff --git a/src/test/bench/shootout-threadring.rs b/src/test/bench/shootout-threadring.rs index 60485f40ba4..1a6582927ca 100644 --- a/src/test/bench/shootout-threadring.rs +++ b/src/test/bench/shootout-threadring.rs @@ -39,9 +39,11 @@ fn main() { let token = if std::os::getenv("RUST_BENCH").is_some() { 2000000 } else { - args.get(1).and_then(|arg| from_str(*arg)).unwrap_or(1000) + args.get(1).and_then(|arg| from_str(arg.as_slice())).unwrap_or(1000) }; - let n_tasks = args.get(2).and_then(|arg| from_str(*arg)).unwrap_or(503); + let n_tasks = args.get(2) + .and_then(|arg| from_str(arg.as_slice())) + .unwrap_or(503); start(n_tasks, token); } diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index ae1d9db8982..3b26de9cf47 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -38,8 +38,8 @@ fn main() { } else { args.move_iter().collect() }; - let max = from_str::(*args.get(1)).unwrap(); - let rep = from_str::(*args.get(2)).unwrap(); + let max = from_str::(args.get(1).as_slice()).unwrap(); + let rep = from_str::(args.get(2).as_slice()).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 58568282e15..0485e10a38b 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -72,7 +72,10 @@ impl Sudoku { let mut g = Vec::from_fn(10u, { |_i| vec!(0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8) }); for line in reader.lines() { let line = line.unwrap(); - let comps: Vec<&str> = line.trim().split(',').collect(); + let comps: Vec<&str> = line.as_slice() + .trim() + .split(',') + .collect(); if comps.len() == 3u { let row = from_str::(*comps.get(0)).unwrap() as u8; diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index 442386e3058..1669f41374d 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -49,7 +49,7 @@ fn main() { }; let (tx, rx) = channel(); - child_generation(from_str::(*args.get(1)).unwrap(), tx); + child_generation(from_str::(args.get(1).as_slice()).unwrap(), tx); if rx.recv_opt().is_err() { fail!("it happened when we slumbered"); } diff --git a/src/test/bench/task-perf-spawnalot.rs b/src/test/bench/task-perf-spawnalot.rs index e64b807ca3a..cb5eb77df6c 100644 --- a/src/test/bench/task-perf-spawnalot.rs +++ b/src/test/bench/task-perf-spawnalot.rs @@ -31,7 +31,7 @@ fn main() { } else { args.move_iter().collect() }; - let n = from_str::(*args.get(1)).unwrap(); + let n = from_str::(args.get(1).as_slice()).unwrap(); let mut i = 0u; while i < n { task::spawn(proc() f(n) ); i += 1u; } } diff --git a/src/test/compile-fail/closure-reform-bad.rs b/src/test/compile-fail/closure-reform-bad.rs index a5168c46045..1e1889c7339 100644 --- a/src/test/compile-fail/closure-reform-bad.rs +++ b/src/test/compile-fail/closure-reform-bad.rs @@ -17,7 +17,7 @@ fn call_bare(f: fn(&str)) { fn main() { let string = "world!"; - let f: |&str| = |s| println!("{}", s + string); + let f: |&str| = |s| println!("{}{}", s, string); call_bare(f) //~ ERROR mismatched types } diff --git a/src/test/compile-fail/lint-heap-memory.rs b/src/test/compile-fail/lint-heap-memory.rs index eaa1819bd53..ae18e9bebad 100644 --- a/src/test/compile-fail/lint-heap-memory.rs +++ b/src/test/compile-fail/lint-heap-memory.rs @@ -27,6 +27,5 @@ fn main() { box 2; //~ ERROR type uses owned fn g(_: Box) {} //~ ERROR type uses owned - "".to_owned(); //~ ERROR type uses owned proc() {}; //~ ERROR type uses owned } diff --git a/src/test/compile-fail/regions-glb-free-free.rs b/src/test/compile-fail/regions-glb-free-free.rs index d8a6391826b..1d8c4cec655 100644 --- a/src/test/compile-fail/regions-glb-free-free.rs +++ b/src/test/compile-fail/regions-glb-free-free.rs @@ -33,7 +33,7 @@ mod argparse { } fn main () { - let f : argparse::Flag = argparse::flag("flag".to_owned(), "My flag".to_owned()); - let updated_flag = f.set_desc("My new flag".to_owned()); - assert_eq!(updated_flag.desc, "My new flag"); + let f : argparse::Flag = argparse::flag("flag", "My flag"); + let updated_flag = f.set_desc("My new flag"); + assert_eq!(updated_flag.desc.as_slice(), "My new flag"); } diff --git a/src/test/compile-fail/trait-coercion-generic-regions.rs b/src/test/compile-fail/trait-coercion-generic-regions.rs index 04239de2a83..cf7a5c4ad14 100644 --- a/src/test/compile-fail/trait-coercion-generic-regions.rs +++ b/src/test/compile-fail/trait-coercion-generic-regions.rs @@ -25,7 +25,7 @@ impl Trait<&'static str> for Struct { fn main() { let person = "Fred".to_owned(); - let person: &str = person; //~ ERROR `person[..]` does not live long enough + let person: &str = person.as_slice(); //~ ERROR `person` does not live long enough let s: Box> = box Struct { person: person }; } diff --git a/src/test/compile-fail/unsafe-modifying-str.rs b/src/test/compile-fail/unsafe-modifying-str.rs deleted file mode 100644 index 1adf88c80be..00000000000 --- a/src/test/compile-fail/unsafe-modifying-str.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let mut s = "test".to_owned(); - s[0] = 3; //~ ERROR: not allowed - s[0] += 3; //~ ERROR: not allowed - { - let _a = &mut s[0]; //~ ERROR: not allowed - } -} diff --git a/src/test/pretty/match-naked-expr-long.rs b/src/test/pretty/match-naked-expr-long.rs deleted file mode 100644 index 994a81dc486..00000000000 --- a/src/test/pretty/match-naked-expr-long.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// pp-exact - -// actually this doesn't quite look how I want it to, but I can't -// get the prettyprinter to indent the long expr - -fn main() { - let x = Some(3); - let _y = - match x { - Some(_) => - "some".to_owned() + "very" + "very" + "very" + "very" + "very" + - "very" + "very" + "very" + "long" + "string", - None => "none".to_owned() - }; -} diff --git a/src/test/run-fail/issue-3029.rs b/src/test/run-fail/issue-3029.rs index b3b1fd2082b..a57f4683df3 100644 --- a/src/test/run-fail/issue-3029.rs +++ b/src/test/run-fail/issue-3029.rs @@ -19,5 +19,4 @@ fn main() { let y = vec!(3); fail!("so long"); x.push_all_move(y); - "good".to_owned() + "bye".to_owned(); } diff --git a/src/test/run-make/unicode-input/multiple_files.rs b/src/test/run-make/unicode-input/multiple_files.rs index 219eb1a3ebd..e41c5d1b626 100644 --- a/src/test/run-make/unicode-input/multiple_files.rs +++ b/src/test/run-make/unicode-input/multiple_files.rs @@ -57,7 +57,11 @@ fn main() { // rustc is passed to us with --out-dir and -L etc., so we // can't exec it directly let result = Command::new("sh") - .arg("-c").arg(rustc + " " + main_file.as_str().unwrap()) + .arg("-c") + .arg(format!("{} {}", + rustc, + main_file.as_str() + .unwrap()).as_slice()) .output().unwrap(); let err = str::from_utf8_lossy(result.error.as_slice()); diff --git a/src/test/run-make/unicode-input/span_length.rs b/src/test/run-make/unicode-input/span_length.rs index 2bb89d76213..854ed94e20a 100644 --- a/src/test/run-make/unicode-input/span_length.rs +++ b/src/test/run-make/unicode-input/span_length.rs @@ -52,13 +52,17 @@ fn main() { // rustc is passed to us with --out-dir and -L etc., so we // can't exec it directly let result = Command::new("sh") - .arg("-c").arg(rustc + " " + main_file.as_str().unwrap()) + .arg("-c") + .arg(format!("{} {}", + rustc, + main_file.as_str() + .unwrap()).as_slice()) .output().unwrap(); let err = str::from_utf8_lossy(result.error.as_slice()); // the span should end the line (e.g no extra ~'s) - let expected_span = "^" + "~".repeat(n - 1) + "\n"; - assert!(err.as_slice().contains(expected_span)); + let expected_span = format!("^{}\n", "~".repeat(n - 1)); + assert!(err.as_slice().contains(expected_span.as_slice())); } } diff --git a/src/test/run-pass/auto-ref-slice-plus-ref.rs b/src/test/run-pass/auto-ref-slice-plus-ref.rs index 626f19b5108..f7b9732f12e 100644 --- a/src/test/run-pass/auto-ref-slice-plus-ref.rs +++ b/src/test/run-pass/auto-ref-slice-plus-ref.rs @@ -30,7 +30,6 @@ pub fn main() { (vec!(1)).as_slice().test_imm(); (&[1]).test_imm(); ("test").test_imm(); - ("test".to_owned()).test_imm(); ("test").test_imm(); // FIXME: Other types of mutable vecs don't currently exist diff --git a/src/test/run-pass/issue-3574.rs b/src/test/run-pass/issue-3574.rs index 85c56733777..e31f2ade125 100644 --- a/src/test/run-pass/issue-3574.rs +++ b/src/test/run-pass/issue-3574.rs @@ -8,21 +8,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![allow(unnecessary_allocation)] - // rustc --test match_borrowed_str.rs.rs && ./match_borrowed_str.rs -fn compare(x: &str, y: &str) -> bool -{ - match x - { +fn compare(x: &str, y: &str) -> bool { + match x { "foo" => y == "foo", _ => y == "bar", } } -pub fn main() -{ +pub fn main() { assert!(compare("foo", "foo")); - assert!(compare("foo".to_owned(), "foo".to_owned())); } diff --git a/src/test/run-pass/let-assignability.rs b/src/test/run-pass/let-assignability.rs index e89151fcd9d..477f3b2acaf 100644 --- a/src/test/run-pass/let-assignability.rs +++ b/src/test/run-pass/let-assignability.rs @@ -9,8 +9,8 @@ // except according to those terms. fn f() { - let a = "hello".to_owned(); - let b: &str = a; + let a = box 1; + let b: &int = a; println!("{}", b); } diff --git a/src/test/run-pass/let-destruct-ref.rs b/src/test/run-pass/let-destruct-ref.rs index 70ce2b93fc9..343780b2463 100644 --- a/src/test/run-pass/let-destruct-ref.rs +++ b/src/test/run-pass/let-destruct-ref.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let x = "hello".to_owned(); + let x = 3u; let ref y = x; - assert_eq!(x.slice(0, x.len()), y.slice(0, y.len())); + assert_eq!(x, *y); } diff --git a/src/test/run-pass/linear-for-loop.rs b/src/test/run-pass/linear-for-loop.rs index 9ae8cc893b1..2f8f16fb1ae 100644 --- a/src/test/run-pass/linear-for-loop.rs +++ b/src/test/run-pass/linear-for-loop.rs @@ -16,7 +16,7 @@ pub fn main() { assert_eq!(y, 6); let s = "hello there".to_owned(); let mut i: int = 0; - for c in s.bytes() { + for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { assert!((c == 'e' as u8)); } if i == 2 { assert!((c == 'l' as u8)); } diff --git a/src/test/run-pass/log-err-phi.rs b/src/test/run-pass/log-err-phi.rs index cf3131514db..2f2328faaca 100644 --- a/src/test/run-pass/log-err-phi.rs +++ b/src/test/run-pass/log-err-phi.rs @@ -10,4 +10,8 @@ -pub fn main() { if false { println!("{}", "foo".to_owned() + "bar"); } } +pub fn main() { + if false { + println!("{}", "foobar"); + } +} diff --git a/src/test/run-pass/option-ext.rs b/src/test/run-pass/option-ext.rs index 967ca621948..7a816f91335 100644 --- a/src/test/run-pass/option-ext.rs +++ b/src/test/run-pass/option-ext.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let thing = "{{ f }}".to_owned(); + let thing = "{{ f }}"; let f = thing.find_str("{{"); if f.is_none() { diff --git a/src/test/run-pass/regions-borrow-estr-uniq.rs b/src/test/run-pass/regions-borrow-estr-uniq.rs deleted file mode 100644 index 161e392520e..00000000000 --- a/src/test/run-pass/regions-borrow-estr-uniq.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn foo(x: &str) -> u8 { - x[0] -} - -pub fn main() { - let p = "hello".to_owned(); - let r = foo(p); - assert_eq!(r, 'h' as u8); - - let p = "hello".to_owned(); - let r = foo(p); - assert_eq!(r, 'h' as u8); -} diff --git a/src/test/run-pass/str-idx.rs b/src/test/run-pass/str-idx.rs index 7597b02e31b..d65eb6415bf 100644 --- a/src/test/run-pass/str-idx.rs +++ b/src/test/run-pass/str-idx.rs @@ -12,7 +12,7 @@ pub fn main() { let s = "hello".to_owned(); - let c: u8 = s[4]; + let c: u8 = s.as_slice()[4]; println!("{:?}", c); assert_eq!(c, 0x6f as u8); } diff --git a/src/test/run-pass/super-fast-paren-parsing.rs b/src/test/run-pass/super-fast-paren-parsing.rs index 1204efc29eb..26cc43bcfa0 100644 --- a/src/test/run-pass/super-fast-paren-parsing.rs +++ b/src/test/run-pass/super-fast-paren-parsing.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// exec-env:RUST_MIN_STACK=8000000 +// exec-env:RUST_MIN_STACK=16000000 // // Big stack is needed for pretty printing, a little sad... diff --git a/src/test/run-pass/syntax-extension-source-utils.rs b/src/test/run-pass/syntax-extension-source-utils.rs index 017b17d0e9c..9f58cbbff20 100644 --- a/src/test/run-pass/syntax-extension-source-utils.rs +++ b/src/test/run-pass/syntax-extension-source-utils.rs @@ -15,17 +15,19 @@ pub mod m1 { pub mod m2 { - pub fn where_am_i() -> StrBuf { (module_path!()).to_strbuf() } + pub fn where_am_i() -> StrBuf { + (module_path!()).to_strbuf() + } } } macro_rules! indirect_line( () => ( line!() ) ) pub fn main() { - assert_eq!(line!(), 25); + assert_eq!(line!(), 27); //assert!((col!() == 11)); - assert_eq!(indirect_line!(), 27); - assert!((file!().to_owned().ends_with("syntax-extension-source-utils.rs"))); + assert_eq!(indirect_line!(), 29); + assert!((file!().ends_with("syntax-extension-source-utils.rs"))); assert_eq!(stringify!((2*3) + 5).to_strbuf(), "( 2 * 3 ) + 5".to_strbuf()); assert!(include!("syntax-extension-source-utils-files/includeme.\ fragment").to_strbuf() diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index 47f21a0c60c..963121fff82 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -39,10 +39,10 @@ fn test_str() { let s0 = "test".to_owned(); tx.send(s0); let s1 = rx.recv(); - assert_eq!(s1[0], 't' as u8); - assert_eq!(s1[1], 'e' as u8); - assert_eq!(s1[2], 's' as u8); - assert_eq!(s1[3], 't' as u8); + assert_eq!(s1.as_slice()[0], 't' as u8); + assert_eq!(s1.as_slice()[1], 'e' as u8); + assert_eq!(s1.as_slice()[2], 's' as u8); + assert_eq!(s1.as_slice()[3], 't' as u8); } #[deriving(Show)] -- cgit 1.4.1-3-g733a5