assert!(!args.is_empty());
let argv0 = (*args.get(0)).clone();
let args_ = args.tail();
- if *args.get(1) == ~"-h" || *args.get(1) == ~"--help" {
+ if *args.get(1) == "-h".to_owned() || *args.get(1) == "--help".to_owned() {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message, groups.as_slice()));
println!("");
logv(c, format!("adb_test_dir: {}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}", config.adb_device_status));
match config.test_shard {
- None => logv(c, ~"test_shard: (all)"),
+ None => logv(c, "test_shard: (all)".to_owned()),
Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b))
}
logv(c, format!("verbose: {}", config.verbose));
}
pub fn opt_str2(maybestr: Option<~str>) -> ~str {
- match maybestr { None => ~"(none)", Some(s) => { s } }
+ match maybestr { None => "(none)".to_owned(), Some(s) => { s } }
}
pub fn str_mode(s: ~str) -> mode {
pub fn mode_str(mode: mode) -> ~str {
match mode {
- mode_compile_fail => ~"compile-fail",
- mode_run_fail => ~"run-fail",
- mode_run_pass => ~"run-pass",
- mode_pretty => ~"pretty",
- mode_debug_info => ~"debug-info",
- mode_codegen => ~"codegen",
+ mode_compile_fail => "compile-fail".to_owned(),
+ mode_run_fail => "run-fail".to_owned(),
+ mode_run_pass => "run-pass".to_owned(),
+ mode_pretty => "pretty".to_owned(),
+ mode_debug_info => "debug-info".to_owned(),
+ mode_codegen => "codegen".to_owned(),
}
}
pub fn run_tests(config: &config) {
- if config.target == ~"arm-linux-androideabi" {
+ if config.target == "arm-linux-androideabi".to_owned() {
match config.mode{
mode_debug_info => {
println!("arm-linux-androideabi debug-info \
// Pretty-printer does not work with .rc files yet
let valid_extensions =
match config.mode {
- mode_pretty => vec!(~".rs"),
- _ => vec!(~".rc", ~".rs")
+ mode_pretty => vec!(".rs".to_owned()),
+ _ => vec!(".rc".to_owned(), ".rs".to_owned())
};
- let invalid_prefixes = vec!(~".", ~"#", ~"~");
+ let invalid_prefixes = vec!(".".to_owned(), "#".to_owned(), "~".to_owned());
let name = testfile.filename_str().unwrap();
let mut valid = false;
fn parse_expected(line_num: uint, line: ~str) -> Vec<ExpectedError> {
let line = line.trim();
- let error_tag = ~"//~";
+ let error_tag = "//~".to_owned();
let mut idx;
match line.find_str(error_tag) {
None => return Vec::new(),
pub fn is_test_ignored(config: &config, testfile: &Path) -> bool {
fn ignore_target(config: &config) -> ~str {
- ~"ignore-" + util::get_os(config.target)
+ "ignore-".to_owned() + util::get_os(config.target)
}
fn ignore_stage(config: &config) -> ~str {
- ~"ignore-" + config.stage_id.split('-').next().unwrap()
+ "ignore-".to_owned() + config.stage_id.split('-').next().unwrap()
}
let val = iter_header(testfile, |ln| {
}
fn parse_error_pattern(line: &str) -> Option<~str> {
- parse_name_value_directive(line, ~"error-pattern")
+ parse_name_value_directive(line, "error-pattern".to_owned())
}
fn parse_aux_build(line: &str) -> Option<~str> {
- parse_name_value_directive(line, ~"aux-build")
+ parse_name_value_directive(line, "aux-build".to_owned())
}
fn parse_compile_flags(line: &str) -> Option<~str> {
- parse_name_value_directive(line, ~"compile-flags")
+ parse_name_value_directive(line, "compile-flags".to_owned())
}
fn parse_debugger_cmd(line: &str) -> Option<~str> {
- parse_name_value_directive(line, ~"debugger")
+ parse_name_value_directive(line, "debugger".to_owned())
}
fn parse_check_line(line: &str) -> Option<~str> {
- parse_name_value_directive(line, ~"check")
+ parse_name_value_directive(line, "check".to_owned())
}
fn parse_force_host(line: &str) -> bool {
}
fn parse_exec_env(line: &str) -> Option<(~str, ~str)> {
- parse_name_value_directive(line, ~"exec-env").map(|nv| {
+ parse_name_value_directive(line, "exec-env".to_owned()).map(|nv| {
// nv is either FOO or FOO=BAR
let mut strs: Vec<~str> = nv.splitn('=', 1).map(|s| s.to_owned()).collect();
match strs.len() {
- 1u => (strs.pop().unwrap(), ~""),
+ 1u => (strs.pop().unwrap(), "".to_owned()),
2u => {
let end = strs.pop().unwrap();
(strs.pop().unwrap(), end)
}
fn parse_pp_exact(line: &str, testfile: &Path) -> Option<Path> {
- match parse_name_value_directive(line, ~"pp-exact") {
+ match parse_name_value_directive(line, "pp-exact".to_owned()) {
Some(s) => Some(Path::new(s)),
None => {
if parse_name_directive(line, "pp-exact") {
(k, new_v)
}).collect();
if prog.ends_with("rustc.exe") {
- new_env.push((~"RUST_THREADS", ~"1"));
+ new_env.push(("RUST_THREADS".to_owned(), "1".to_owned()));
}
return new_env;
}
};
let prev = match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
Some(i) => env.remove(i).unwrap().val1(),
- None => ~"",
+ None => "".to_owned(),
};
env.push((var.to_owned(), if prev.is_empty() {
lib_path + ":" + aux_path
let proc_res = compile_test(config, props, testfile);
if proc_res.status.success() {
- fatal_ProcRes(~"compile-fail test compiled successfully!", &proc_res);
+ fatal_ProcRes("compile-fail test compiled successfully!".to_owned(), &proc_res);
}
check_correct_failure_status(&proc_res);
let expected_errors = errors::load_errors(testfile);
if !expected_errors.is_empty() {
if !props.error_patterns.is_empty() {
- fatal(~"both error pattern and expected errors specified");
+ fatal("both error pattern and expected errors specified".to_owned());
}
check_expected_errors(expected_errors, testfile, &proc_res);
} else {
let proc_res = compile_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"compilation failed!", &proc_res);
+ fatal_ProcRes("compilation failed!".to_owned(), &proc_res);
}
exec_compiled_test(config, props, testfile)
// The value our Makefile configures valgrind to return on failure
static VALGRIND_ERR: int = 100;
if proc_res.status.matches_exit_status(VALGRIND_ERR) {
- fatal_ProcRes(~"run-fail test isn't valgrind-clean!", &proc_res);
+ fatal_ProcRes("run-fail test isn't valgrind-clean!".to_owned(), &proc_res);
}
check_correct_failure_status(&proc_res);
let mut proc_res = compile_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"compilation failed!", &proc_res);
+ fatal_ProcRes("compilation failed!".to_owned(), &proc_res);
}
proc_res = exec_compiled_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"test run failed!", &proc_res);
+ fatal_ProcRes("test run failed!".to_owned(), &proc_res);
}
} else {
let proc_res = jit_test(config, props, testfile);
- if !proc_res.status.success() { fatal_ProcRes(~"jit failed!", &proc_res); }
+ if !proc_res.status.success() { fatal_ProcRes("jit failed!".to_owned(), &proc_res); }
}
}
fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
if props.pp_exact.is_some() {
- logv(config, ~"testing for exact pretty-printing");
- } else { logv(config, ~"testing for converging pretty-printing"); }
+ logv(config, "testing for exact pretty-printing".to_owned());
+ } else { logv(config, "testing for converging pretty-printing".to_owned()); }
let rounds =
match props.pp_exact { Some(_) => 1, None => 2 };
if props.pp_exact.is_some() {
// Now we have to care about line endings
- let cr = ~"\r";
+ let cr = "\r".to_owned();
actual = actual.replace(cr, "");
expected = expected.replace(cr, "");
}
let proc_res = typecheck_source(config, props, testfile, actual);
if !proc_res.status.success() {
- fatal_ProcRes(~"pretty-printed source does not typecheck", &proc_res);
+ fatal_ProcRes("pretty-printed source does not typecheck".to_owned(), &proc_res);
}
return;
}
fn make_pp_args(config: &config, _testfile: &Path) -> ProcArgs {
- let args = vec!(~"-", ~"--pretty", ~"normal",
- ~"--target=" + config.target);
+ let args = vec!("-".to_owned(), "--pretty".to_owned(), "normal".to_owned(),
+ "--target=".to_owned() + config.target);
// FIXME (#9639): This needs to handle non-utf8 paths
return ProcArgs {prog: config.rustc_path.as_str().unwrap().to_owned(), args: args};
}
fn compare_source(expected: &str, actual: &str) {
if expected != actual {
- error(~"pretty-printed source does not match expected source");
+ error("pretty-printed source does not match expected source".to_owned());
println!("\n\
expected:\n\
------------------------------------------\n\
config.target.as_slice()
};
// FIXME (#9639): This needs to handle non-utf8 paths
- let mut args = vec!(~"-",
- ~"--no-trans", ~"--crate-type=lib",
- ~"--target=" + target,
- ~"-L", config.build_base.as_str().unwrap().to_owned(),
- ~"-L",
+ let mut args = vec!("-".to_owned(),
+ "--no-trans".to_owned(), "--crate-type=lib".to_owned(),
+ "--target=".to_owned() + target,
+ "-L".to_owned(), config.build_base.as_str().unwrap().to_owned(),
+ "-L".to_owned(),
aux_dir.as_str().unwrap().to_owned());
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.push_all_move(split_maybe_args(&props.compile_flags));
// compile test file (it shoud have 'compile-flags:-g' in the header)
let mut proc_res = compile_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"compilation failed!", &proc_res);
+ fatal_ProcRes("compilation failed!".to_owned(), &proc_res);
}
let exe_file = make_exe_name(config, testfile);
cmds = cmds.replace("run","continue");
// write debugger script
- let script_str = [~"set charset UTF-8",
+ let script_str = ["set charset UTF-8".to_owned(),
format!("file {}",exe_file.as_str().unwrap().to_owned()),
- ~"target remote :5039",
+ "target remote :5039".to_owned(),
cmds,
- ~"quit"].connect("\n");
+ "quit".to_owned()].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config, testfile, script_str, "debugger.script");
procsrv::run("", config.adb_path,
- [~"push", exe_file.as_str().unwrap().to_owned(),
+ ["push".to_owned(), exe_file.as_str().unwrap().to_owned(),
config.adb_test_dir.clone()],
- vec!((~"",~"")), Some(~""))
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
procsrv::run("", config.adb_path,
- [~"forward", ~"tcp:5039", ~"tcp:5039"],
- vec!((~"",~"")), Some(~""))
+ ["forward".to_owned(), "tcp:5039".to_owned(), "tcp:5039".to_owned()],
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
let adb_arg = format!("export LD_LIBRARY_PATH={}; gdbserver :5039 {}/{}",
str::from_utf8(exe_file.filename().unwrap()).unwrap());
let mut process = procsrv::run_background("", config.adb_path,
- [~"shell",adb_arg.clone()],
- vec!((~"",~"")), Some(~""))
+ ["shell".to_owned(),adb_arg.clone()],
+ vec!(("".to_owned(),"".to_owned())),
+ Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
loop {
//waiting 1 second for gdbserver start
}
if tool_path.is_empty() {
- fatal(~"cannot found android cross path");
+ fatal("cannot found android cross path".to_owned());
}
let debugger_script = make_out_name(config, testfile, "debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
- let debugger_opts = vec!(~"-quiet", ~"-batch", ~"-nx",
+ let debugger_opts = vec!("-quiet".to_owned(), "-batch".to_owned(), "-nx".to_owned(),
"-command=" + debugger_script.as_str().unwrap().to_owned());
let gdb_path = tool_path.append("/bin/arm-linux-androideabi-gdb");
procsrv::run("",
gdb_path.as_slice(),
debugger_opts.as_slice(),
- vec!((~"",~"")),
+ vec!(("".to_owned(),"".to_owned())),
None)
.expect(format!("failed to exec `{}`", gdb_path));
let cmdline = {
_=> {
// write debugger script
- let script_str = [~"set charset UTF-8",
+ let script_str = ["set charset UTF-8".to_owned(),
cmds,
- ~"quit\n"].connect("\n");
+ "quit\n".to_owned()].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config, testfile, script_str, "debugger.script");
// run debugger script with gdb
#[cfg(windows)]
- fn debugger() -> ~str { ~"gdb.exe" }
+ fn debugger() -> ~str { "gdb.exe".to_owned() }
#[cfg(unix)]
- fn debugger() -> ~str { ~"gdb" }
+ fn debugger() -> ~str { "gdb".to_owned() }
let debugger_script = make_out_name(config, testfile, "debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
- let debugger_opts = vec!(~"-quiet", ~"-batch", ~"-nx",
+ let debugger_opts = vec!("-quiet".to_owned(), "-batch".to_owned(), "-nx".to_owned(),
"-command=" + debugger_script.as_str().unwrap().to_owned(),
exe_file.as_str().unwrap().to_owned());
proc_args = ProcArgs {prog: debugger(), args: debugger_opts};
}
if !proc_res.status.success() {
- fatal(~"gdb failed to execute");
+ fatal("gdb failed to execute".to_owned());
}
let num_check_lines = check_lines.len();
if num_check_lines > 0 {
}
// Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
- let options_to_remove = [~"-O", ~"-g", ~"--debuginfo"];
+ let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
let new_options = split_maybe_args(options).move_iter()
.filter(|x| !options_to_remove.contains(x))
.collect::<Vec<~str>>()
testfile: &Path,
proc_res: &ProcRes) {
if props.error_patterns.is_empty() {
- fatal(~"no error pattern specified in " + testfile.display().as_maybe_owned().as_slice());
+ fatal("no error pattern specified in ".to_owned() +
+ testfile.display().as_maybe_owned().as_slice());
}
if proc_res.status.success() {
- fatal(~"process did not return an error status");
+ fatal("process did not return an error status".to_owned());
}
let mut next_err_idx = 0u;
for pattern in missing_patterns.iter() {
error(format!("error pattern '{}' not found!", *pattern));
}
- fatal_ProcRes(~"multiple error patterns not found", proc_res);
+ fatal_ProcRes("multiple error patterns not found".to_owned(), proc_res);
}
}
expected_errors.len(), false);
if proc_res.status.success() {
- fatal(~"process did not return an error status");
+ fatal("process did not return an error status".to_owned());
}
let prefixes = expected_errors.iter().map(|ee| {
}
fn jit_test(config: &config, props: &TestProps, testfile: &Path) -> ProcRes {
- compile_test_(config, props, testfile, [~"--jit"])
+ compile_test_(config, props, testfile, ["--jit".to_owned()])
}
fn compile_test_(config: &config, props: &TestProps,
testfile: &Path, extra_args: &[~str]) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let link_args = vec!(~"-L", aux_dir.as_str().unwrap().to_owned());
+ let link_args = vec!("-L".to_owned(), aux_dir.as_str().unwrap().to_owned());
let args = make_compile_args(config,
props,
link_args.append(extra_args),
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let extra_link_args = vec!(~"-L", aux_dir.as_str().unwrap().to_owned());
+ let extra_link_args = vec!("-L".to_owned(), aux_dir.as_str().unwrap().to_owned());
for rel_ab in props.aux_builds.iter() {
let abs_ab = config.aux_base.join(rel_ab.as_slice());
let crate_type = if aux_props.no_prefer_dynamic {
Vec::new()
} else {
- vec!(~"--crate-type=dylib")
+ vec!("--crate-type=dylib".to_owned())
};
let aux_args =
make_compile_args(config,
};
// FIXME (#9639): This needs to handle non-utf8 paths
let mut args = vec!(testfile.as_str().unwrap().to_owned(),
- ~"-L", config.build_base.as_str().unwrap().to_owned(),
- ~"--target=" + target);
+ "-L".to_owned(), config.build_base.as_str().unwrap().to_owned(),
+ "--target=".to_owned() + target);
args.push_all(extras.as_slice());
if !props.no_prefer_dynamic {
- args.push(~"-C");
- args.push(~"prefer-dynamic");
+ args.push("-C".to_owned());
+ args.push("prefer-dynamic".to_owned());
}
let path = match xform_file {
- ThisFile(path) => { args.push(~"-o"); path }
- ThisDirectory(path) => { args.push(~"--out-dir"); path }
+ ThisFile(path) => { args.push("-o".to_owned()); path }
+ ThisDirectory(path) => { args.push("--out-dir".to_owned()); path }
};
args.push(path.as_str().unwrap().to_owned());
if props.force_host {
// copy to target
let copy_result = procsrv::run("", config.adb_path,
- [~"push", args.prog.clone(), config.adb_test_dir.clone()],
- vec!((~"",~"")), Some(~""))
+ ["push".to_owned(), args.prog.clone(), config.adb_test_dir.clone()],
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
if config.verbose {
let mut runargs = Vec::new();
// run test via adb_run_wrapper
- runargs.push(~"shell");
+ runargs.push("shell".to_owned());
for (key, val) in env.move_iter() {
runargs.push(format!("{}={}", key, val));
}
procsrv::run("",
config.adb_path,
runargs.as_slice(),
- vec!((~"",~"")), Some(~""))
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
// get exitcode of result
runargs = Vec::new();
- runargs.push(~"shell");
- runargs.push(~"cat");
+ runargs.push("shell".to_owned());
+ runargs.push("cat".to_owned());
runargs.push(format!("{}/{}.exitcode", config.adb_test_dir, prog_short));
let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
- procsrv::run("", config.adb_path, runargs.as_slice(), vec!((~"",~"")),
- Some(~""))
+ procsrv::run("", config.adb_path, runargs.as_slice(), vec!(("".to_owned(),"".to_owned())),
+ Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
let mut exitcode : int = 0;
// get stdout of result
runargs = Vec::new();
- runargs.push(~"shell");
- runargs.push(~"cat");
+ runargs.push("shell".to_owned());
+ runargs.push("cat".to_owned());
runargs.push(format!("{}/{}.stdout", config.adb_test_dir, prog_short));
let procsrv::Result{ out: stdout_out, err: _, status: _ } =
procsrv::run("",
config.adb_path,
runargs.as_slice(),
- vec!((~"",~"")), Some(~""))
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
// get stderr of result
runargs = Vec::new();
- runargs.push(~"shell");
- runargs.push(~"cat");
+ runargs.push("shell".to_owned());
+ runargs.push("cat".to_owned());
runargs.push(format!("{}/{}.stderr", config.adb_test_dir, prog_short));
let procsrv::Result{ out: stderr_out, err: _, status: _ } =
procsrv::run("",
config.adb_path,
runargs.as_slice(),
- vec!((~"",~"")), Some(~""))
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
dump_output(config, testfile, stdout_out, stderr_out);
if file.extension_str() == Some("so") {
// FIXME (#9639): This needs to handle non-utf8 paths
let copy_result = procsrv::run("", config.adb_path,
- [~"push", file.as_str().unwrap().to_owned(), config.adb_test_dir.clone()],
- vec!((~"",~"")), Some(~""))
+ ["push".to_owned(), file.as_str().unwrap().to_owned(), config.adb_test_dir.clone()],
+ vec!(("".to_owned(),"".to_owned())), Some("".to_owned()))
.expect(format!("failed to exec `{}`", config.adb_path));
if config.verbose {
testfile: &Path) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let link_args = vec!(~"-L", aux_dir.as_str().unwrap().to_owned());
- let llvm_args = vec!(~"--emit=obj", ~"--crate-type=lib", ~"-C", ~"save-temps");
+ let link_args = vec!("-L".to_owned(), aux_dir.as_str().unwrap().to_owned());
+ let llvm_args = vec!("--emit=obj".to_owned(), "--crate-type=lib".to_owned(),
+ "-C".to_owned(), "save-temps".to_owned());
let args = make_compile_args(config,
props,
link_args.append(llvm_args.as_slice()),
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
prog: config.clang_path.get_ref().as_str().unwrap().to_owned(),
- args: vec!(~"-c",
- ~"-emit-llvm",
- ~"-o", bitcodefile.as_str().unwrap().to_owned(),
+ args: vec!("-c".to_owned(),
+ "-emit-llvm".to_owned(),
+ "-o".to_owned(), bitcodefile.as_str().unwrap().to_owned(),
testcc.as_str().unwrap().to_owned() )
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None)
testfile: &Path, mm: &mut MetricMap) {
if config.llvm_bin_path.is_none() {
- fatal(~"missing --llvm-bin-path");
+ fatal("missing --llvm-bin-path".to_owned());
}
if config.clang_path.is_none() {
- fatal(~"missing --clang-path");
+ fatal("missing --clang-path".to_owned());
}
let mut proc_res = compile_test_and_save_bitcode(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"compilation failed!", &proc_res);
+ fatal_ProcRes("compilation failed!".to_owned(), &proc_res);
}
proc_res = extract_function_from_bitcode(config, props, "test", testfile, "");
if !proc_res.status.success() {
- fatal_ProcRes(~"extracting 'test' function failed", &proc_res);
+ fatal_ProcRes("extracting 'test' function failed".to_owned(), &proc_res);
}
proc_res = disassemble_extract(config, props, testfile, "");
if !proc_res.status.success() {
- fatal_ProcRes(~"disassembling extract failed", &proc_res);
+ fatal_ProcRes("disassembling extract failed".to_owned(), &proc_res);
}
let mut proc_res = compile_cc_with_clang_and_save_bitcode(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes(~"compilation failed!", &proc_res);
+ fatal_ProcRes("compilation failed!".to_owned(), &proc_res);
}
proc_res = extract_function_from_bitcode(config, props, "test", testfile, "clang");
if !proc_res.status.success() {
- fatal_ProcRes(~"extracting 'test' function failed", &proc_res);
+ fatal_ProcRes("extracting 'test' function failed".to_owned(), &proc_res);
}
proc_res = disassemble_extract(config, props, testfile, "clang");
if !proc_res.status.success() {
- fatal_ProcRes(~"disassembling extract failed", &proc_res);
+ fatal_ProcRes("disassembling extract failed".to_owned(), &proc_res);
}
let base = output_base_name(config, testfile);
}
#[cfg(target_os = "win32")]
-pub fn lib_path_env_var() -> ~str { ~"PATH" }
+pub fn lib_path_env_var() -> ~str { "PATH".to_owned() }
#[cfg(target_os = "win32")]
-pub fn path_div() -> ~str { ~";" }
+pub fn path_div() -> ~str { ";".to_owned() }
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
Door::<Open>(name)
}
-let _ = close(Door::<Open>(~"front"));
+let _ = close(Door::<Open>("front".to_owned()));
~~~
Attempting to close a closed door is prevented statically:
~~~ {.ignore}
-let _ = close(Door::<Closed>(~"front")); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
+let _ = close(Door::<Closed>("front".to_owned())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
~~~
# FFI (Foreign Function Interface)
});
from_child.send(22);
-assert!(from_child.recv() == ~"22");
+assert!(from_child.recv() == "22".to_owned());
from_child.send(23);
from_child.send(0);
-assert!(from_child.recv() == ~"23");
-assert!(from_child.recv() == ~"0");
+assert!(from_child.recv() == "23".to_owned());
+assert!(from_child.recv() == "0".to_owned());
# }
~~~~
Cat { name: ~str, weight: f64 }
}
-let mut a: Animal = Dog(~"Cocoa", 37.2);
-a = Cat{ name: ~"Spotty", weight: 2.7 };
+let mut a: Animal = Dog("Cocoa".to_owned(), 37.2);
+a = Cat{ name: "Spotty".to_owned(), weight: 2.7 };
~~~~
In this example, `Cat` is a _struct-like enum variant_,
procedure:
```rust
-let string = ~"Hello";
+let string = "Hello".to_owned();
// Creates a new procedure, passing it to the `spawn` function.
spawn(proc() {
}
# 1.print();
-# (~"foo").print();
+# ("foo".to_owned()).print();
~~~~
Methods defined in an impl for a trait may be called just like
impl Printable for f32 {}
# 1.print();
-# (~"foo").print();
+# ("foo".to_owned()).print();
# true.print();
# 3.14159.print();
~~~~
let arena = TypedArena::new();
for _ in range(0, 100000) {
arena.alloc(Noncopy {
- string: ~"hello world",
+ string: "hello world".to_owned(),
array: vec!( 1, 2, 3, 4, 5 ),
});
}
let arena = TypedArena::new();
b.iter(|| {
arena.alloc(Noncopy {
- string: ~"hello world",
+ string: "hello world".to_owned(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
pub fn bench_noncopy_nonarena(b: &mut Bencher) {
b.iter(|| {
~Noncopy {
- string: ~"hello world",
+ string: "hello world".to_owned(),
array: vec!( 1, 2, 3, 4, 5 ),
}
})
let arena = Arena::new();
b.iter(|| {
arena.alloc(|| Noncopy {
- string: ~"hello world",
+ string: "hello world".to_owned(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
#[test]
fn test_to_str() {
let zerolen = Bitv::new(0u, false);
- assert_eq!(zerolen.to_str(), ~"");
+ assert_eq!(zerolen.to_str(), "".to_owned());
let eightbits = Bitv::new(8u, false);
- assert_eq!(eightbits.to_str(), ~"00000000");
+ assert_eq!(eightbits.to_str(), "00000000".to_owned());
}
#[test]
let mut b = bitv::Bitv::new(2, false);
b.set(0, true);
b.set(1, false);
- assert_eq!(b.to_str(), ~"10");
+ assert_eq!(b.to_str(), "10".to_owned());
}
#[test]
#[test]
fn test_from_bytes() {
let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]);
- let str = ~"10110110" + "00000000" + "11111111";
+ let str = "10110110".to_owned() + "00000000" + "11111111";
assert_eq!(bitv.to_str(), str);
}
#[test]
fn test_from_bools() {
assert!(from_bools([true, false, true, true]).to_str() ==
- ~"1011");
+ "1011".to_owned());
}
#[test]
//Tests the functionality of the insert methods (which are unfinished).
#[test]
fn insert_test_one() {
- let b = BTree::new(1, ~"abc", 2);
- let is_insert = b.insert(2, ~"xyz");
+ let b = BTree::new(1, "abc".to_owned(), 2);
+ let is_insert = b.insert(2, "xyz".to_owned());
//println!("{}", is_insert.clone().to_str());
assert!(is_insert.root.is_leaf());
}
#[test]
fn insert_test_two() {
- let leaf_elt_1 = LeafElt::new(1, ~"aaa");
- let leaf_elt_2 = LeafElt::new(2, ~"bbb");
- let leaf_elt_3 = LeafElt::new(3, ~"ccc");
+ let leaf_elt_1 = LeafElt::new(1, "aaa".to_owned());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_owned());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_owned());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3));
let b = BTree::new_with_node_len(n, 3, 2);
- //println!("{}", b.clone().insert(4, ~"ddd").to_str());
- assert!(b.insert(4, ~"ddd").root.is_leaf());
+ //println!("{}", b.clone().insert(4, "ddd".to_owned()).to_str());
+ assert!(b.insert(4, "ddd".to_owned()).root.is_leaf());
}
#[test]
fn insert_test_three() {
- let leaf_elt_1 = LeafElt::new(1, ~"aaa");
- let leaf_elt_2 = LeafElt::new(2, ~"bbb");
- let leaf_elt_3 = LeafElt::new(3, ~"ccc");
- let leaf_elt_4 = LeafElt::new(4, ~"ddd");
+ let leaf_elt_1 = LeafElt::new(1, "aaa".to_owned());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_owned());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_owned());
+ let leaf_elt_4 = LeafElt::new(4, "ddd".to_owned());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
- //println!("{}", b.clone().insert(5, ~"eee").to_str());
- assert!(!b.insert(5, ~"eee").root.is_leaf());
+ //println!("{}", b.clone().insert(5, "eee".to_owned()).to_str());
+ assert!(!b.insert(5, "eee".to_owned()).root.is_leaf());
}
#[test]
fn insert_test_four() {
- let leaf_elt_1 = LeafElt::new(1, ~"aaa");
- let leaf_elt_2 = LeafElt::new(2, ~"bbb");
- let leaf_elt_3 = LeafElt::new(3, ~"ccc");
- let leaf_elt_4 = LeafElt::new(4, ~"ddd");
+ let leaf_elt_1 = LeafElt::new(1, "aaa".to_owned());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_owned());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_owned());
+ let leaf_elt_4 = LeafElt::new(4, "ddd".to_owned());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let mut b = BTree::new_with_node_len(n, 3, 2);
- b = b.clone().insert(5, ~"eee");
- b = b.clone().insert(6, ~"fff");
- b = b.clone().insert(7, ~"ggg");
- b = b.clone().insert(8, ~"hhh");
- b = b.clone().insert(0, ~"omg");
+ b = b.clone().insert(5, "eee".to_owned());
+ b = b.clone().insert(6, "fff".to_owned());
+ b = b.clone().insert(7, "ggg".to_owned());
+ b = b.clone().insert(8, "hhh".to_owned());
+ b = b.clone().insert(0, "omg".to_owned());
//println!("{}", b.clone().to_str());
assert!(!b.root.is_leaf());
}
#[test]
fn bsearch_test_one() {
- let b = BTree::new(1, ~"abc", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
assert_eq!(Some(1), b.root.bsearch_node(2));
}
#[test]
fn bsearch_test_two() {
- let b = BTree::new(1, ~"abc", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
assert_eq!(Some(0), b.root.bsearch_node(0));
}
#[test]
fn bsearch_test_three() {
- let leaf_elt_1 = LeafElt::new(1, ~"aaa");
- let leaf_elt_2 = LeafElt::new(2, ~"bbb");
- let leaf_elt_3 = LeafElt::new(4, ~"ccc");
- let leaf_elt_4 = LeafElt::new(5, ~"ddd");
+ let leaf_elt_1 = LeafElt::new(1, "aaa".to_owned());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_owned());
+ let leaf_elt_3 = LeafElt::new(4, "ccc".to_owned());
+ let leaf_elt_4 = LeafElt::new(5, "ddd".to_owned());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(2), b.root.bsearch_node(3));
#[test]
fn bsearch_test_four() {
- let leaf_elt_1 = LeafElt::new(1, ~"aaa");
- let leaf_elt_2 = LeafElt::new(2, ~"bbb");
- let leaf_elt_3 = LeafElt::new(4, ~"ccc");
- let leaf_elt_4 = LeafElt::new(5, ~"ddd");
+ let leaf_elt_1 = LeafElt::new(1, "aaa".to_owned());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_owned());
+ let leaf_elt_3 = LeafElt::new(4, "ccc".to_owned());
+ let leaf_elt_4 = LeafElt::new(5, "ddd".to_owned());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(4), b.root.bsearch_node(800));
//Tests the functionality of the get method.
#[test]
fn get_test() {
- let b = BTree::new(1, ~"abc", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
let val = b.get(1);
- assert_eq!(val, Some(~"abc"));
+ assert_eq!(val, Some("abc".to_owned()));
}
//Tests the BTree's clone() method.
#[test]
fn btree_clone_test() {
- let b = BTree::new(1, ~"abc", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
let b2 = b.clone();
assert!(b.root == b2.root)
}
//Tests the BTree's cmp() method when one node is "less than" another.
#[test]
fn btree_cmp_test_less() {
- let b = BTree::new(1, ~"abc", 2);
- let b2 = BTree::new(2, ~"bcd", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
+ let b2 = BTree::new(2, "bcd".to_owned(), 2);
assert!(&b.cmp(&b2) == &Less)
}
//Tests the BTree's cmp() method when two nodes are equal.
#[test]
fn btree_cmp_test_eq() {
- let b = BTree::new(1, ~"abc", 2);
- let b2 = BTree::new(1, ~"bcd", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
+ let b2 = BTree::new(1, "bcd".to_owned(), 2);
assert!(&b.cmp(&b2) == &Equal)
}
//Tests the BTree's cmp() method when one node is "greater than" another.
#[test]
fn btree_cmp_test_greater() {
- let b = BTree::new(1, ~"abc", 2);
- let b2 = BTree::new(2, ~"bcd", 2);
+ let b = BTree::new(1, "abc".to_owned(), 2);
+ let b2 = BTree::new(2, "bcd".to_owned(), 2);
assert!(&b2.cmp(&b) == &Greater)
}
//Tests the BTree's to_str() method.
#[test]
fn btree_tostr_test() {
- let b = BTree::new(1, ~"abc", 2);
- assert_eq!(b.to_str(), ~"Key: 1, value: abc;")
+ let b = BTree::new(1, "abc".to_owned(), 2);
+ assert_eq!(b.to_str(), "Key: 1, value: abc;".to_owned())
}
}
let mut m = HashMap::new();
let (foo, bar, baz) = (1,2,3);
- m.insert(~"foo", foo);
- m.insert(~"bar", bar);
- m.insert(~"baz", baz);
+ m.insert("foo".to_owned(), foo);
+ m.insert("bar".to_owned(), bar);
+ m.insert("baz".to_owned(), baz);
assert_eq!(m.find_equiv(&("foo")), Some(&foo));
let set_str = format!("{}", set);
- assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
- assert_eq!(format!("{}", empty), ~"{}");
+ assert!(set_str == "{1, 2}".to_owned() || set_str == "{2, 1}".to_owned());
+ assert_eq!(format!("{}", empty), "{}".to_owned());
}
}
#[test]
fn test_put_update() {
let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1);
- cache.put(~"1", vec![10, 10]);
- cache.put(~"1", vec![10, 19]);
- assert_opt_eq(cache.get(&~"1"), vec![10, 19]);
+ cache.put("1".to_owned(), vec![10, 10]);
+ cache.put("1".to_owned(), vec![10, 19]);
+ assert_opt_eq(cache.get(&"1".to_owned()), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<~str, ~str> = LruCache::new(2);
- cache.put(~"foo1", ~"bar1");
- cache.put(~"foo2", ~"bar2");
- cache.put(~"foo3", ~"bar3");
- assert!(cache.get(&~"foo1").is_none());
- cache.put(~"foo2", ~"bar2update");
- cache.put(~"foo4", ~"bar4");
- assert!(cache.get(&~"foo3").is_none());
+ cache.put("foo1".to_owned(), "bar1".to_owned());
+ cache.put("foo2".to_owned(), "bar2".to_owned());
+ cache.put("foo3".to_owned(), "bar3".to_owned());
+ assert!(cache.get(&"foo1".to_owned()).is_none());
+ cache.put("foo2".to_owned(), "bar2update".to_owned());
+ cache.put("foo4".to_owned(), "bar4".to_owned());
+ assert!(cache.get(&"foo3".to_owned()).is_none());
}
#[test]
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
- assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
+ assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_owned());
cache.put(2, 22);
- assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
+ assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned());
cache.put(6, 60);
- assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
+ assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned());
cache.get(&3);
- assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
+ assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned());
cache.change_capacity(2);
- assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
+ assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned());
}
#[test]
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
- assert_eq!(cache.to_str(), ~"{}");
+ assert_eq!(cache.to_str(), "{}".to_owned());
}
}
OptGroup {
short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
- hint: ~"",
+ hint: "".to_owned(),
desc: desc.to_owned(),
hasarg: No,
occur: Optional
OptGroup {
short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
- hint: ~"",
+ hint: "".to_owned(),
desc: desc.to_owned(),
hasarg: No,
occur: Multi
let curlen = cur.len();
if !is_arg(cur) {
free.push(cur);
- } else if cur == ~"--" {
+ } else if cur == "--".to_owned() {
let mut j = i + 1;
while j < l { free.push(args[j].clone()); j += 1; }
break;
}
t("", 0, []);
t("", 15, []);
- t("hello", 15, [~"hello"]);
+ t("hello", 15, ["hello".to_owned()]);
t("\nMary had a little lamb\nLittle lamb\n", 15,
- [~"Mary had a", ~"little lamb", ~"Little lamb"]);
+ ["Mary had a".to_owned(), "little lamb".to_owned(), "Little lamb".to_owned()]);
t("\nMary had a little lamb\nLittle lamb\n", ::std::uint::MAX,
- [~"Mary had a little lamb\nLittle lamb"]);
+ ["Mary had a little lamb\nLittle lamb".to_owned()]);
}
#[cfg(test)]
// Tests for reqopt
#[test]
fn test_reqopt() {
- let long_args = vec!(~"--test=20");
+ let long_args = vec!("--test=20".to_owned());
let opts = vec!(reqopt("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!(m.opt_present("t"));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => { fail!("test_reqopt failed (long arg)"); }
}
- let short_args = vec!(~"-t", ~"20");
+ let short_args = vec!("-t".to_owned(), "20".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Ok(ref m) => {
assert!((m.opt_present("test")));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => { fail!("test_reqopt failed (short arg)"); }
}
#[test]
fn test_reqopt_missing() {
- let args = vec!(~"blah");
+ let args = vec!("blah".to_owned());
let opts = vec!(reqopt("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_reqopt_no_arg() {
- let long_args = vec!(~"--test");
+ let long_args = vec!("--test".to_owned());
let opts = vec!(reqopt("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
- let short_args = vec!(~"-t");
+ let short_args = vec!("-t".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
#[test]
fn test_reqopt_multi() {
- let args = vec!(~"--test=20", ~"-t", ~"30");
+ let args = vec!("--test=20".to_owned(), "-t".to_owned(), "30".to_owned());
let opts = vec!(reqopt("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
// Tests for optopt
#[test]
fn test_optopt() {
- let long_args = vec!(~"--test=20");
+ let long_args = vec!("--test=20".to_owned());
let opts = vec!(optopt("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => fail!()
}
- let short_args = vec!(~"-t", ~"20");
+ let short_args = vec!("-t".to_owned(), "20".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Ok(ref m) => {
assert!((m.opt_present("test")));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => fail!()
}
#[test]
fn test_optopt_missing() {
- let args = vec!(~"blah");
+ let args = vec!("blah".to_owned());
let opts = vec!(optopt("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optopt_no_arg() {
- let long_args = vec!(~"--test");
+ let long_args = vec!("--test".to_owned());
let opts = vec!(optopt("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
- let short_args = vec!(~"-t");
+ let short_args = vec!("-t".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
#[test]
fn test_optopt_multi() {
- let args = vec!(~"--test=20", ~"-t", ~"30");
+ let args = vec!("--test=20".to_owned(), "-t".to_owned(), "30".to_owned());
let opts = vec!(optopt("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
// Tests for optflag
#[test]
fn test_optflag() {
- let long_args = vec!(~"--test");
+ let long_args = vec!("--test".to_owned());
let opts = vec!(optflag("t", "test", "testing"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
}
_ => fail!()
}
- let short_args = vec!(~"-t");
+ let short_args = vec!("-t".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Ok(ref m) => {
assert!(m.opt_present("test"));
#[test]
fn test_optflag_missing() {
- let args = vec!(~"blah");
+ let args = vec!("blah".to_owned());
let opts = vec!(optflag("t", "test", "testing"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflag_long_arg() {
- let args = vec!(~"--test=20");
+ let args = vec!("--test=20".to_owned());
let opts = vec!(optflag("t", "test", "testing"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflag_multi() {
- let args = vec!(~"--test", ~"-t");
+ let args = vec!("--test".to_owned(), "-t".to_owned());
let opts = vec!(optflag("t", "test", "testing"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflag_short_arg() {
- let args = vec!(~"-t", ~"20");
+ let args = vec!("-t".to_owned(), "20".to_owned());
let opts = vec!(optflag("t", "test", "testing"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
// The next variable after the flag is just a free argument
- assert!(*m.free.get(0) == ~"20");
+ assert!(*m.free.get(0) == "20".to_owned());
}
_ => fail!()
}
// Tests for optflagmulti
#[test]
fn test_optflagmulti_short1() {
- let args = vec!(~"-v");
+ let args = vec!("-v".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflagmulti_short2a() {
- let args = vec!(~"-v", ~"-v");
+ let args = vec!("-v".to_owned(), "-v".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflagmulti_short2b() {
- let args = vec!(~"-vv");
+ let args = vec!("-vv".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflagmulti_long1() {
- let args = vec!(~"--verbose");
+ let args = vec!("--verbose".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflagmulti_long2() {
- let args = vec!(~"--verbose", ~"--verbose");
+ let args = vec!("--verbose".to_owned(), "--verbose".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optflagmulti_mix() {
- let args = vec!(~"--verbose", ~"-v", ~"-vv", ~"verbose");
+ let args = vec!("--verbose".to_owned(), "-v".to_owned(),
+ "-vv".to_owned(), "verbose".to_owned());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
// Tests for optmulti
#[test]
fn test_optmulti() {
- let long_args = vec!(~"--test=20");
+ let long_args = vec!("--test=20".to_owned());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
assert!((m.opt_present("test")));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => fail!()
}
- let short_args = vec!(~"-t", ~"20");
+ let short_args = vec!("-t".to_owned(), "20".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Ok(ref m) => {
assert!((m.opt_present("test")));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
}
_ => fail!()
}
#[test]
fn test_optmulti_missing() {
- let args = vec!(~"blah");
+ let args = vec!("blah".to_owned());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
#[test]
fn test_optmulti_no_arg() {
- let long_args = vec!(~"--test");
+ let long_args = vec!("--test".to_owned());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
- let short_args = vec!(~"-t");
+ let short_args = vec!("-t".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
#[test]
fn test_optmulti_multi() {
- let args = vec!(~"--test=20", ~"-t", ~"30");
+ let args = vec!("--test=20".to_owned(), "-t".to_owned(), "30".to_owned());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
- assert_eq!(m.opt_str("test").unwrap(), ~"20");
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_owned());
assert!(m.opt_present("t"));
- assert_eq!(m.opt_str("t").unwrap(), ~"20");
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_owned());
let pair = m.opt_strs("test");
- assert!(*pair.get(0) == ~"20");
- assert!(*pair.get(1) == ~"30");
+ assert!(*pair.get(0) == "20".to_owned());
+ assert!(*pair.get(1) == "30".to_owned());
}
_ => fail!()
}
#[test]
fn test_unrecognized_option() {
- let long_args = vec!(~"--untest");
+ let long_args = vec!("--untest".to_owned());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!()
}
- let short_args = vec!(~"-u");
+ let short_args = vec!("-u".to_owned());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!()
#[test]
fn test_combined() {
let args =
- vec!(~"prog", ~"free1", ~"-s", ~"20", ~"free2",
- ~"--flag", ~"--long=30", ~"-f", ~"-m", ~"40",
- ~"-m", ~"50", ~"-n", ~"-A B", ~"-n", ~"-60 70");
+ vec!("prog".to_owned(), "free1".to_owned(), "-s".to_owned(), "20".to_owned(),
+ "free2".to_owned(), "--flag".to_owned(), "--long=30".to_owned(), "-f".to_owned(),
+ "-m".to_owned(), "40".to_owned(), "-m".to_owned(), "50".to_owned(), "-n".to_owned(),
+ "-A B".to_owned(), "-n".to_owned(), "-60 70".to_owned());
let opts =
vec!(optopt("s", "something", "something", "SOMETHING"),
optflag("", "flag", "a flag"),
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Ok(ref m) => {
- assert!(*m.free.get(0) == ~"prog");
- assert!(*m.free.get(1) == ~"free1");
- assert_eq!(m.opt_str("s").unwrap(), ~"20");
- assert!(*m.free.get(2) == ~"free2");
+ assert!(*m.free.get(0) == "prog".to_owned());
+ assert!(*m.free.get(1) == "free1".to_owned());
+ assert_eq!(m.opt_str("s").unwrap(), "20".to_owned());
+ assert!(*m.free.get(2) == "free2".to_owned());
assert!((m.opt_present("flag")));
- assert_eq!(m.opt_str("long").unwrap(), ~"30");
+ assert_eq!(m.opt_str("long").unwrap(), "30".to_owned());
assert!((m.opt_present("f")));
let pair = m.opt_strs("m");
- assert!(*pair.get(0) == ~"40");
- assert!(*pair.get(1) == ~"50");
+ assert!(*pair.get(0) == "40".to_owned());
+ assert!(*pair.get(1) == "50".to_owned());
let pair = m.opt_strs("n");
- assert!(*pair.get(0) == ~"-A B");
- assert!(*pair.get(1) == ~"-60 70");
+ assert!(*pair.get(0) == "-A B".to_owned());
+ assert!(*pair.get(1) == "-60 70".to_owned());
assert!((!m.opt_present("notpresent")));
}
_ => fail!()
optopt("", "encrypt", "encrypt", "ENCRYPT"),
optopt("f", "", "flag", "FLAG"));
- let args_single = vec!(~"-e", ~"foo");
+ let args_single = vec!("-e".to_owned(), "foo".to_owned());
let matches_single = &match getopts(args_single.as_slice(),
opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
};
- assert!(matches_single.opts_present([~"e"]));
- assert!(matches_single.opts_present([~"encrypt", ~"e"]));
- assert!(matches_single.opts_present([~"e", ~"encrypt"]));
- assert!(!matches_single.opts_present([~"encrypt"]));
- assert!(!matches_single.opts_present([~"thing"]));
+ assert!(matches_single.opts_present(["e".to_owned()]));
+ assert!(matches_single.opts_present(["encrypt".to_owned(), "e".to_owned()]));
+ assert!(matches_single.opts_present(["e".to_owned(), "encrypt".to_owned()]));
+ assert!(!matches_single.opts_present(["encrypt".to_owned()]));
+ assert!(!matches_single.opts_present(["thing".to_owned()]));
assert!(!matches_single.opts_present([]));
- assert_eq!(matches_single.opts_str([~"e"]).unwrap(), ~"foo");
- assert_eq!(matches_single.opts_str([~"e", ~"encrypt"]).unwrap(), ~"foo");
- assert_eq!(matches_single.opts_str([~"encrypt", ~"e"]).unwrap(), ~"foo");
+ assert_eq!(matches_single.opts_str(["e".to_owned()]).unwrap(), "foo".to_owned());
+ assert_eq!(matches_single.opts_str(["e".to_owned(), "encrypt".to_owned()]).unwrap(),
+ "foo".to_owned());
+ assert_eq!(matches_single.opts_str(["encrypt".to_owned(), "e".to_owned()]).unwrap(),
+ "foo".to_owned());
- let args_both = vec!(~"-e", ~"foo", ~"--encrypt", ~"foo");
+ let args_both = vec!("-e".to_owned(), "foo".to_owned(), "--encrypt".to_owned(),
+ "foo".to_owned());
let matches_both = &match getopts(args_both.as_slice(),
opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
};
- assert!(matches_both.opts_present([~"e"]));
- assert!(matches_both.opts_present([~"encrypt"]));
- assert!(matches_both.opts_present([~"encrypt", ~"e"]));
- assert!(matches_both.opts_present([~"e", ~"encrypt"]));
- assert!(!matches_both.opts_present([~"f"]));
- assert!(!matches_both.opts_present([~"thing"]));
+ assert!(matches_both.opts_present(["e".to_owned()]));
+ assert!(matches_both.opts_present(["encrypt".to_owned()]));
+ assert!(matches_both.opts_present(["encrypt".to_owned(), "e".to_owned()]));
+ assert!(matches_both.opts_present(["e".to_owned(), "encrypt".to_owned()]));
+ assert!(!matches_both.opts_present(["f".to_owned()]));
+ assert!(!matches_both.opts_present(["thing".to_owned()]));
assert!(!matches_both.opts_present([]));
- assert_eq!(matches_both.opts_str([~"e"]).unwrap(), ~"foo");
- assert_eq!(matches_both.opts_str([~"encrypt"]).unwrap(), ~"foo");
- assert_eq!(matches_both.opts_str([~"e", ~"encrypt"]).unwrap(), ~"foo");
- assert_eq!(matches_both.opts_str([~"encrypt", ~"e"]).unwrap(), ~"foo");
+ assert_eq!(matches_both.opts_str(["e".to_owned()]).unwrap(), "foo".to_owned());
+ assert_eq!(matches_both.opts_str(["encrypt".to_owned()]).unwrap(), "foo".to_owned());
+ assert_eq!(matches_both.opts_str(["e".to_owned(), "encrypt".to_owned()]).unwrap(),
+ "foo".to_owned());
+ assert_eq!(matches_both.opts_str(["encrypt".to_owned(), "e".to_owned()]).unwrap(),
+ "foo".to_owned());
}
#[test]
fn test_nospace() {
- let args = vec!(~"-Lfoo", ~"-M.");
+ let args = vec!("-Lfoo".to_owned(), "-M.".to_owned());
let opts = vec!(optmulti("L", "", "library directory", "LIB"),
optmulti("M", "", "something", "MMMM"));
let matches = &match getopts(args.as_slice(), opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
};
- assert!(matches.opts_present([~"L"]));
- assert_eq!(matches.opts_str([~"L"]).unwrap(), ~"foo");
- assert!(matches.opts_present([~"M"]));
- assert_eq!(matches.opts_str([~"M"]).unwrap(), ~".");
+ assert!(matches.opts_present(["L".to_owned()]));
+ assert_eq!(matches.opts_str(["L".to_owned()]).unwrap(), "foo".to_owned());
+ assert!(matches.opts_present(["M".to_owned()]));
+ assert_eq!(matches.opts_str(["M".to_owned()]).unwrap(), ".".to_owned());
}
#[test]
fn test_long_to_short() {
let mut short = Opt {
- name: Long(~"banana"),
+ name: Long("banana".to_owned()),
hasarg: Yes,
occur: Req,
aliases: Vec::new(),
let opts = vec!(
optflagmulti("a", "apple", "Desc"));
- let args = vec!(~"-a", ~"--apple", ~"-a");
+ let args = vec!("-a".to_owned(), "--apple".to_owned(), "-a".to_owned());
let matches = getopts(args.as_slice(), opts.as_slice()).unwrap();
assert_eq!(3, matches.opt_count("a"));
optflagopt("p", "", "Desc", "VAL"),
optmulti("l", "", "Desc", "VAL"));
- let expected = ~"Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..";
+ let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_owned();
let generated_usage = short_usage("fruits", optgroups.as_slice());
debug!("expected: <<{}>>", expected);
#[test]
fn test_pattern_escape() {
let s = "_[_]_?_*_!_";
- assert_eq!(Pattern::escape(s), ~"_[[]_[]]_[?]_[*]_!_");
+ assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_owned());
assert!(Pattern::new(Pattern::escape(s)).matches(s));
}
let mut chars = s.chars().peekable();
let mut i = 0;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
- if chars.next() != Some('0') { return Some((i, ~"Expected '0'")); } i+=1;
- if chars.next() != Some('x') { return Some((i, ~"Expected 'x'")); } i+=1;
+ if chars.next() != Some('0') { return Some((i, "Expected '0'".to_owned())); } i+=1;
+ if chars.next() != Some('x') { return Some((i, "Expected 'x'".to_owned())); } i+=1;
let mut d_len = 0;
for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;}
- if chars.next() != Some('.') { return Some((i, ~"Expected '.'")); } i+=1;
+ if chars.next() != Some('.') { return Some((i, "Expected '.'".to_owned())); } i+=1;
let mut f_len = 0;
for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;}
if d_len == 0 && f_len == 0 {
- return Some((i, ~"Expected digits before or after decimal point"));
+ return Some((i, "Expected digits before or after decimal point".to_owned()));
}
- if chars.next() != Some('p') { return Some((i, ~"Expected 'p'")); } i+=1;
+ if chars.next() != Some('p') { return Some((i, "Expected 'p'".to_owned())); } i+=1;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
let mut e_len = 0;
for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
if e_len == 0 {
- return Some((i, ~"Expected exponent digits"));
+ return Some((i, "Expected exponent digits".to_owned()));
}
match chars.next() {
None => None,
- Some(_) => Some((i, ~"Expected end of string"))
+ Some(_) => Some((i, "Expected end of string".to_owned()))
}
}
let dirs = parse_logging_spec("crate1::mod1=1,crate1::mod2,crate2=4");
let dirs = dirs.as_slice();
assert_eq!(dirs.len(), 3);
- assert_eq!(dirs[0].name, Some(~"crate1::mod1"));
+ assert_eq!(dirs[0].name, Some("crate1::mod1".to_owned()));
assert_eq!(dirs[0].level, 1);
- assert_eq!(dirs[1].name, Some(~"crate1::mod2"));
+ assert_eq!(dirs[1].name, Some("crate1::mod2".to_owned()));
assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL);
- assert_eq!(dirs[2].name, Some(~"crate2"));
+ assert_eq!(dirs[2].name, Some("crate2".to_owned()));
assert_eq!(dirs[2].level, 4);
}
let dirs = parse_logging_spec("crate1::mod1=1=2,crate2=4");
let dirs = dirs.as_slice();
assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some(~"crate2"));
+ assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, 4);
}
let dirs = parse_logging_spec("crate1::mod1=noNumber,crate2=4");
let dirs = dirs.as_slice();
assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some(~"crate2"));
+ assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, 4);
}
let dirs = parse_logging_spec("crate1::mod1=wrong,crate2=warn");
let dirs = dirs.as_slice();
assert_eq!(dirs.len(), 1);
- assert_eq!(dirs[0].name, Some(~"crate2"));
+ assert_eq!(dirs[0].name, Some("crate2".to_owned()));
assert_eq!(dirs[0].level, ::WARN);
}
assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0].name, None);
assert_eq!(dirs[0].level, 2);
- assert_eq!(dirs[1].name, Some(~"crate2"));
+ assert_eq!(dirs[1].name, Some("crate2".to_owned()));
assert_eq!(dirs[1].level, 4);
}
}
#[test]
fn match_full_path() {
- let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
- LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
+ let dirs = [LogDirective { name: Some("crate2".to_owned()), level: 3 },
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 2 }];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
#[test]
fn no_match() {
- let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
- LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
+ let dirs = [LogDirective { name: Some("crate2".to_owned()), level: 3 },
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 2 }];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
- let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
- LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
+ let dirs = [LogDirective { name: Some("crate2".to_owned()), level: 3 },
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 2 }];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
- let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
- LogDirective { name: Some(~"crate2::mod"), level: 4 },
- LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
+ let dirs = [LogDirective { name: Some("crate2".to_owned()), level: 3 },
+ LogDirective { name: Some("crate2::mod".to_owned()), level: 4 },
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 2 }];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn match_default() {
let dirs = [LogDirective { name: None, level: 3 },
- LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 2 }];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level() {
let dirs = [LogDirective { name: None, level: 3 },
- LogDirective { name: Some(~"crate1::mod1"), level: 0 }];
+ LogDirective { name: Some("crate1::mod1".to_owned()), level: 0 }];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
fn test_make_command_line() {
use super::make_command_line;
assert_eq!(
- make_command_line("prog", [~"aaa", ~"bbb", ~"ccc"]),
- ~"prog aaa bbb ccc"
+ make_command_line("prog", ["aaa".to_owned(), "bbb".to_owned(), "ccc".to_owned()]),
+ "prog aaa bbb ccc".to_owned()
);
assert_eq!(
- make_command_line("C:\\Program Files\\blah\\blah.exe", [~"aaa"]),
- ~"\"C:\\Program Files\\blah\\blah.exe\" aaa"
+ make_command_line("C:\\Program Files\\blah\\blah.exe", ["aaa".to_owned()]),
+ "\"C:\\Program Files\\blah\\blah.exe\" aaa".to_owned()
);
assert_eq!(
- make_command_line("C:\\Program Files\\test", [~"aa\"bb"]),
- ~"\"C:\\Program Files\\test\" aa\\\"bb"
+ make_command_line("C:\\Program Files\\test", ["aa\"bb".to_owned()]),
+ "\"C:\\Program Files\\test\" aa\\\"bb".to_owned()
);
assert_eq!(
- make_command_line("echo", [~"a b c"]),
- ~"echo \"a b c\""
+ make_command_line("echo", ["a b c".to_owned()]),
+ "echo \"a b c\"".to_owned()
);
}
}
}
fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> ~str {
- if v.is_empty() { return ~"0" }
+ if v.is_empty() { return "0".to_owned() }
let mut s = StrBuf::with_capacity(v.len() * l);
for n in v.rev_iter() {
let ss = (*n as uint).to_str_radix(radix);
fn to_str_radix(&self, radix: uint) -> ~str {
match self.sign {
Plus => self.data.to_str_radix(radix),
- Zero => ~"0",
- Minus => ~"-" + self.data.to_str_radix(radix)
+ Zero => "0".to_owned(),
+ Minus => "-".to_owned() + self.data.to_str_radix(radix)
}
}
}
fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, ~str)>)> {
let bits = BigDigit::bits;
vec!(( Zero::zero(), vec!(
- (2, ~"0"), (3, ~"0")
+ (2, "0".to_owned()), (3, "0".to_owned())
)), ( BigUint::from_slice([ 0xff ]), vec!(
- (2, ~"11111111"),
- (3, ~"100110"),
- (4, ~"3333"),
- (5, ~"2010"),
- (6, ~"1103"),
- (7, ~"513"),
- (8, ~"377"),
- (9, ~"313"),
- (10, ~"255"),
- (11, ~"212"),
- (12, ~"193"),
- (13, ~"168"),
- (14, ~"143"),
- (15, ~"120"),
- (16, ~"ff")
+ (2, "11111111".to_owned()),
+ (3, "100110".to_owned()),
+ (4, "3333".to_owned()),
+ (5, "2010".to_owned()),
+ (6, "1103".to_owned()),
+ (7, "513".to_owned()),
+ (8, "377".to_owned()),
+ (9, "313".to_owned()),
+ (10, "255".to_owned()),
+ (11, "212".to_owned()),
+ (12, "193".to_owned()),
+ (13, "168".to_owned()),
+ (14, "143".to_owned()),
+ (15, "120".to_owned()),
+ (16, "ff".to_owned())
)), ( BigUint::from_slice([ 0xfff ]), vec!(
- (2, ~"111111111111"),
- (4, ~"333333"),
- (16, ~"fff")
+ (2, "111111111111".to_owned()),
+ (4, "333333".to_owned()),
+ (16, "fff".to_owned())
)), ( BigUint::from_slice([ 1, 2 ]), vec!(
(2,
- ~"10" +
+ "10".to_owned() +
"0".repeat(bits - 1) + "1"),
(4,
- ~"2" +
+ "2".to_owned() +
"0".repeat(bits / 2 - 1) + "1"),
(10, match bits {
- 32 => ~"8589934593", 16 => ~"131073", _ => fail!()
+ 32 => "8589934593".to_owned(), 16 => "131073".to_owned(), _ => fail!()
}),
(16,
- ~"2" +
+ "2".to_owned() +
"0".repeat(bits / 4 - 1) + "1")
)), ( BigUint::from_slice([ 1, 2, 3 ]), vec!(
(2,
- ~"11" +
+ "11".to_owned() +
"0".repeat(bits - 2) + "10" +
"0".repeat(bits - 1) + "1"),
(4,
- ~"3" +
+ "3".to_owned() +
"0".repeat(bits / 2 - 1) + "2" +
"0".repeat(bits / 2 - 1) + "1"),
(10, match bits {
- 32 => ~"55340232229718589441",
- 16 => ~"12885032961",
+ 32 => "55340232229718589441".to_owned(),
+ 16 => "12885032961".to_owned(),
_ => fail!()
}),
- (16, ~"3" +
+ (16, "3".to_owned() +
"0".repeat(bits / 4 - 1) + "2" +
"0".repeat(bits / 4 - 1) + "1")
)) )
fn test(c : Complex64, s: ~str) {
assert_eq!(c.to_str(), s);
}
- test(_0_0i, ~"0+0i");
- test(_1_0i, ~"1+0i");
- test(_0_1i, ~"0+1i");
- test(_1_1i, ~"1+1i");
- test(_neg1_1i, ~"-1+1i");
- test(-_neg1_1i, ~"1-1i");
- test(_05_05i, ~"0.5+0.5i");
+ test(_0_0i, "0+0i".to_owned());
+ test(_1_0i, "1+0i".to_owned());
+ test(_0_1i, "0+1i".to_owned());
+ test(_1_1i, "1+1i".to_owned());
+ test(_neg1_1i, "-1+1i".to_owned());
+ test(-_neg1_1i, "1-1i".to_owned());
+ test(_05_05i, "0.5+0.5i".to_owned());
}
}
assert_eq!(FromStr::from_str(s), Some(r));
assert_eq!(r.to_str(), s);
}
- test(_1, ~"1/1");
- test(_0, ~"0/1");
- test(_1_2, ~"1/2");
- test(_3_2, ~"3/2");
- test(_2, ~"2/1");
- test(_neg1_2, ~"-1/2");
+ test(_1, "1/1".to_owned());
+ test(_0, "0/1".to_owned());
+ test(_1_2, "1/2".to_owned());
+ test(_3_2, "3/2".to_owned());
+ test(_2, "2/1".to_owned());
+ test(_neg1_2, "-1/2".to_owned());
}
#[test]
fn test_from_str_fail() {
fn test3(r: Rational, s: ~str) { test(r, s, 3) }
fn test16(r: Rational, s: ~str) { test(r, s, 16) }
- test3(_1, ~"1/1");
- test3(_0, ~"0/1");
- test3(_1_2, ~"1/2");
- test3(_3_2, ~"10/2");
- test3(_2, ~"2/1");
- test3(_neg1_2, ~"-1/2");
- test3(_neg1_2 / _2, ~"-1/11");
-
- test16(_1, ~"1/1");
- test16(_0, ~"0/1");
- test16(_1_2, ~"1/2");
- test16(_3_2, ~"3/2");
- test16(_2, ~"2/1");
- test16(_neg1_2, ~"-1/2");
- test16(_neg1_2 / _2, ~"-1/4");
- test16(Ratio::new(13,15), ~"d/f");
- test16(_1_2*_1_2*_1_2*_1_2, ~"1/10");
+ test3(_1, "1/1".to_owned());
+ test3(_0, "0/1".to_owned());
+ test3(_1_2, "1/2".to_owned());
+ test3(_3_2, "10/2".to_owned());
+ test3(_2, "2/1".to_owned());
+ test3(_neg1_2, "-1/2".to_owned());
+ test3(_neg1_2 / _2, "-1/11".to_owned());
+
+ test16(_1, "1/1".to_owned());
+ test16(_0, "0/1".to_owned());
+ test16(_1_2, "1/2".to_owned());
+ test16(_3_2, "3/2".to_owned());
+ test16(_2, "2/1".to_owned());
+ test16(_neg1_2, "-1/2".to_owned());
+ test16(_neg1_2 / _2, "-1/4".to_owned());
+ test16(Ratio::new(13,15), "d/f".to_owned());
+ test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_owned());
}
#[test]
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
let cc_args = if target_triple.contains("thumb") {
- vec!(~"-mthumb")
+ vec!("-mthumb".to_owned())
} else {
- vec!(~"-marm")
+ vec!("-marm".to_owned())
};
return target_strs::t {
- module_asm: ~"",
+ module_asm: "".to_owned(),
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
- ~"e-p:32:32:32" +
+ "e-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsWin32 => {
- ~"e-p:32:32:32" +
+ "e-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsLinux => {
- ~"e-p:32:32:32" +
+ "e-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsAndroid => {
- ~"e-p:32:32:32" +
+ "e-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsFreebsd => {
- ~"e-p:32:32:32" +
+ "e-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
let result = llvm::LLVMRustWriteOutputFile(
target, pm, m, output, file_type);
if !result {
- llvm_err(sess, ~"could not write output");
+ llvm_err(sess, "could not write output".to_owned());
}
})
}
// FIXME (#9639): This needs to handle non-utf8 paths
let args = [
- ~"-c",
- ~"-o", object.as_str().unwrap().to_owned(),
+ "-c".to_owned(),
+ "-o".to_owned(), object.as_str().unwrap().to_owned(),
assembly.as_str().unwrap().to_owned()];
debug!("{} '{}'", cc, args.connect("' '"));
if result.len() > 0u &&
result[0] != '_' as u8 &&
! char::is_XID_start(result[0] as char) {
- return ~"_" + result;
+ return "_".to_owned() + result;
}
return result;
// instead of hard-coded gcc.
// For win32, there is no cc command, so we add a condition to make it use gcc.
match sess.targ_cfg.os {
- abi::OsWin32 => return ~"gcc",
+ abi::OsWin32 => return "gcc".to_owned(),
_ => {},
}
// The location of crates will be determined as needed.
// FIXME (#9639): This needs to handle non-utf8 paths
let lib_path = sess.filesearch().get_target_lib_path();
- let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
+ let stage: ~str = "-L".to_owned() + lib_path.as_str().unwrap();
let mut args = vec!(stage);
// FIXME (#9639): This needs to handle non-utf8 paths
args.push_all([
- ~"-o", out_filename.as_str().unwrap().to_owned(),
+ "-o".to_owned(), out_filename.as_str().unwrap().to_owned(),
obj_filename.as_str().unwrap().to_owned()]);
// Stack growth requires statically linking a __morestack function. Note
// line, but inserting this farther to the left makes the
// "rust_stack_exhausted" symbol an outstanding undefined symbol, which
// flags libstd as a required library (or whatever provides the symbol).
- args.push(~"-lmorestack");
+ args.push("-lmorestack".to_owned());
// When linking a dynamic library, we put the metadata into a section of the
// executable. This metadata is in a separate object file from the main
//
// FIXME(#11937) we should invoke the system linker directly
if sess.targ_cfg.os != abi::OsWin32 {
- args.push(~"-nodefaultlibs");
+ args.push("-nodefaultlibs".to_owned());
}
if sess.targ_cfg.os == abi::OsLinux {
// GNU-style linkers will use this to omit linking to libraries which
// don't actually fulfill any relocations, but only for libraries which
// follow this flag. Thus, use it before specifying libraries to link to.
- args.push(~"-Wl,--as-needed");
+ args.push("-Wl,--as-needed".to_owned());
// GNU-style linkers support optimization with -O. --gc-sections
// removes metadata and potentially other useful things, so don't
// do.
if sess.opts.optimize == session::Default ||
sess.opts.optimize == session::Aggressive {
- args.push(~"-Wl,-O1");
+ args.push("-Wl,-O1".to_owned());
}
}
// Make sure that we link to the dynamic libgcc, otherwise cross-module
// DWARF stack unwinding will not work.
// This behavior may be overridden by --link-args "-static-libgcc"
- args.push(~"-shared-libgcc");
+ args.push("-shared-libgcc".to_owned());
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
//
// [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
// [2] - https://code.google.com/p/go/issues/detail?id=2139
- args.push(~"-Wl,--enable-long-section-names");
+ args.push("-Wl,--enable-long-section-names".to_owned());
}
if sess.targ_cfg.os == abi::OsAndroid {
// Many of the symbols defined in compiler-rt are also defined in libgcc.
// Android linker doesn't like that by default.
- args.push(~"-Wl,--allow-multiple-definition");
+ args.push("-Wl,--allow-multiple-definition".to_owned());
}
// Take careful note of the ordering of the arguments we pass to the linker
if dylib {
// On mac we need to tell the linker to let this library be rpathed
if sess.targ_cfg.os == abi::OsMacos {
- args.push(~"-dynamiclib");
- args.push(~"-Wl,-dylib");
+ args.push("-dynamiclib".to_owned());
+ args.push("-Wl,-dylib".to_owned());
// FIXME (#9639): This needs to handle non-utf8 paths
if !sess.opts.cg.no_rpath {
- args.push(~"-Wl,-install_name,@rpath/" +
+ args.push("-Wl,-install_name,@rpath/".to_owned() +
out_filename.filename_str().unwrap());
}
} else {
- args.push(~"-shared")
+ args.push("-shared".to_owned())
}
}
if sess.targ_cfg.os == abi::OsFreebsd {
- args.push_all([~"-L/usr/local/lib",
- ~"-L/usr/local/lib/gcc46",
- ~"-L/usr/local/lib/gcc44"]);
+ args.push_all(["-L/usr/local/lib".to_owned(),
+ "-L/usr/local/lib/gcc46".to_owned(),
+ "-L/usr/local/lib/gcc44".to_owned()]);
}
// FIXME (#2397): At some point we want to rpath our guesses as to
//
// This is the end of the command line, so this library is used to resolve
// *all* undefined symbols in all other libraries, and this is intentional.
- args.push(~"-lcompiler-rt");
+ args.push("-lcompiler-rt".to_owned());
// Finally add all the linker arguments provided on the command line along
// with any #[link_args] attributes found inside the crate
args.push("-l" + *l);
}
cstore::NativeFramework => {
- args.push(~"-framework");
+ args.push("-framework".to_owned());
args.push(l.to_owned());
}
}
match kind {
cstore::NativeUnknown => args.push("-l" + *lib),
cstore::NativeFramework => {
- args.push(~"-framework");
+ args.push("-framework".to_owned());
args.push(lib.to_owned());
}
cstore::NativeStatic => {
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
- module_asm: ~"",
+ module_asm: "".to_owned(),
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
- ~"E-p:32:32:32" +
+ "E-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsWin32 => {
- ~"E-p:32:32:32" +
+ "E-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsLinux => {
- ~"E-p:32:32:32" +
+ "E-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsAndroid => {
- ~"E-p:32:32:32" +
+ "E-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
}
abi::OsFreebsd => {
- ~"E-p:32:32:32" +
+ "E-p:32:32:32".to_owned() +
"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" +
"-f32:32:32-f64:64:64" +
"-v64:64:64-v128:64:128" +
let mut flags = Vec::new();
if sess.targ_cfg.os == abi::OsFreebsd {
- flags.push_all([~"-Wl,-rpath,/usr/local/lib/gcc46",
- ~"-Wl,-rpath,/usr/local/lib/gcc44",
- ~"-Wl,-z,origin"]);
+ flags.push_all(["-Wl,-rpath,/usr/local/lib/gcc46".to_owned(),
+ "-Wl,-rpath,/usr/local/lib/gcc44".to_owned(),
+ "-Wl,-z,origin".to_owned()]);
}
debug!("preparing the RPATH!");
#[test]
fn test_rpaths_to_flags() {
- let flags = rpaths_to_flags([~"path1", ~"path2"]);
- assert_eq!(flags, vec!(~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"));
+ let flags = rpaths_to_flags(["path1".to_owned(), "path2".to_owned()]);
+ assert_eq!(flags, vec!("-Wl,-rpath,path1".to_owned(), "-Wl,-rpath,path2".to_owned()));
}
#[test]
#[test]
fn test_minimize1() {
- let res = minimize_rpaths([~"rpath1", ~"rpath2", ~"rpath1"]);
- assert!(res.as_slice() == [~"rpath1", ~"rpath2"]);
+ let res = minimize_rpaths(["rpath1".to_owned(), "rpath2".to_owned(), "rpath1".to_owned()]);
+ assert!(res.as_slice() == ["rpath1".to_owned(), "rpath2".to_owned()]);
}
#[test]
fn test_minimize2() {
- let res = minimize_rpaths([~"1a", ~"2", ~"2",
- ~"1a", ~"4a", ~"1a",
- ~"2", ~"3", ~"4a",
- ~"3"]);
- assert!(res.as_slice() == [~"1a", ~"2", ~"4a", ~"3"]);
+ let res = minimize_rpaths(["1a".to_owned(), "2".to_owned(), "2".to_owned(),
+ "1a".to_owned(), "4a".to_owned(), "1a".to_owned(),
+ "2".to_owned(), "3".to_owned(), "4a".to_owned(),
+ "3".to_owned()]);
+ assert!(res.as_slice() == ["1a".to_owned(), "2".to_owned(), "4a".to_owned(),
+ "3".to_owned()]);
}
#[test]
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
- module_asm: ~"",
+ module_asm: "".to_owned(),
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
- ~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
+ "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16".to_owned() +
"-i32:32:32-i64:32:64" +
"-f32:32:32-f64:32:64-v64:64:64" +
"-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32"
}
abi::OsWin32 => {
- ~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32"
+ "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_owned()
}
abi::OsLinux => {
- ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_owned()
}
abi::OsAndroid => {
- ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_owned()
}
abi::OsFreebsd => {
- ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_owned()
}
},
target_triple: target_triple,
- cc_args: vec!(~"-m32"),
+ cc_args: vec!("-m32".to_owned()),
};
}
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
- module_asm: ~"",
+ module_asm: "".to_owned(),
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
- ~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
+ "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-".to_owned()+
"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
"s0:64:64-f80:128:128-n8:16:32:64"
}
abi::OsWin32 => {
// FIXME: Test this. Copied from linux (#2398)
- ~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
+ "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-".to_owned()+
"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
abi::OsLinux => {
- ~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
+ "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-".to_owned()+
"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
abi::OsAndroid => {
- ~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
+ "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-".to_owned()+
"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
abi::OsFreebsd => {
- ~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
+ "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-".to_owned()+
"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
target_triple: target_triple,
- cc_args: vec!(~"-m64"),
+ cc_args: vec!("-m64".to_owned()),
};
}
fn filestem(&self) -> ~str {
match *self {
FileInput(ref ifile) => ifile.filestem_str().unwrap().to_str(),
- StrInput(_) => ~"rust_out",
+ StrInput(_) => "rust_out".to_owned(),
}
}
}
}
pprust::NodeBlock(blk) => {
try!(pp::space(&mut s.s));
- s.synth_comment(~"block " + blk.id.to_str())
+ s.synth_comment("block ".to_owned() + blk.id.to_str())
}
pprust::NodeExpr(expr) => {
try!(pp::space(&mut s.s));
}
pprust::NodePat(pat) => {
try!(pp::space(&mut s.s));
- s.synth_comment(~"pat " + pat.id.to_str())
+ s.synth_comment("pat ".to_owned() + pat.id.to_str())
}
}
}
#[test]
fn test_switch_implies_cfg_test() {
let matches =
- &match getopts([~"--test"], optgroups().as_slice()) {
+ &match getopts(["--test".to_owned()], optgroups().as_slice()) {
Ok(m) => m,
Err(f) => fail!("test_switch_implies_cfg_test: {}", f.to_err_msg())
};
#[test]
fn test_switch_implies_cfg_test_unless_cfg_test() {
let matches =
- &match getopts([~"--test", ~"--cfg=test"],
+ &match getopts(["--test".to_owned(), "--cfg=test".to_owned()],
optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
"system linker to link outputs with"),
link_args: Vec<~str> = (Vec::new(), parse_list,
"extra arguments to pass to the linker (space separated)"),
- target_cpu: ~str = (~"generic", parse_string,
+ target_cpu: ~str = ("generic".to_owned(), parse_string,
"select target processor (llc -mcpu=help for details)"),
- target_feature: ~str = (~"", parse_string,
+ target_feature: ~str = ("".to_owned(), parse_string,
"target specific attributes (llc -mattr=help for details)"),
passes: Vec<~str> = (Vec::new(), parse_list,
"a list of extra LLVM passes to run (space separated)"),
"prefer dynamic linking to static linking"),
no_integrated_as: bool = (false, parse_bool,
"use an external assembler rather than LLVM's integrated one"),
- relocation_model: ~str = (~"pic", parse_string,
+ relocation_model: ~str = ("pic".to_owned(), parse_string,
"choose the relocation model to use (llc -relocation-model for details)"),
)
session.add_lint(lint::UnknownCrateType,
ast::CRATE_NODE_ID,
a.span,
- ~"invalid `crate_type` value");
+ "invalid `crate_type` value".to_owned());
None
}
_ => {
session.add_lint(lint::UnknownCrateType, ast::CRATE_NODE_ID,
- a.span, ~"`crate_type` requires a value");
+ a.span, "`crate_type` requires a value".to_owned());
None
}
}
sess.add_lint(lint::UnknownFeatures,
ast::CRATE_NODE_ID,
mi.span,
- ~"unknown feature");
+ "unknown feature".to_owned());
}
}
}
cx.ext_cx.bt_push(ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
- name: ~"test",
+ name: "test".to_owned(),
format: MacroAttribute,
span: None
}
let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
matches.opt_strs("warn").as_slice());
- if lint_flags.iter().any(|x| x == &~"help") {
+ if lint_flags.iter().any(|x| x == &"help".to_owned()) {
describe_warnings();
return;
}
let r = matches.opt_strs("Z");
- if r.iter().any(|x| x == &~"help") {
+ if r.iter().any(|x| x == &"help".to_owned()) {
describe_debug_flags();
return;
}
let cg_flags = matches.opt_strs("C");
- if cg_flags.iter().any(|x| x == &~"help") {
+ if cg_flags.iter().any(|x| x == &"help".to_owned()) {
describe_codegen_flags();
return;
}
- if cg_flags.contains(&~"passes=list") {
+ if cg_flags.contains(&"passes=list".to_owned()) {
unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); }
return;
}
}
let xs = [
- ~"the compiler hit an unexpected failure path. this is a bug.",
+ "the compiler hit an unexpected failure path. this is a bug.".to_owned(),
"we would appreciate a bug report: " + BUG_REPORT_URL,
- ~"run with `RUST_BACKTRACE=1` for a backtrace",
+ "run with `RUST_BACKTRACE=1` for a backtrace".to_owned(),
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
}
#[cfg(target_word_size = "64")]
- fn primary_libdir_name() -> ~str { ~"lib64" }
+ fn primary_libdir_name() -> ~str { "lib64".to_owned() }
#[cfg(target_word_size = "32")]
- fn primary_libdir_name() -> ~str { ~"lib32" }
+ fn primary_libdir_name() -> ~str { "lib32".to_owned() }
- fn secondary_libdir_name() -> ~str { ~"lib" }
+ fn secondary_libdir_name() -> ~str { "lib".to_owned() }
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> ~str {
- ~"bin"
+ "bin".to_owned()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> ~str {
- ~"rustlib"
+ "rustlib".to_owned()
}
if restr.loan_path != loan2.loan_path { continue; }
let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
- ~"it"
+ "it".to_owned()
} else {
format!("`{}`",
self.bccx.loan_path_to_str(old_loan.loan_path))
ExprCast(_, _) => {
let ety = ty::expr_ty(v.tcx, e);
if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
- v.tcx.sess.span_err(e.span, ~"can not cast to `" +
+ v.tcx.sess.span_err(e.span, "can not cast to `".to_owned() +
ppaux::ty_to_str(v.tcx, ety) +
"` in a constant expression");
}
match ty::get(ty).sty {
ty::ty_bool => {
match *ctor {
- val(const_bool(true)) => Some(~"true"),
- val(const_bool(false)) => Some(~"false"),
+ val(const_bool(true)) => Some("true".to_owned()),
+ val(const_bool(false)) => Some("false".to_owned()),
_ => None
}
}
}
}
};
- let msg = ~"non-exhaustive patterns" + match ext {
+ let msg = "non-exhaustive patterns".to_owned() + match ext {
Some(ref s) => format!(": {} not covered", *s),
- None => ~""
+ None => "".to_owned()
};
cx.tcx.sess.span_err(sp, msg);
}
ty::ty_enum(did, _) => {
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
- Some(~"static items are not allowed to have destructors"));
+ Some("static items are not allowed to have destructors".to_owned()));
return;
}
}
Ok(const_float(f)) => Ok(const_float(-f)),
Ok(const_int(i)) => Ok(const_int(-i)),
Ok(const_uint(i)) => Ok(const_uint(-i)),
- Ok(const_str(_)) => Err(~"negate on string"),
- Ok(const_bool(_)) => Err(~"negate on boolean"),
+ Ok(const_str(_)) => Err("negate on string".to_owned()),
+ Ok(const_bool(_)) => Err("negate on boolean".to_owned()),
ref err => ((*err).clone())
}
}
Ok(const_int(i)) => Ok(const_int(!i)),
Ok(const_uint(i)) => Ok(const_uint(!i)),
Ok(const_bool(b)) => Ok(const_bool(!b)),
- _ => Err(~"not on float or string")
+ _ => Err("not on float or string".to_owned())
}
}
ExprBinary(op, a, b) => {
BiNe => fromb(a != b),
BiGe => fromb(a >= b),
BiGt => fromb(a > b),
- _ => Err(~"can't do this op on floats")
+ _ => Err("can't do this op on floats".to_owned())
}
}
(Ok(const_int(a)), Ok(const_int(b))) => {
BiAdd => Ok(const_int(a + b)),
BiSub => Ok(const_int(a - b)),
BiMul => Ok(const_int(a * b)),
- BiDiv if b == 0 => Err(~"attempted to divide by zero"),
+ BiDiv if b == 0 => Err("attempted to divide by zero".to_owned()),
BiDiv => Ok(const_int(a / b)),
- BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
+ BiRem if b == 0 => Err("attempted remainder with a divisor of zero".to_owned()),
BiRem => Ok(const_int(a % b)),
BiAnd | BiBitAnd => Ok(const_int(a & b)),
BiOr | BiBitOr => Ok(const_int(a | b)),
BiAdd => Ok(const_uint(a + b)),
BiSub => Ok(const_uint(a - b)),
BiMul => Ok(const_uint(a * b)),
- BiDiv if b == 0 => Err(~"attempted to divide by zero"),
+ BiDiv if b == 0 => Err("attempted to divide by zero".to_owned()),
BiDiv => Ok(const_uint(a / b)),
- BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
+ BiRem if b == 0 => Err("attempted remainder with a divisor of zero".to_owned()),
BiRem => Ok(const_uint(a % b)),
BiAnd | BiBitAnd => Ok(const_uint(a & b)),
BiOr | BiBitOr => Ok(const_uint(a | b)),
match op {
BiShl => Ok(const_int(a << b)),
BiShr => Ok(const_int(a >> b)),
- _ => Err(~"can't do this op on an int and uint")
+ _ => Err("can't do this op on an int and uint".to_owned())
}
}
(Ok(const_uint(a)), Ok(const_int(b))) => {
match op {
BiShl => Ok(const_uint(a << b)),
BiShr => Ok(const_uint(a >> b)),
- _ => Err(~"can't do this op on a uint and int")
+ _ => Err("can't do this op on a uint and int".to_owned())
}
}
(Ok(const_bool(a)), Ok(const_bool(b))) => {
BiBitOr => a | b,
BiEq => a == b,
BiNe => a != b,
- _ => return Err(~"can't do this op on bools")
+ _ => return Err("can't do this op on bools".to_owned())
}))
}
- _ => Err(~"bad operands for binary")
+ _ => Err("bad operands for binary".to_owned())
}
}
ExprCast(base, target_ty) => {
const_uint(u) => Ok(const_float(u as f64)),
const_int(i) => Ok(const_float(i as f64)),
const_float(f) => Ok(const_float(f)),
- _ => Err(~"can't cast float to str"),
+ _ => Err("can't cast float to str".to_owned()),
}
}
ty::ty_uint(_) => {
const_uint(u) => Ok(const_uint(u)),
const_int(i) => Ok(const_uint(i as u64)),
const_float(f) => Ok(const_uint(f as u64)),
- _ => Err(~"can't cast str to uint"),
+ _ => Err("can't cast str to uint".to_owned()),
}
}
ty::ty_int(_) | ty::ty_bool => {
const_uint(u) => Ok(const_int(u as i64)),
const_int(i) => Ok(const_int(i)),
const_float(f) => Ok(const_int(f as i64)),
- _ => Err(~"can't cast str to int"),
+ _ => Err("can't cast str to int".to_owned()),
}
}
- _ => Err(~"can't cast this type")
+ _ => Err("can't cast this type".to_owned())
}
}
}
ExprPath(_) => {
match lookup_const(tcx.ty_ctxt(), e) {
Some(actual_e) => eval_const_expr_partial(tcx.ty_ctxt(), actual_e),
- None => Err(~"non-constant path in constant expr")
+ None => Err("non-constant path in constant expr".to_owned())
}
}
ExprLit(lit) => Ok(lit_to_const(lit)),
// If we have a vstore, just keep going; it has to be a string
ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
ExprParen(e) => eval_const_expr_partial(tcx, e),
- _ => Err(~"unsupported constant expr")
+ _ => Err("unsupported constant expr".to_owned())
}
}
let gens_str = if gens.iter().any(|&u| u != 0) {
format!(" gen: {}", bits_to_str(gens))
} else {
- ~""
+ "".to_owned()
};
let kills = self.kills.slice(start, end);
let kills_str = if kills.iter().any(|&u| u != 0) {
format!(" kill: {}", bits_to_str(kills))
} else {
- ~""
+ "".to_owned()
};
try!(ps.synth_comment(format!("id {}: {}{}{}", id, entry_str,
FreeVarNode(s) => format!("Free var node [{}]", cm.span_to_str(s)),
ExprNode(s) => format!("Expr node [{}]", cm.span_to_str(s)),
VarDefNode(s) => format!("Var def node [{}]", cm.span_to_str(s)),
- ExitNode => ~"Exit node"
+ ExitNode => "Exit node".to_owned()
}
}
&Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
token::get_ident(nm).get().to_str()
},
- &ImplicitRet => ~"<implicit-ret>"
+ &ImplicitRet => "<implicit-ret>".to_owned()
}
}
pub fn cmt_to_str(&self, cmt: cmt) -> ~str {
match cmt.cat {
cat_static_item => {
- ~"static item"
+ "static item".to_owned()
}
cat_copied_upvar(_) => {
- ~"captured outer variable in a proc"
+ "captured outer variable in a proc".to_owned()
}
cat_rvalue(..) => {
- ~"non-lvalue"
+ "non-lvalue".to_owned()
}
cat_local(_) => {
- ~"local variable"
+ "local variable".to_owned()
}
cat_arg(..) => {
- ~"argument"
+ "argument".to_owned()
}
cat_deref(base, _, pk) => {
match base.cat {
}
}
cat_interior(_, InteriorField(NamedField(_))) => {
- ~"field"
+ "field".to_owned()
}
cat_interior(_, InteriorField(PositionalField(_))) => {
- ~"anonymous field"
+ "anonymous field".to_owned()
}
cat_interior(_, InteriorElement(VecElement)) => {
- ~"vec content"
+ "vec content".to_owned()
}
cat_interior(_, InteriorElement(StrElement)) => {
- ~"str content"
+ "str content".to_owned()
}
cat_interior(_, InteriorElement(OtherElement)) => {
- ~"indexed content"
+ "indexed content".to_owned()
}
cat_upvar(..) => {
- ~"captured outer variable"
+ "captured outer variable".to_owned()
}
cat_discr(cmt, _) => {
self.cmt_to_str(cmt)
token::get_name(fld).get().to_str()
}
InteriorField(PositionalField(i)) => format!("\\#{:?}", i),
- InteriorElement(_) => ~"[]",
+ InteriorElement(_) => "[]".to_owned(),
}
}
}
if self.path_is_private_type(path_id) {
self.tcx.sess.add_lint(lint::VisiblePrivateTypes,
path_id, p.span,
- ~"private type in exported type signature");
+ "private type in exported type signature".to_owned());
}
}
_ => {}
SingleImport(_, source) => {
token::get_ident(source).get().to_str()
}
- GlobImport => ~"*"
+ GlobImport => "*".to_owned()
}
}
self.session.add_lint(UnnecessaryQualification,
id,
path.span,
- ~"unnecessary qualification");
+ "unnecessary qualification".to_owned());
}
_ => ()
}
ViewPathGlob(_, id) => {
if !self.used_imports.contains(&(id, TypeNS)) &&
!self.used_imports.contains(&(id, ValueNS)) {
- self.session.add_lint(UnusedImports, id, p.span, ~"unused import");
+ self.session.add_lint(UnusedImports, id, p.span,
+ "unused import".to_owned());
}
},
}
if !self.used_imports.contains(&(id, TypeNS)) &&
!self.used_imports.contains(&(id, ValueNS)) {
- self.session.add_lint(UnusedImports, id, span, ~"unused import");
+ self.session.add_lint(UnusedImports, id, span, "unused import".to_owned());
}
let (v_priv, t_priv) = match self.last_private.find(&id) {
}
if idents.len() == 0 {
- return ~"???";
+ return "???".to_owned();
}
return self.idents_to_str(idents.move_iter()
.rev()
for (&name, import_resolution) in import_resolutions.iter() {
let value_repr;
match import_resolution.target_for_namespace(ValueNS) {
- None => { value_repr = ~""; }
+ None => { value_repr = "".to_owned(); }
Some(_) => {
- value_repr = ~" value:?";
+ value_repr = " value:?".to_owned();
// FIXME #4954
}
}
let type_repr;
match import_resolution.target_for_namespace(TypeNS) {
- None => { type_repr = ~""; }
+ None => { type_repr = "".to_owned(); }
Some(_) => {
- type_repr = ~" type:?";
+ type_repr = " type:?".to_owned();
// FIXME #4954
}
}
let root_msg = match self.root_ty {
Some(root) => format!(" in the substitution of `{}`",
root.repr(self.tcx)),
- None => ~""
+ None => "".to_owned()
};
let m = format!("can't use type parameters from outer \
function{}; try using a local type \
let root_msg = match self.root_ty {
Some(root) => format!(" in the substitution of `{}`",
root.repr(self.tcx)),
- None => ~""
+ None => "".to_owned()
};
let m = format!("missing `Self` type param{}", root_msg);
match self.span {
#[cfg(target_arch = "arm")]
#[cfg(target_arch = "mips")]
fn getClobbers() -> ~str {
- ~""
+ "".to_owned()
}
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
fn getClobbers() -> ~str {
- ~"~{dirflag},~{fpsr},~{flags}"
+ "~{dirflag},~{fpsr},~{flags}".to_owned()
}
// silently mangles such symbols, breaking our linkage model.
pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
if ccx.all_llvm_symbols.borrow().contains(&sym) {
- ccx.sess().bug(~"duplicate LLVM symbol: " + sym);
+ ccx.sess().bug("duplicate LLVM symbol: ".to_owned() + sym);
}
ccx.all_llvm_symbols.borrow_mut().insert(sym);
}
for variant in (*variants).iter() {
let variant_cx =
- fcx.new_temp_block(~"enum-iter-variant-" +
+ fcx.new_temp_block("enum-iter-variant-".to_owned() +
variant.disr_val.to_str());
match adt::trans_case(cx, repr, variant.disr_val) {
_match::single_result(r) => {
ICmp(cx, lib::llvm::IntEQ, rhs, zero)
}
_ => {
- cx.sess().bug(~"fail-if-zero on unexpected type: " +
+ cx.sess().bug("fail-if-zero on unexpected type: ".to_owned() +
ty_to_str(cx.tcx(), rhs_t));
}
};
for p in param_substs.iter() { p.validate(); }
debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
- if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
+ if id == -1 { "".to_owned() } else { ccx.tcx.map.path_to_str(id) },
id, param_substs.repr(ccx.tcx()));
let substd_output_type = match param_substs {
// symbol. This symbol is required for use by the libmorestack library that
// we link in, so we must ensure that this symbol is not internalized (if
// defined in the crate).
- reachable.push(~"main");
- reachable.push(~"rust_stack_exhausted");
- reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
- reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
+ reachable.push("main".to_owned());
+ reachable.push("rust_stack_exhausted".to_owned());
+
+ // referenced from .eh_frame section on some platforms
+ reachable.push("rust_eh_personality".to_owned());
+ reachable.push("rust_eh_personality_catch".to_owned()); // referenced from rt/rust_try.ll
let metadata_module = ccx.metadata_llmod;
impl EnvAction {
pub fn to_str(&self) -> ~str {
match *self {
- EnvCopy => ~"EnvCopy",
- EnvMove => ~"EnvMove",
- EnvRef => ~"EnvRef"
+ EnvCopy => "EnvCopy".to_owned(),
+ EnvMove => "EnvMove".to_owned(),
+ EnvRef => "EnvRef".to_owned()
}
}
}
debug!("basic_type_metadata: {:?}", ty::get(t));
let (name, encoding) = match ty::get(t).sty {
- ty::ty_nil => (~"()", DW_ATE_unsigned),
- ty::ty_bot => (~"!", DW_ATE_unsigned),
- ty::ty_bool => (~"bool", DW_ATE_boolean),
- ty::ty_char => (~"char", DW_ATE_unsigned_char),
+ ty::ty_nil => ("()".to_owned(), DW_ATE_unsigned),
+ ty::ty_bot => ("!".to_owned(), DW_ATE_unsigned),
+ ty::ty_bool => ("bool".to_owned(), DW_ATE_boolean),
+ ty::ty_char => ("char".to_owned(), DW_ATE_unsigned_char),
ty::ty_int(int_ty) => match int_ty {
- ast::TyI => (~"int", DW_ATE_signed),
- ast::TyI8 => (~"i8", DW_ATE_signed),
- ast::TyI16 => (~"i16", DW_ATE_signed),
- ast::TyI32 => (~"i32", DW_ATE_signed),
- ast::TyI64 => (~"i64", DW_ATE_signed)
+ ast::TyI => ("int".to_owned(), DW_ATE_signed),
+ ast::TyI8 => ("i8".to_owned(), DW_ATE_signed),
+ ast::TyI16 => ("i16".to_owned(), DW_ATE_signed),
+ ast::TyI32 => ("i32".to_owned(), DW_ATE_signed),
+ ast::TyI64 => ("i64".to_owned(), DW_ATE_signed)
},
ty::ty_uint(uint_ty) => match uint_ty {
- ast::TyU => (~"uint", DW_ATE_unsigned),
- ast::TyU8 => (~"u8", DW_ATE_unsigned),
- ast::TyU16 => (~"u16", DW_ATE_unsigned),
- ast::TyU32 => (~"u32", DW_ATE_unsigned),
- ast::TyU64 => (~"u64", DW_ATE_unsigned)
+ ast::TyU => ("uint".to_owned(), DW_ATE_unsigned),
+ ast::TyU8 => ("u8".to_owned(), DW_ATE_unsigned),
+ ast::TyU16 => ("u16".to_owned(), DW_ATE_unsigned),
+ ast::TyU32 => ("u32".to_owned(), DW_ATE_unsigned),
+ ast::TyU64 => ("u64".to_owned(), DW_ATE_unsigned)
},
ty::ty_float(float_ty) => match float_ty {
- ast::TyF32 => (~"f32", DW_ATE_float),
- ast::TyF64 => (~"f64", DW_ATE_float)
+ ast::TyF32 => ("f32".to_owned(), DW_ATE_float),
+ ast::TyF64 => ("f64".to_owned(), DW_ATE_float)
},
_ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
};
-> Vec<MemberDescription> {
self.fields.iter().map(|field| {
let name = if field.ident.name == special_idents::unnamed_field.name {
- ~""
+ "".to_owned()
} else {
token::get_ident(field.ident).get().to_str()
};
-> Vec<MemberDescription> {
self.component_types.iter().map(|&component_type| {
MemberDescription {
- name: ~"",
+ name: "".to_owned(),
llvm_type: type_of::type_of(cx, component_type),
type_metadata: type_metadata(cx, component_type, self.span),
offset: ComputedMemberOffset,
self.file_metadata,
codemap::DUMMY_SP);
MemberDescription {
- name: ~"",
+ name: "".to_owned(),
llvm_type: variant_llvm_type,
type_metadata: variant_type_metadata,
offset: FixedMemberOffset { bytes: 0 },
Some(ref names) => {
names.iter().map(|ident| token::get_ident(*ident).get().to_str()).collect()
}
- None => variant_info.args.iter().map(|_| ~"").collect()
+ None => variant_info.args.iter().map(|_| "".to_owned()).collect()
};
// If this is not a univariant enum, there is also the (unnamed) discriminant field
if discriminant_type_metadata.is_some() {
- arg_names.insert(0, ~"");
+ arg_names.insert(0, "".to_owned());
}
// Build an array of (field name, field type) pairs to be captured in the factory closure.
-> DICompositeType {
let box_type_name = match content_type_name {
Some(content_type_name) => format!("Boxed<{}>", content_type_name),
- None => ~"BoxedType"
+ None => "BoxedType".to_owned()
};
let box_llvm_type = Type::at_box(cx, content_llvm_type);
let member_descriptions = [
MemberDescription {
- name: ~"refcnt",
+ name: "refcnt".to_owned(),
llvm_type: *member_llvm_types.get(0),
type_metadata: type_metadata(cx, int_type, codemap::DUMMY_SP),
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"drop_glue",
+ name: "drop_glue".to_owned(),
llvm_type: *member_llvm_types.get(1),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"prev",
+ name: "prev".to_owned(),
llvm_type: *member_llvm_types.get(2),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"next",
+ name: "next".to_owned(),
llvm_type: *member_llvm_types.get(3),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"val",
+ name: "val".to_owned(),
llvm_type: *member_llvm_types.get(4),
type_metadata: content_type_metadata,
offset: ComputedMemberOffset,
let member_descriptions = [
MemberDescription {
- name: ~"fill",
+ name: "fill".to_owned(),
llvm_type: *member_llvm_types.get(0),
type_metadata: int_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"alloc",
+ name: "alloc".to_owned(),
llvm_type: *member_llvm_types.get(1),
type_metadata: int_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"elements",
+ name: "elements".to_owned(),
llvm_type: *member_llvm_types.get(2),
type_metadata: array_type_metadata,
offset: ComputedMemberOffset,
let member_descriptions = [
MemberDescription {
- name: ~"data_ptr",
+ name: "data_ptr".to_owned(),
llvm_type: *member_llvm_types.get(0),
type_metadata: type_metadata(cx, data_ptr_type, span),
offset: ComputedMemberOffset,
},
MemberDescription {
- name: ~"length",
+ name: "length".to_owned(),
llvm_type: *member_llvm_types.get(1),
type_metadata: type_metadata(cx, ty::mk_uint(), span),
offset: ComputedMemberOffset,
pub fn to_str(&self, ccx: &CrateContext) -> ~str {
match *self {
SaveIn(v) => format!("SaveIn({})", ccx.tn.val_to_str(v)),
- Ignore => ~"Ignore"
+ Ignore => "Ignore".to_owned()
}
}
}
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_" + name);
+ let fn_nm = mangle_internal_name_by_type_and_seq(ccx, t, "glue_".to_owned() + name);
debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t));
let llfn = decl_cdecl_fn(ccx.llmod, fn_nm, llfnty, ty::mk_nil());
note_unique_llvm_symbol(ccx, fn_nm);
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_" + ty_name),
+ let mth_idx = ty::method_idx(token::str_to_ident("visit_".to_owned() + ty_name),
self.visitor_methods.as_slice()).expect(
format!("couldn't find visit method for {}", ty_name));
let mth_ty =
match vstore {
ty::VstoreFixed(n) => {
let extra = (vec!(self.c_uint(n))).append(self.c_size_and_align(t).as_slice());
- (~"fixed", extra)
+ ("fixed".to_owned(), extra)
}
- ty::VstoreSlice(..) => (~"slice", Vec::new()),
- ty::VstoreUniq => (~"uniq", Vec::new()),
+ ty::VstoreSlice(..) => ("slice".to_owned(), Vec::new()),
+ ty::VstoreUniq => ("uniq".to_owned(), Vec::new()),
}
}
// Should rename to str_*/vec_*.
ty::ty_str(vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
- self.visit(~"estr_" + name, extra.as_slice())
+ self.visit("estr_".to_owned() + name, extra.as_slice())
}
ty::ty_vec(ty, vst) => {
let (name, extra) = self.vstore_name_and_extra(t, vst);
_ => ast::MutImmutable
}
}).as_slice());
- self.visit(~"evec_" + name, extra.as_slice())
+ self.visit("evec_".to_owned() + name, extra.as_slice())
}
// Should remove mt from box and uniq.
ty::ty_box(typ) => {
content_expr: &ast::Expr)
-> DatumBlock<'a, Expr> {
/*!
- * ~[...] and ~"..." allocate boxes in the exchange heap and write
+ * ~[...] and "...".to_owned() allocate boxes in the exchange heap and write
* the array elements into them.
*/
let fcx = bcx.fcx;
let ccx = fcx.ccx;
- // Handle ~"".
+ // Handle "".to_owned().
match content_expr.node {
ast::ExprLit(lit) => {
match lit.node {
}
ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
- ty_box(_) => ~"@-ptr",
- ty_uniq(_) => ~"~-ptr",
- ty_vec(_, _) => ~"vector",
- ty_ptr(_) => ~"*-ptr",
- ty_rptr(_, _) => ~"&-ptr",
- ty_bare_fn(_) => ~"extern fn",
- ty_closure(_) => ~"fn",
+ ty_box(_) => "@-ptr".to_owned(),
+ ty_uniq(_) => "~-ptr".to_owned(),
+ ty_vec(_, _) => "vector".to_owned(),
+ ty_ptr(_) => "*-ptr".to_owned(),
+ ty_rptr(_, _) => "&-ptr".to_owned(),
+ ty_bare_fn(_) => "extern fn".to_owned(),
+ ty_closure(_) => "fn".to_owned(),
ty_trait(ref inner) => format!("trait {}", item_path_str(cx, inner.def_id)),
ty_struct(id, _) => format!("struct {}", item_path_str(cx, id)),
- ty_tup(_) => ~"tuple",
- ty_infer(TyVar(_)) => ~"inferred type",
- ty_infer(IntVar(_)) => ~"integral variable",
- ty_infer(FloatVar(_)) => ~"floating-point variable",
- ty_param(_) => ~"type parameter",
- ty_self(_) => ~"self",
- ty_err => ~"type error"
+ ty_tup(_) => "tuple".to_owned(),
+ ty_infer(TyVar(_)) => "inferred type".to_owned(),
+ ty_infer(IntVar(_)) => "integral variable".to_owned(),
+ ty_infer(FloatVar(_)) => "floating-point variable".to_owned(),
+ ty_param(_) => "type parameter".to_owned(),
+ ty_self(_) => "self".to_owned(),
+ ty_err => "type error".to_owned()
}
}
fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
match k {
- terr_vec => ~"[]",
- terr_str => ~"str",
- terr_fn => ~"fn",
- terr_trait => ~"trait"
+ terr_vec => "[]".to_owned(),
+ terr_str => "str".to_owned(),
+ terr_fn => "fn".to_owned(),
+ terr_trait => "trait".to_owned()
}
}
match *err {
- terr_mismatch => ~"types differ",
+ terr_mismatch => "types differ".to_owned(),
terr_fn_style_mismatch(values) => {
format!("expected {} fn but found {} fn",
values.expected.to_str(), values.found.to_str())
values.expected.to_str(),
values.found.to_str())
}
- terr_mutability => ~"values differ in mutability",
- terr_box_mutability => ~"boxed values differ in mutability",
- terr_vec_mutability => ~"vectors differ in mutability",
- terr_ptr_mutability => ~"pointers differ in mutability",
- terr_ref_mutability => ~"references differ in mutability",
+ terr_mutability => "values differ in mutability".to_owned(),
+ terr_box_mutability => "boxed values differ in mutability".to_owned(),
+ terr_vec_mutability => "vectors differ in mutability".to_owned(),
+ terr_ptr_mutability => "pointers differ in mutability".to_owned(),
+ terr_ref_mutability => "references differ in mutability".to_owned(),
terr_ty_param_size(values) => {
format!("expected a type with {} type params \
but found one with {} type params",
values.expected, values.found)
}
terr_record_mutability => {
- ~"record elements differ in mutability"
+ "record elements differ in mutability".to_owned()
}
terr_record_fields(values) => {
format!("expected a record with field `{}` but found one with field \
token::get_ident(values.expected),
token::get_ident(values.found))
}
- terr_arg_count => ~"incorrect number of function parameters",
+ terr_arg_count => "incorrect number of function parameters".to_owned(),
terr_regions_does_not_outlive(..) => {
format!("lifetime mismatch")
}
// See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs
fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
- expected.map_or(~"", |e| {
+ expected.map_or("".to_owned(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)})},
- Some(expected), ~"a structure pattern",
+ Some(expected), "a structure pattern".to_owned(),
None);
fcx.write_error(pat.id);
kind_name = "[error]";
// See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs
fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
- expected.map_or(~"", |e| {
+ expected.map_or("".to_owned(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)})},
- Some(expected), ~"an enum or structure pattern",
+ Some(expected), "an enum or structure pattern".to_owned(),
None);
fcx.write_error(pat.id);
kind_name = "[error]";
debug!("pat_range ending type: {:?}", e_ty);
if !require_same_types(
tcx, Some(fcx.infcx()), false, pat.span, b_ty, e_ty,
- || ~"mismatched types in range")
+ || "mismatched types in range".to_owned())
{
// no-op
} else if !ty::type_is_numeric(b_ty) && !ty::type_is_char(b_ty) {
// See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs
fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
- expected.map_or(~"", |e| {
+ expected.map_or("".to_owned(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)})},
- Some(expected), ~"a structure pattern",
+ Some(expected), "a structure pattern".to_owned(),
None);
match tcx.def_map.borrow().find(&pat.id) {
Some(&ast::DefStruct(supplied_def_id)) => {
};
// See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs
fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| {
- expected.map_or(~"", |e| {
- format!("mismatched types: expected `{}` but found {}",
- e, actual)})}, Some(expected), ~"tuple", Some(&type_error));
+ expected.map_or("".to_owned(), |e| {
+ format!("mismatched types: expected `{}` but found {}",
+ e, actual)})},
+ Some(expected), "tuple".to_owned(), Some(&type_error));
fcx.write_error(pat.id);
}
}
fcx.infcx().type_error_message_str_with_expected(
pat.span,
|expected, actual| {
- expected.map_or(~"", |e| {
+ expected.map_or("".to_owned(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)})},
Some(expected),
- ~"a vector pattern",
+ "a vector pattern".to_owned(),
None);
fcx.write_error(pat.id);
return;
fcx.infcx().type_error_message_str_with_expected(
span,
|expected, actual| {
- expected.map_or(~"", |e| {
+ expected.map_or("".to_owned(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)})},
Some(expected),
let name = class_field.name;
let (_, seen) = *class_field_map.get(&name);
if !seen {
- missing_fields.push(~"`" + token::get_name(name).get() + "`");
+ missing_fields.push("`".to_owned() + token::get_name(name).get() + "`");
}
}
ppaux::ty_to_str(tcx, fcx.expr_ty(expr)),
match expected {
Some(t) => ppaux::ty_to_str(tcx, t),
- _ => ~"empty"
+ _ => "empty".to_owned()
});
unifier();
_ => false
} {
fcx.ccx.tcx.sess.add_lint(UnreachableCode, s_id, s.span,
- ~"unreachable statement");
+ "unreachable statement".to_owned());
warned = true;
}
if ty::type_is_bot(s_ty) {
Some(e) => {
if any_bot && !warned {
fcx.ccx.tcx.sess.add_lint(UnreachableCode, e.id, e.span,
- ~"unreachable expression");
+ "unreachable expression".to_owned());
}
check_expr_with_opt_hint(fcx, e, expected);
let ety = fcx.expr_ty(e);
Ok(t_s) if !ty::type_is_ty_var(t_s) => t_s,
_ => {
fcx.type_error_message(sp, |_actual| {
- ~"the type of this value must be known in this context"
+ "the type of this value must be known in this context".to_owned()
}, tp, None);
demand::suptype(fcx, sp, ty::mk_err(), tp);
tp
fn report_inference_failure(&self,
var_origin: RegionVariableOrigin) {
let var_description = match var_origin {
- infer::MiscVariable(_) => ~"",
- infer::PatternRegion(_) => ~" for pattern",
- infer::AddrOfRegion(_) => ~" for borrow expression",
- infer::AddrOfSlice(_) => ~" for slice expression",
- infer::Autoref(_) => ~" for autoref",
- infer::Coercion(_) => ~" for automatic coercion",
+ infer::MiscVariable(_) => "".to_owned(),
+ infer::PatternRegion(_) => " for pattern".to_owned(),
+ infer::AddrOfRegion(_) => " for borrow expression".to_owned(),
+ infer::AddrOfSlice(_) => " for slice expression".to_owned(),
+ infer::Autoref(_) => " for autoref".to_owned(),
+ infer::Coercion(_) => " for automatic coercion".to_owned(),
infer::LateBoundRegion(_, br) => {
format!(" for {}in function call",
bound_region_to_str(self.tcx, "lifetime parameter ", true, br))
impl<'f> Combine for Glb<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> ~str { ~"glb" }
+ fn tag(&self) -> ~str { "glb".to_owned() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
impl<'f> Combine for Lub<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> ~str { ~"lub" }
+ fn tag(&self) -> ~str { "lub".to_owned() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
pub fn fixup_err_to_str(f: fixup_err) -> ~str {
match f {
- unresolved_int_ty(_) => ~"unconstrained integral type",
- unresolved_ty(_) => ~"unconstrained type",
- cyclic_ty(_) => ~"cyclic type of infinite size",
- unresolved_region(_) => ~"unconstrained region",
+ unresolved_int_ty(_) => "unconstrained integral type".to_owned(),
+ unresolved_ty(_) => "unconstrained type".to_owned(),
+ cyclic_ty(_) => "cyclic type of infinite size".to_owned(),
+ unresolved_region(_) => "unconstrained region".to_owned(),
region_var_bound_by_region_var(r1, r2) => {
format!("region var {:?} bound by another region var {:?}; this is \
a bug in rustc", r1, r2)
err: Option<&ty::type_err>) {
debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
- let error_str = err.map_or(~"", |t_err| {
+ let error_str = err.map_or("".to_owned(), |t_err| {
format!(" ({})", ty::type_err_to_str(self.tcx, t_err))
});
let resolved_expected = expected_ty.map(|e_ty| {
impl<'f> Combine for Sub<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> ~str { ~"sub" }
+ fn tag(&self) -> ~str { "sub".to_owned() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
fn setup_env(test_name: &str, source_string: &str) -> Env {
let messages = @DVec();
- let matches = getopts(vec!(~"-Z", ~"verbose"), optgroups()).get();
+ let matches = getopts(vec!("-Z".to_owned(), "verbose".to_owned()), optgroups()).get();
let diag = diagnostic::collect(messages);
- let sessopts = build_session_options(~"rustc", &matches, diag);
+ let sessopts = build_session_options("rustc".to_owned(), &matches, diag);
let sess = build_session(sessopts, None, diag);
- let cfg = build_configuration(sess, ~"whatever", str_input(~""));
+ let cfg = build_configuration(sess, "whatever".to_owned(), str_input("".to_owned()));
let dm = HashMap();
let amap = HashMap();
let freevars = HashMap();
fn inf_str(&self, cx: &InferCtxt) -> ~str {
match *self {
Some(ref v) => v.inf_str(cx),
- None => ~"none"
+ None => "none".to_owned()
}
}
}
}
}
- ReStatic => { (~"the static lifetime", None) }
+ ReStatic => { ("the static lifetime".to_owned(), None) }
- ReEmpty => { (~"the empty lifetime", None) }
+ ReEmpty => { ("the empty lifetime".to_owned(), None) }
// I believe these cases should not occur (except when debugging,
// perhaps)
pub fn mutability_to_str(m: ast::Mutability) -> ~str {
match m {
- ast::MutMutable => ~"mut ",
- ast::MutImmutable => ~"",
+ ast::MutMutable => "mut ".to_owned(),
+ ast::MutImmutable => "".to_owned(),
}
}
pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> ~str {
match s {
- ty::UniqTraitStore => ~"~",
+ ty::UniqTraitStore => "~".to_owned(),
ty::RegionTraitStore(r, m) => {
format!("{}{}", region_ptr_to_str(cx, r), mutability_to_str(m))
}
// pretty print the structural type representation:
return match ty::get(typ).sty {
- ty_nil => ~"()",
- ty_bot => ~"!",
- ty_bool => ~"bool",
- ty_char => ~"char",
+ ty_nil => "()".to_owned(),
+ ty_bot => "!".to_owned(),
+ ty_bool => "bool".to_owned(),
+ ty_char => "char".to_owned(),
ty_int(t) => ast_util::int_ty_to_str(t, None),
ty_uint(t) => ast_util::uint_ty_to_str(t, None),
ty_float(t) => ast_util::float_ty_to_str(t),
- ty_box(typ) => ~"@" + ty_to_str(cx, typ),
- ty_uniq(typ) => ~"~" + ty_to_str(cx, typ),
- ty_ptr(ref tm) => ~"*" + mt_to_str(cx, tm),
+ ty_box(typ) => "@".to_owned() + ty_to_str(cx, typ),
+ ty_uniq(typ) => "~".to_owned() + ty_to_str(cx, typ),
+ ty_ptr(ref tm) => "*".to_owned() + mt_to_str(cx, tm),
ty_rptr(r, ref tm) => {
region_ptr_to_str(cx, r) + mt_to_str(cx, tm)
}
ty_tup(ref elems) => {
let strs: Vec<~str> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
- ~"(" + strs.connect(",") + ")"
+ "(".to_owned() + strs.connect(",") + ")"
}
ty_closure(ref f) => {
closure_to_str(cx, *f)
bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig)
}
ty_infer(infer_ty) => infer_ty.to_str(),
- ty_err => ~"[type error]",
+ ty_err => "[type error]".to_owned(),
ty_param(param_ty {idx: id, def_id: did}) => {
let ident = match cx.ty_param_defs.borrow().find(&did.node) {
Some(def) => token::get_ident(def.ident).get().to_str(),
format!("{}:{:?}", ident, did)
}
}
- ty_self(..) => ~"Self",
+ ty_self(..) => "Self".to_owned(),
ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
let base = ty::item_path_str(cx, did);
parameterized(cx,
ty_str(vs) => {
match vs {
ty::VstoreFixed(n) => format!("str/{}", n),
- ty::VstoreUniq => ~"~str",
+ ty::VstoreUniq => "~str".to_owned(),
ty::VstoreSlice(r, ()) => format!("{}str", region_ptr_to_str(cx, r))
}
}
impl<T:Repr> Repr for Option<T> {
fn repr(&self, tcx: &ctxt) -> ~str {
match self {
- &None => ~"None",
+ &None => "None".to_owned(),
&Some(ref t) => t.repr(tcx),
}
}
impl Repr for () {
fn repr(&self, _tcx: &ctxt) -> ~str {
- ~"()"
+ "()".to_owned()
}
}
impl Repr for ty::RegionSubsts {
fn repr(&self, tcx: &ctxt) -> ~str {
match *self {
- ty::ErasedRegions => ~"erased",
+ ty::ErasedRegions => "erased".to_owned(),
ty::NonerasedRegions(ref regions) => regions.repr(tcx)
}
}
let mut res = Vec::new();
for b in self.builtin_bounds.iter() {
res.push(match b {
- ty::BoundStatic => ~"'static",
- ty::BoundSend => ~"Send",
- ty::BoundSized => ~"Sized",
- ty::BoundCopy => ~"Pod",
- ty::BoundShare => ~"Share",
+ ty::BoundStatic => "'static".to_owned(),
+ ty::BoundSend => "Send".to_owned(),
+ ty::BoundSized => "Sized".to_owned(),
+ ty::BoundCopy => "Pod".to_owned(),
+ ty::BoundShare => "Share".to_owned(),
});
}
for t in self.trait_bounds.iter() {
fn repr(&self, tcx: &ctxt) -> ~str {
match *self {
ty::VstoreFixed(n) => format!("{}", n),
- ty::VstoreUniq => ~"~",
+ ty::VstoreUniq => "~".to_owned(),
ty::VstoreSlice(r, m) => {
format!("{}{}", region_ptr_to_str(tcx, r), mutability_to_str(m))
}
fn repr(&self, tcx: &ctxt) -> ~str {
match *self {
ty::VstoreFixed(n) => format!("{}", n),
- ty::VstoreUniq => ~"~",
+ ty::VstoreUniq => "~".to_owned(),
ty::VstoreSlice(r, ()) => region_ptr_to_str(tcx, r)
}
}
impl UserString for ty::BuiltinBound {
fn user_string(&self, _tcx: &ctxt) -> ~str {
match *self {
- ty::BoundStatic => ~"'static",
- ty::BoundSend => ~"Send",
- ty::BoundSized => ~"Sized",
- ty::BoundCopy => ~"Pod",
- ty::BoundShare => ~"Share",
+ ty::BoundStatic => "'static".to_owned(),
+ ty::BoundSend => "Send".to_owned(),
+ ty::BoundSized => "Sized".to_owned(),
+ ty::BoundCopy => "Pod".to_owned(),
+ ty::BoundShare => "Share".to_owned(),
}
}
}
impl UserString for ty::BuiltinBounds {
fn user_string(&self, tcx: &ctxt) -> ~str {
- if self.is_empty() { ~"<no-bounds>" } else {
+ if self.is_empty() { "<no-bounds>".to_owned() } else {
let mut result = Vec::new();
for bb in self.iter() {
result.push(bb.user_string(tcx));
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
- input: ~"",
- output_str: ~"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ input: "".to_owned(),
+ output_str: "e3b0c44298fc1c149afb\
+ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_owned()
},
Test {
- input: ~"The quick brown fox jumps over the lazy dog",
- output_str: ~"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
+ input: "The quick brown fox jumps over the lazy dog".to_owned(),
+ output_str: "d7a8fbb307d7809469ca\
+ 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_owned()
},
Test {
- input: ~"The quick brown fox jumps over the lazy dog.",
- output_str: ~"ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"
+ input: "The quick brown fox jumps over the lazy dog.".to_owned(),
+ output_str: "ef537f25c895bfa78252\
+ 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_owned()
});
let tests = wikipedia_tests;
let name = if self.name.is_some() {
self.name.unwrap().clean()
} else {
- ~""
+ "".to_owned()
};
let mut foreigns = Vec::new();
for subforeigns in self.foreigns.clean().move_iter() {
ForeignStaticItem(Static {
type_: ty.clean(),
mutability: if mutbl {Mutable} else {Immutable},
- expr: ~"",
+ expr: "".to_owned(),
})
}
};
let cm = local_data::get(super::ctxtkey, |x| x.unwrap().clone()).sess().codemap().clone();
let sn = match cm.span_to_snippet(*self) {
Some(x) => x,
- None => ~""
+ None => "".to_owned()
};
debug!("got snippet {}", sn);
sn
match lit.node {
ast::LitStr(ref st, _) => st.get().to_owned(),
ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
- ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'",
+ ast::LitChar(c) => "'".to_owned() + std::char::from_u32(c).unwrap().to_str() + "'",
ast::LitInt(i, _t) => i.to_str(),
ast::LitUint(u, _t) => u.to_str(),
ast::LitIntUnsuffixed(i) => i.to_str(),
ast::LitFloat(ref f, _t) => f.get().to_str(),
ast::LitFloatUnsuffixed(ref f) => f.get().to_str(),
ast::LitBool(b) => b.to_str(),
- ast::LitNil => ~"",
+ ast::LitNil => "".to_owned(),
}
}
debug!("Trying to get a name from pattern: {:?}", p);
match p.node {
- PatWild => ~"_",
- PatWildMulti => ~"..",
+ PatWild => "_".to_owned(),
+ PatWildMulti => "..".to_owned(),
PatIdent(_, ref p, _) => path_to_str(p),
PatEnum(ref p, _) => path_to_str(p),
PatStruct(..) => fail!("tried to get argument name from pat_struct, \
which is not allowed in function arguments"),
- PatTup(..) => ~"(tuple arg NYI)",
+ PatTup(..) => "(tuple arg NYI)".to_owned(),
PatUniq(p) => name_from_pat(p),
PatRegion(p) => name_from_pat(p),
PatLit(..) => {
warn!("tried to get argument name from PatLit, \
which is silly in function arguments");
- ~"()"
+ "()".to_owned()
},
PatRange(..) => fail!("tried to get argument name from PatRange, \
which is not allowed in function arguments"),
let cache = cache.unwrap();
let abs_root = root(&**cache, loc.as_slice());
let rel_root = match path.segments.get(0).name.as_slice() {
- "self" => Some(~"./"),
+ "self" => Some("./".to_owned()),
_ => None,
};
{arrow, select, yes{ -> {ret}} other{}}",
style = FnStyleSpace(decl.fn_style),
lifetimes = if decl.lifetimes.len() == 0 {
- ~""
+ "".to_owned()
} else {
format!("<{:#}>", decl.lifetimes)
},
{arrow, select, yes{ -> {ret}} other{}}",
style = FnStyleSpace(decl.fn_style),
lifetimes = if decl.lifetimes.len() == 0 {
- ~""
+ "".to_owned()
} else {
format!("<{:#}>", decl.lifetimes)
},
args = decl.decl.inputs,
bounds = if decl.bounds.len() == 0 {
- ~""
+ "".to_owned()
} else {
let mut m = decl.bounds.iter().map(|s| s.to_str());
": " + m.collect::<~[~str]>().connect(" + ")
write!(f.buf, "{}{}fn{}{}",
FnStyleSpace(decl.fn_style),
match decl.abi {
- ref x if "" == *x => ~"",
- ref x if "\"Rust\"" == *x => ~"",
+ ref x if "" == *x => "".to_owned(),
+ ref x if "\"Rust\"" == *x => "".to_owned(),
ref s => " " + *s + " ",
},
decl.generics,
}, **t)
}
clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
- let lt = match *l { Some(ref l) => format!("{} ", *l), _ => ~"" };
+ let lt = match *l { Some(ref l) => format!("{} ", *l), _ => "".to_owned() };
write!(f.buf, "&{}{}{}",
lt,
match mutability {
/// Highlights some source code, returning the HTML output.
pub fn highlight(src: &str, class: Option<&str>) -> ~str {
let sess = parse::new_parse_sess();
- let fm = parse::string_to_filemap(&sess, src.to_owned(), ~"<stdin>");
+ let fm = parse::string_to_filemap(&sess, src.to_owned(), "<stdin>".to_owned());
let mut out = io::MemWriter::new();
doit(&sess,
// Extract the text provided
let s = if text.is_null() {
- ~""
+ "".to_owned()
} else {
unsafe {
str::raw::from_buf_len((*text).data, (*text).size as uint)
root_path: StrBuf::new(),
sidebar: HashMap::new(),
layout: layout::Layout {
- logo: ~"",
- favicon: ~"",
+ logo: "".to_owned(),
+ favicon: "".to_owned(),
krate: krate.name.clone(),
},
include_sources: true,
let mut w = MemWriter::new();
try!(write!(&mut w, r#"searchIndex['{}'] = \{"items":["#, krate.name));
- let mut lastpath = ~"";
+ let mut lastpath = "".to_owned();
for (i, item) in cache.search_index.iter().enumerate() {
// Omit the path if it is same to that of the prior item.
let path;
// there's been no macro mistake.
macro_rules! push {
($level: expr, $name: expr) => {
- assert_eq!(builder.push($level, $name.to_owned(), ~""), $name);
+ assert_eq!(builder.push($level, $name.to_owned(), "".to_owned()), $name);
}
}
push!(2, "0.1");
level: $level,
name: $name.to_owned(),
sec_number: $name.to_owned(),
- id: ~"",
+ id: "".to_owned(),
children: toc!($($sub),*)
}
),*
(false, false) => {}
}
- if matches.opt_strs("passes").as_slice() == &[~"list"] {
+ if matches.opt_strs("passes").as_slice() == &["list".to_owned()] {
println!("Available passes for running rustdoc:");
for &(name, _, description) in PASSES.iter() {
println!("{:>20s} - {}", name, description);
}
// Load all plugins/passes into a PluginManager
- let path = matches.opt_str("plugin-path").unwrap_or(~"/tmp/rustdoc/plugins");
+ let path = matches.opt_str("plugin-path").unwrap_or("/tmp/rustdoc/plugins".to_owned());
let mut pm = plugins::PluginManager::new(Path::new(path));
for pass in passes.iter() {
let plugin = match PASSES.iter().position(|&(p, _, _)| p == *pass) {
Ok(json::Object(obj)) => {
let mut obj = obj;
// Make sure the schema is what we expect
- match obj.pop(&~"schema") {
+ match obj.pop(&"schema".to_owned()) {
Some(json::String(version)) => {
if version.as_slice() != SCHEMA_VERSION {
return Err(format!("sorry, but I only understand \
version {}", SCHEMA_VERSION))
}
}
- Some(..) => return Err(~"malformed json"),
- None => return Err(~"expected a schema version"),
+ Some(..) => return Err("malformed json".to_owned()),
+ None => return Err("expected a schema version".to_owned()),
}
- let krate = match obj.pop(&~"crate") {
+ let krate = match obj.pop(&"crate".to_owned()) {
Some(json) => {
let mut d = json::Decoder::new(json);
Decodable::decode(&mut d).unwrap()
}
- None => return Err(~"malformed json"),
+ None => return Err("malformed json".to_owned()),
};
// FIXME: this should read from the "plugins" field, but currently
// Json doesn't implement decodable...
let plugin_output = Vec::new();
Ok((krate, plugin_output))
}
- Ok(..) => Err(~"malformed json input: expected an object at the top"),
+ Ok(..) => Err("malformed json input: expected an object at the top".to_owned()),
}
}
// "plugins": { output of plugins ... }
// }
let mut json = ~collections::TreeMap::new();
- json.insert(~"schema", json::String(SCHEMA_VERSION.to_owned()));
+ json.insert("schema".to_owned(), json::String(SCHEMA_VERSION.to_owned()));
let plugins_json = ~res.move_iter().filter_map(|opt| opt).collect();
// FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
};
- json.insert(~"crate", crate_json);
- json.insert(~"plugins", json::Object(plugins_json));
+ json.insert("crate".to_owned(), crate_json);
+ json.insert("plugins".to_owned(), json::Object(plugins_json));
let mut file = try!(File::create(&dst));
try!(json::Object(json).to_writer(&mut file));
let mut collector = Collector::new(input.to_owned(), libs, true, true);
find_testable_code(input_str, &mut collector);
- test_args.unshift(~"rustdoctest");
+ test_args.unshift("rustdoctest".to_owned());
testing::test_main(test_args.as_slice(), collector.tests);
0
}
for attr in i.attrs.iter() {
match attr {
&clean::NameValue(ref x, ref s) if "doc" == *x => avec.push(
- clean::NameValue(~"doc", unindent(*s))),
+ clean::NameValue("doc".to_owned(), unindent(*s))),
x => avec.push(x.clone())
}
}
_ => true
}).map(|x| x.clone()).collect();
if docstr.len() > 0 {
- a.push(clean::NameValue(~"doc", docstr.into_owned()));
+ a.push(clean::NameValue("doc".to_owned(), docstr.into_owned()));
}
i.attrs = a;
self.fold_item_recur(i)
#[test]
fn should_unindent() {
- let s = ~" line1\n line2";
+ let s = " line1\n line2".to_owned();
let r = unindent(s);
- assert_eq!(r, ~"line1\nline2");
+ assert_eq!(r, "line1\nline2".to_owned());
}
#[test]
fn should_unindent_multiple_paragraphs() {
- let s = ~" line1\n\n line2";
+ let s = " line1\n\n line2".to_owned();
let r = unindent(s);
- assert_eq!(r, ~"line1\n\nline2");
+ assert_eq!(r, "line1\n\nline2".to_owned());
}
#[test]
fn should_leave_multiple_indent_levels() {
// Line 2 is indented another level beyond the
// base indentation and should be preserved
- let s = ~" line1\n\n line2";
+ let s = " line1\n\n line2".to_owned();
let r = unindent(s);
- assert_eq!(r, ~"line1\n\n line2");
+ assert_eq!(r, "line1\n\n line2".to_owned());
}
#[test]
//
// #[doc = "Start way over here
// and continue here"]
- let s = ~"line1\n line2";
+ let s = "line1\n line2".to_owned();
let r = unindent(s);
- assert_eq!(r, ~"line1\nline2");
+ assert_eq!(r, "line1\nline2".to_owned());
}
#[test]
fn should_not_ignore_first_line_indent_in_a_single_line_para() {
- let s = ~"line1\n\n line2";
+ let s = "line1\n\n line2".to_owned();
let r = unindent(s);
- assert_eq!(r, ~"line1\n\n line2");
+ assert_eq!(r, "line1\n\n line2".to_owned());
}
}
false);
collector.fold_crate(krate);
- test_args.unshift(~"rustdoctest");
+ test_args.unshift("rustdoctest".to_owned());
testing::test_main(test_args.as_slice(),
collector.tests.move_iter().collect());
#[test]
fn error_smoke_test() {
let err: UvError = UvError(uvll::EOF);
- assert_eq!(err.to_str(), ~"EOF: end of file");
+ assert_eq!(err.to_str(), "EOF: end of file".to_owned());
}
pub fn uv_error_to_io_error(uverr: UvError) -> IoError {
fn connect_close_ip4() {
match TcpWatcher::connect(local_loop(), next_test_ip4()) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), ~"ECONNREFUSED"),
+ Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_owned()),
}
}
fn connect_close_ip6() {
match TcpWatcher::connect(local_loop(), next_test_ip6()) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), ~"ECONNREFUSED"),
+ Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_owned()),
}
}
fn bind_err() {
match PipeListener::bind(local_loop(), &"path/to/nowhere".to_c_str()) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), ~"EACCES"),
+ Err(e) => assert_eq!(e.name(), "EACCES".to_owned()),
}
}
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric(~"alpha1")),
+ pre: vec!(AlphaNumeric("alpha1".to_owned())),
build: vec!(),
}));
assert!(parse(" 1.2.3-alpha1 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric(~"alpha1")),
+ pre: vec!(AlphaNumeric("alpha1".to_owned())),
build: vec!()
}));
assert!(parse("1.2.3+build5") == Some(Version {
minor: 2u,
patch: 3u,
pre: vec!(),
- build: vec!(AlphaNumeric(~"build5"))
+ build: vec!(AlphaNumeric("build5".to_owned()))
}));
assert!(parse(" 1.2.3+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
- build: vec!(AlphaNumeric(~"build5"))
+ build: vec!(AlphaNumeric("build5".to_owned()))
}));
assert!(parse("1.2.3-alpha1+build5") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric(~"alpha1")),
- build: vec!(AlphaNumeric(~"build5"))
+ pre: vec!(AlphaNumeric("alpha1".to_owned())),
+ build: vec!(AlphaNumeric("build5".to_owned()))
}));
assert!(parse(" 1.2.3-alpha1+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric(~"alpha1")),
- build: vec!(AlphaNumeric(~"build5"))
+ pre: vec!(AlphaNumeric("alpha1".to_owned())),
+ build: vec!(AlphaNumeric("build5".to_owned()))
}));
assert!(parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(Numeric(1),AlphaNumeric(~"alpha1"),Numeric(9)),
- build: vec!(AlphaNumeric(~"build5"),
+ pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_owned()),Numeric(9)),
+ build: vec!(AlphaNumeric("build5".to_owned()),
Numeric(7),
- AlphaNumeric(~"3aedf"))
+ AlphaNumeric("3aedf".to_owned()))
}));
}
#[test]
fn test_show() {
- assert_eq!(format!("{}", parse("1.2.3").unwrap()), ~"1.2.3");
- assert_eq!(format!("{}", parse("1.2.3-alpha1").unwrap()), ~"1.2.3-alpha1");
- assert_eq!(format!("{}", parse("1.2.3+build.42").unwrap()), ~"1.2.3+build.42");
- assert_eq!(format!("{}", parse("1.2.3-alpha1+42").unwrap()), ~"1.2.3-alpha1+42");
+ assert_eq!(format!("{}", parse("1.2.3").unwrap()), "1.2.3".to_owned());
+ assert_eq!(format!("{}", parse("1.2.3-alpha1").unwrap()), "1.2.3-alpha1".to_owned());
+ assert_eq!(format!("{}", parse("1.2.3+build.42").unwrap()), "1.2.3+build.42".to_owned());
+ assert_eq!(format!("{}", parse("1.2.3-alpha1+42").unwrap()), "1.2.3-alpha1+42".to_owned());
}
#[test]
fn test_to_str() {
- assert_eq!(parse("1.2.3").unwrap().to_str(), ~"1.2.3");
- assert_eq!(parse("1.2.3-alpha1").unwrap().to_str(), ~"1.2.3-alpha1");
- assert_eq!(parse("1.2.3+build.42").unwrap().to_str(), ~"1.2.3+build.42");
- assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_str(), ~"1.2.3-alpha1+42");
+ assert_eq!(parse("1.2.3").unwrap().to_str(), "1.2.3".to_owned());
+ assert_eq!(parse("1.2.3-alpha1").unwrap().to_str(), "1.2.3-alpha1".to_owned());
+ assert_eq!(parse("1.2.3+build.42").unwrap().to_str(), "1.2.3+build.42".to_owned());
+ assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_str(), "1.2.3-alpha1+42".to_owned());
}
#[test]
#[test]
fn test_to_base64_basic() {
- assert_eq!("".as_bytes().to_base64(STANDARD), ~"");
- assert_eq!("f".as_bytes().to_base64(STANDARD), ~"Zg==");
- assert_eq!("fo".as_bytes().to_base64(STANDARD), ~"Zm8=");
- assert_eq!("foo".as_bytes().to_base64(STANDARD), ~"Zm9v");
- assert_eq!("foob".as_bytes().to_base64(STANDARD), ~"Zm9vYg==");
- assert_eq!("fooba".as_bytes().to_base64(STANDARD), ~"Zm9vYmE=");
- assert_eq!("foobar".as_bytes().to_base64(STANDARD), ~"Zm9vYmFy");
+ assert_eq!("".as_bytes().to_base64(STANDARD), "".to_owned());
+ assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_owned());
+ assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_owned());
+ assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_owned());
+ assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_owned());
+ assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_owned());
+ assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_owned());
}
#[test]
.contains("\r\n"));
assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
..STANDARD}),
- ~"Zm9v\r\nYmFy");
+ "Zm9v\r\nYmFy".to_owned());
}
#[test]
fn test_to_base64_padding() {
- assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zg");
- assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zm8");
+ assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_owned());
+ assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_owned());
}
#[test]
fn test_to_base64_url_safe() {
- assert_eq!([251, 255].to_base64(URL_SAFE), ~"-_8");
- assert_eq!([251, 255].to_base64(STANDARD), ~"+/8=");
+ assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_owned());
+ assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_owned());
}
#[test]
#[test]
pub fn test_to_hex() {
- assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172");
+ assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172".to_owned());
}
#[test]
}
fn main() {
- let to_encode_object = TestStruct{data_str:~"example of string to encode"};
+ let to_encode_object = TestStruct{data_str:"example of string to encode".to_owned()};
let mut m = io::MemWriter::new();
{
let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
```rust
use serialize::json;
-let to_encode_object = ~"example of string to encode";
+let to_encode_object = "example of string to encode".to_owned();
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
```
impl ToJson for MyStruct {
fn to_json( &self ) -> json::Json {
let mut d = ~TreeMap::new();
- d.insert(~"attr1", self.attr1.to_json());
- d.insert(~"attr2", self.attr2.to_json());
+ d.insert("attr1".to_owned(), self.attr1.to_json());
+ d.insert("attr2".to_owned(), self.attr2.to_json());
json::Object(d)
}
}
fn main() {
- let test2: MyStruct = MyStruct {attr1: 1, attr2:~"test"};
+ let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_owned()};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();
}
fn main() {
let json_str_to_decode: ~str =
- ~"{\"attr1\":1,\"attr2\":\"toto\"}";
+ "{\"attr1\":1,\"attr2\":\"toto\"}".to_owned();
let json_object = json::from_str(json_str_to_decode);
let mut decoder = json::Decoder::new(json_object.unwrap());
let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
// It calls the generated `Encodable` impl.
fn main() {
let to_encode_object = TestStruct1
- {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
+ {data_int: 1, data_str:"toto".to_owned(), data_vector:~[2,3,4,5]};
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
// To deserialize use the `json::from_str` and `json::Decoder`
impl ToJson for TestStruct1 {
fn to_json( &self ) -> json::Json {
let mut d = ~TreeMap::new();
- d.insert(~"data_int", self.data_int.to_json());
- d.insert(~"data_str", self.data_str.to_json());
- d.insert(~"data_vector", self.data_vector.to_json());
+ d.insert("data_int".to_owned(), self.data_int.to_json());
+ d.insert("data_str".to_owned(), self.data_str.to_json());
+ d.insert("data_vector".to_owned(), self.data_vector.to_json());
json::Object(d)
}
}
fn main() {
// Serialization using our impl of to_json
- let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
+ let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
+ data_vector:~[2,3,4,5]};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();
if self.eof() {
Ok(value)
} else {
- self.error(~"trailing characters")
+ self.error("trailing characters".to_owned())
}
}
Err(e) => Err(e)
fn parse_value(&mut self) -> DecodeResult<Json> {
self.parse_whitespace();
- if self.eof() { return self.error(~"EOF while parsing value"); }
+ if self.eof() { return self.error("EOF while parsing value".to_owned()); }
match self.ch_or_null() {
'n' => self.parse_ident("ull", Null),
},
'[' => self.parse_list(),
'{' => self.parse_object(),
- _ => self.error(~"invalid syntax"),
+ _ => self.error("invalid syntax".to_owned()),
}
}
self.bump();
Ok(value)
} else {
- self.error(~"invalid syntax")
+ self.error("invalid syntax".to_owned())
}
}
// There can be only one leading '0'.
match self.ch_or_null() {
- '0' .. '9' => return self.error(~"invalid number"),
+ '0' .. '9' => return self.error("invalid number".to_owned()),
_ => ()
}
},
}
}
}
- _ => return self.error(~"invalid number"),
+ _ => return self.error("invalid number".to_owned()),
}
Ok(res)
}
// Make sure a digit follows the decimal place.
match self.ch_or_null() {
'0' .. '9' => (),
- _ => return self.error(~"invalid number")
+ _ => return self.error("invalid number".to_owned())
}
let mut res = res;
// Make sure a digit follows the exponent place.
match self.ch_or_null() {
'0' .. '9' => (),
- _ => return self.error(~"invalid number")
+ _ => return self.error("invalid number".to_owned())
}
while !self.eof() {
match self.ch_or_null() {
'e' | 'E' => n * 16_u16 + 14_u16,
'f' | 'F' => n * 16_u16 + 15_u16,
_ => return self.error(
- ~"invalid \\u escape (unrecognized hex)")
+ "invalid \\u escape (unrecognized hex)".to_owned())
};
i += 1u;
// Error out if we didn't parse 4 digits.
if i != 4u {
return self.error(
- ~"invalid \\u escape (not four digits)");
+ "invalid \\u escape (not four digits)".to_owned());
}
Ok(n)
loop {
self.bump();
if self.eof() {
- return self.error(~"EOF while parsing string");
+ return self.error("EOF while parsing string".to_owned());
}
if escape {
't' => res.push_char('\t'),
'u' => match try!(self.decode_hex_escape()) {
0xDC00 .. 0xDFFF => return self.error(
- ~"lone trailing surrogate in hex escape"),
+ "lone trailing surrogate in hex escape".to_owned()),
// Non-BMP characters are encoded as a sequence of
// two hex escapes, representing UTF-16 surrogates.
match (c1, c2) {
(Some('\\'), Some('u')) => (),
_ => return self.error(
- ~"unexpected end of non-BMP hex escape"),
+ "unexpected end of non-BMP hex escape".to_owned()),
}
let buf = [n1, try!(self.decode_hex_escape())];
match str::utf16_items(buf.as_slice()).next() {
Some(ScalarValue(c)) => res.push_char(c),
_ => return self.error(
- ~"lone leading surrogate in hex escape"),
+ "lone leading surrogate in hex escape".to_owned()),
}
}
format!("invalid Unicode codepoint {:u}", n)),
},
},
- _ => return self.error(~"invalid escape"),
+ _ => return self.error("invalid escape".to_owned()),
}
escape = false;
} else if self.ch_is('\\') {
self.parse_whitespace();
if self.eof() {
- return self.error(~"EOF while parsing list");
+ return self.error("EOF while parsing list".to_owned());
}
if self.ch_is(',') {
self.bump();
return Ok(List(values.move_iter().collect()));
} else {
- return self.error(~"expected `,` or `]`")
+ return self.error("expected `,` or `]`".to_owned())
}
};
}
self.parse_whitespace();
if !self.ch_is('"') {
- return self.error(~"key must be a string");
+ return self.error("key must be a string".to_owned());
}
let key = match self.parse_str() {
if !self.ch_is(':') {
if self.eof() { break; }
- return self.error(~"expected `:`");
+ return self.error("expected `:`".to_owned());
}
self.bump();
'}' => { self.bump(); return Ok(Object(values)); },
_ => {
if self.eof() { break; }
- return self.error(~"expected `,` or `}`");
+ return self.error("expected `,` or `}`".to_owned());
}
}
}
- return self.error(~"EOF while parsing object");
+ return self.error("EOF while parsing object".to_owned());
}
}
};
let s = match str::from_utf8(contents.as_slice()) {
Some(s) => s.to_owned(),
- None => return Err(ParseError(~"contents not utf-8", 0, 0))
+ None => return Err(ParseError("contents not utf-8".to_owned(), 0, 0))
};
let mut parser = Parser::new(s.chars());
parser.parse()
($e:expr, Null) => ({
match $e {
Null => Ok(()),
- other => Err(ExpectedError(~"Null", format!("{}", other)))
+ other => Err(ExpectedError("Null".to_owned(), format!("{}", other)))
}
});
($e:expr, $t:ident) => ({
// is going to have a string here, as per JSON spec..
Ok(FromStr::from_str(s).unwrap())
},
- value => Err(ExpectedError(~"Number", format!("{}", value)))
+ value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
}
}
_ => ()
}
}
- Err(ExpectedError(~"single character string", format!("{}", s)))
+ Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
}
fn read_str(&mut self) -> DecodeResult<~str> {
let name = match self.pop() {
String(s) => s,
Object(mut o) => {
- let n = match o.pop(&~"variant") {
+ let n = match o.pop(&"variant".to_owned()) {
Some(String(s)) => s,
- Some(val) => return Err(ExpectedError(~"String", format!("{}", val))),
- None => return Err(MissingFieldError(~"variant"))
+ Some(val) => return Err(ExpectedError("String".to_owned(), format!("{}", val))),
+ None => return Err(MissingFieldError("variant".to_owned()))
};
- match o.pop(&~"fields") {
+ match o.pop(&"fields".to_owned()) {
Some(List(l)) => {
for field in l.move_rev_iter() {
self.stack.push(field.clone());
}
},
- Some(val) => return Err(ExpectedError(~"List", format!("{}", val))),
- None => return Err(MissingFieldError(~"fields"))
+ Some(val) => return Err(ExpectedError("List".to_owned(), format!("{}", val))),
+ None => return Err(MissingFieldError("fields".to_owned()))
}
n
}
- json => return Err(ExpectedError(~"String or Object", format!("{}", json)))
+ json => return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
};
let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
Some(idx) => idx,
#[test]
fn test_write_null() {
- assert_eq!(Null.to_str(), ~"null");
- assert_eq!(Null.to_pretty_str(), ~"null");
+ assert_eq!(Null.to_str(), "null".to_owned());
+ assert_eq!(Null.to_pretty_str(), "null".to_owned());
}
#[test]
fn test_write_number() {
- assert_eq!(Number(3.0).to_str(), ~"3");
- assert_eq!(Number(3.0).to_pretty_str(), ~"3");
+ assert_eq!(Number(3.0).to_str(), "3".to_owned());
+ assert_eq!(Number(3.0).to_pretty_str(), "3".to_owned());
- assert_eq!(Number(3.1).to_str(), ~"3.1");
- assert_eq!(Number(3.1).to_pretty_str(), ~"3.1");
+ assert_eq!(Number(3.1).to_str(), "3.1".to_owned());
+ assert_eq!(Number(3.1).to_pretty_str(), "3.1".to_owned());
- assert_eq!(Number(-1.5).to_str(), ~"-1.5");
- assert_eq!(Number(-1.5).to_pretty_str(), ~"-1.5");
+ assert_eq!(Number(-1.5).to_str(), "-1.5".to_owned());
+ assert_eq!(Number(-1.5).to_pretty_str(), "-1.5".to_owned());
- assert_eq!(Number(0.5).to_str(), ~"0.5");
- assert_eq!(Number(0.5).to_pretty_str(), ~"0.5");
+ assert_eq!(Number(0.5).to_str(), "0.5".to_owned());
+ assert_eq!(Number(0.5).to_pretty_str(), "0.5".to_owned());
}
#[test]
fn test_write_str() {
- assert_eq!(String(~"").to_str(), ~"\"\"");
- assert_eq!(String(~"").to_pretty_str(), ~"\"\"");
+ assert_eq!(String("".to_owned()).to_str(), "\"\"".to_owned());
+ assert_eq!(String("".to_owned()).to_pretty_str(), "\"\"".to_owned());
- assert_eq!(String(~"foo").to_str(), ~"\"foo\"");
- assert_eq!(String(~"foo").to_pretty_str(), ~"\"foo\"");
+ assert_eq!(String("foo".to_owned()).to_str(), "\"foo\"".to_owned());
+ assert_eq!(String("foo".to_owned()).to_pretty_str(), "\"foo\"".to_owned());
}
#[test]
fn test_write_bool() {
- assert_eq!(Boolean(true).to_str(), ~"true");
- assert_eq!(Boolean(true).to_pretty_str(), ~"true");
+ assert_eq!(Boolean(true).to_str(), "true".to_owned());
+ assert_eq!(Boolean(true).to_pretty_str(), "true".to_owned());
- assert_eq!(Boolean(false).to_str(), ~"false");
- assert_eq!(Boolean(false).to_pretty_str(), ~"false");
+ assert_eq!(Boolean(false).to_str(), "false".to_owned());
+ assert_eq!(Boolean(false).to_pretty_str(), "false".to_owned());
}
#[test]
fn test_write_list() {
- assert_eq!(List(~[]).to_str(), ~"[]");
- assert_eq!(List(~[]).to_pretty_str(), ~"[]");
+ assert_eq!(List(~[]).to_str(), "[]".to_owned());
+ assert_eq!(List(~[]).to_pretty_str(), "[]".to_owned());
- assert_eq!(List(~[Boolean(true)]).to_str(), ~"[true]");
+ assert_eq!(List(~[Boolean(true)]).to_str(), "[true]".to_owned());
assert_eq!(
List(~[Boolean(true)]).to_pretty_str(),
- ~"\
+ "\
[\n \
true\n\
- ]"
+ ]".to_owned()
);
let long_test_list = List(~[
Boolean(false),
Null,
- List(~[String(~"foo\nbar"), Number(3.5)])]);
+ List(~[String("foo\nbar".to_owned()), Number(3.5)])]);
assert_eq!(long_test_list.to_str(),
- ~"[false,null,[\"foo\\nbar\",3.5]]");
+ "[false,null,[\"foo\\nbar\",3.5]]".to_owned());
assert_eq!(
long_test_list.to_pretty_str(),
- ~"\
+ "\
[\n \
false,\n \
null,\n \
\"foo\\nbar\",\n \
3.5\n \
]\n\
- ]"
+ ]".to_owned()
);
}
#[test]
fn test_write_object() {
- assert_eq!(mk_object([]).to_str(), ~"{}");
- assert_eq!(mk_object([]).to_pretty_str(), ~"{}");
+ assert_eq!(mk_object([]).to_str(), "{}".to_owned());
+ assert_eq!(mk_object([]).to_pretty_str(), "{}".to_owned());
assert_eq!(
- mk_object([(~"a", Boolean(true))]).to_str(),
- ~"{\"a\":true}"
+ mk_object([("a".to_owned(), Boolean(true))]).to_str(),
+ "{\"a\":true}".to_owned()
);
assert_eq!(
- mk_object([(~"a", Boolean(true))]).to_pretty_str(),
- ~"\
+ mk_object([("a".to_owned(), Boolean(true))]).to_pretty_str(),
+ "\
{\n \
\"a\": true\n\
- }"
+ }".to_owned()
);
let complex_obj = mk_object([
- (~"b", List(~[
- mk_object([(~"c", String(~"\x0c\r"))]),
- mk_object([(~"d", String(~""))])
+ ("b".to_owned(), List(~[
+ mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
+ mk_object([("d".to_owned(), String("".to_owned()))])
]))
]);
assert_eq!(
complex_obj.to_str(),
- ~"{\
+ "{\
\"b\":[\
{\"c\":\"\\f\\r\"},\
{\"d\":\"\"}\
]\
- }"
+ }".to_owned()
);
assert_eq!(
complex_obj.to_pretty_str(),
- ~"\
+ "\
{\n \
\"b\": [\n \
{\n \
\"d\": \"\"\n \
}\n \
]\n\
- }"
+ }".to_owned()
);
let a = mk_object([
- (~"a", Boolean(true)),
- (~"b", List(~[
- mk_object([(~"c", String(~"\x0c\r"))]),
- mk_object([(~"d", String(~""))])
+ ("a".to_owned(), Boolean(true)),
+ ("b".to_owned(), List(~[
+ mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
+ mk_object([("d".to_owned(), String("".to_owned()))])
]))
]);
let mut encoder = Encoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- ~"\"Dog\""
+ "\"Dog\"".to_owned()
);
assert_eq!(
with_str_writer(|wr| {
let mut encoder = PrettyEncoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- ~"\"Dog\""
+ "\"Dog\"".to_owned()
);
- let animal = Frog(~"Henry", 349);
+ let animal = Frog("Henry".to_owned(), 349);
assert_eq!(
with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
+ "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_owned()
);
assert_eq!(
with_str_writer(|wr| {
let mut encoder = PrettyEncoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- ~"\
+ "\
[\n \
\"Frog\",\n \
\"Henry\",\n \
349\n\
- ]"
+ ]".to_owned()
);
}
#[test]
fn test_write_some() {
- let value = Some(~"jodhpurs");
+ let value = Some("jodhpurs".to_owned());
let s = with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, ~"\"jodhpurs\"");
+ assert_eq!(s, "\"jodhpurs\"".to_owned());
- let value = Some(~"jodhpurs");
+ let value = Some("jodhpurs".to_owned());
let s = with_str_writer(|wr| {
let mut encoder = PrettyEncoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, ~"\"jodhpurs\"");
+ assert_eq!(s, "\"jodhpurs\"".to_owned());
}
#[test]
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, ~"null");
+ assert_eq!(s, "null".to_owned());
let s = with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, ~"null");
+ assert_eq!(s, "null".to_owned());
}
#[test]
fn test_trailing_characters() {
assert_eq!(from_str("nulla"),
- Err(ParseError(~"trailing characters", 1u, 5u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
assert_eq!(from_str("truea"),
- Err(ParseError(~"trailing characters", 1u, 5u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
assert_eq!(from_str("falsea"),
- Err(ParseError(~"trailing characters", 1u, 6u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 6u)));
assert_eq!(from_str("1a"),
- Err(ParseError(~"trailing characters", 1u, 2u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 2u)));
assert_eq!(from_str("[]a"),
- Err(ParseError(~"trailing characters", 1u, 3u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
assert_eq!(from_str("{}a"),
- Err(ParseError(~"trailing characters", 1u, 3u)));
+ Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
}
#[test]
fn test_read_identifiers() {
assert_eq!(from_str("n"),
- Err(ParseError(~"invalid syntax", 1u, 2u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
assert_eq!(from_str("nul"),
- Err(ParseError(~"invalid syntax", 1u, 4u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
assert_eq!(from_str("t"),
- Err(ParseError(~"invalid syntax", 1u, 2u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
assert_eq!(from_str("truz"),
- Err(ParseError(~"invalid syntax", 1u, 4u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
assert_eq!(from_str("f"),
- Err(ParseError(~"invalid syntax", 1u, 2u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
assert_eq!(from_str("faz"),
- Err(ParseError(~"invalid syntax", 1u, 3u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 3u)));
assert_eq!(from_str("null"), Ok(Null));
assert_eq!(from_str("true"), Ok(Boolean(true)));
#[test]
fn test_read_number() {
assert_eq!(from_str("+"),
- Err(ParseError(~"invalid syntax", 1u, 1u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
assert_eq!(from_str("."),
- Err(ParseError(~"invalid syntax", 1u, 1u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
assert_eq!(from_str("-"),
- Err(ParseError(~"invalid number", 1u, 2u)));
+ Err(ParseError("invalid number".to_owned(), 1u, 2u)));
assert_eq!(from_str("00"),
- Err(ParseError(~"invalid number", 1u, 2u)));
+ Err(ParseError("invalid number".to_owned(), 1u, 2u)));
assert_eq!(from_str("1."),
- Err(ParseError(~"invalid number", 1u, 3u)));
+ Err(ParseError("invalid number".to_owned(), 1u, 3u)));
assert_eq!(from_str("1e"),
- Err(ParseError(~"invalid number", 1u, 3u)));
+ Err(ParseError("invalid number".to_owned(), 1u, 3u)));
assert_eq!(from_str("1e+"),
- Err(ParseError(~"invalid number", 1u, 4u)));
+ Err(ParseError("invalid number".to_owned(), 1u, 4u)));
assert_eq!(from_str("3"), Ok(Number(3.0)));
assert_eq!(from_str("3.1"), Ok(Number(3.1)));
#[test]
fn test_read_str() {
assert_eq!(from_str("\""),
- Err(ParseError(~"EOF while parsing string", 1u, 2u)));
+ Err(ParseError("EOF while parsing string".to_owned(), 1u, 2u)));
assert_eq!(from_str("\"lol"),
- Err(ParseError(~"EOF while parsing string", 1u, 5u)));
-
- assert_eq!(from_str("\"\""), Ok(String(~"")));
- assert_eq!(from_str("\"foo\""), Ok(String(~"foo")));
- assert_eq!(from_str("\"\\\"\""), Ok(String(~"\"")));
- assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08")));
- assert_eq!(from_str("\"\\n\""), Ok(String(~"\n")));
- assert_eq!(from_str("\"\\r\""), Ok(String(~"\r")));
- assert_eq!(from_str("\"\\t\""), Ok(String(~"\t")));
- assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo")));
- assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab")));
- assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12")));
+ Err(ParseError("EOF while parsing string".to_owned(), 1u, 5u)));
+
+ assert_eq!(from_str("\"\""), Ok(String("".to_owned())));
+ assert_eq!(from_str("\"foo\""), Ok(String("foo".to_owned())));
+ assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_owned())));
+ assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_owned())));
+ assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_owned())));
+ assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_owned())));
+ assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_owned())));
+ assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_owned())));
+ assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_owned())));
+ assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_owned())));
// Non-BMP escapes. The exact error messages and positions are kind of
// arbitrary.
- assert_eq!(from_str("\"\\ud83d\\udca9\""), Ok(String(~"\U0001F4A9")));
+ assert_eq!(from_str("\"\\ud83d\\udca9\""), Ok(String("\U0001F4A9".to_owned())));
assert!(from_str("\"\\ud83d\"").is_err());
assert!(from_str("\"\\udca9\"").is_err());
assert!(from_str("\"\\ud83d\\ud83d\"").is_err());
fn test_decode_str() {
let mut decoder = Decoder::new(from_str("\"\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"");
+ assert_eq!(v, "".to_owned());
let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"foo");
+ assert_eq!(v, "foo".to_owned());
let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\"");
+ assert_eq!(v, "\"".to_owned());
let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\x08");
+ assert_eq!(v, "\x08".to_owned());
let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\n");
+ assert_eq!(v, "\n".to_owned());
let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\r");
+ assert_eq!(v, "\r".to_owned());
let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\t");
+ assert_eq!(v, "\t".to_owned());
let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\u12ab");
+ assert_eq!(v, "\u12ab".to_owned());
let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
let v: ~str = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, ~"\uAB12");
+ assert_eq!(v, "\uAB12".to_owned());
}
#[test]
fn test_read_list() {
assert_eq!(from_str("["),
- Err(ParseError(~"EOF while parsing value", 1u, 2u)));
+ Err(ParseError("EOF while parsing value".to_owned(), 1u, 2u)));
assert_eq!(from_str("[1"),
- Err(ParseError(~"EOF while parsing list", 1u, 3u)));
+ Err(ParseError("EOF while parsing list".to_owned(), 1u, 3u)));
assert_eq!(from_str("[1,"),
- Err(ParseError(~"EOF while parsing value", 1u, 4u)));
+ Err(ParseError("EOF while parsing value".to_owned(), 1u, 4u)));
assert_eq!(from_str("[1,]"),
- Err(ParseError(~"invalid syntax", 1u, 4u)));
+ Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
assert_eq!(from_str("[6 7]"),
- Err(ParseError(~"expected `,` or `]`", 1u, 4u)));
+ Err(ParseError("expected `,` or `]`".to_owned(), 1u, 4u)));
assert_eq!(from_str("[]"), Ok(List(~[])));
assert_eq!(from_str("[ ]"), Ok(List(~[])));
#[test]
fn test_read_object() {
assert_eq!(from_str("{"),
- Err(ParseError(~"EOF while parsing object", 1u, 2u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 2u)));
assert_eq!(from_str("{ "),
- Err(ParseError(~"EOF while parsing object", 1u, 3u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 3u)));
assert_eq!(from_str("{1"),
- Err(ParseError(~"key must be a string", 1u, 2u)));
+ Err(ParseError("key must be a string".to_owned(), 1u, 2u)));
assert_eq!(from_str("{ \"a\""),
- Err(ParseError(~"EOF while parsing object", 1u, 6u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
assert_eq!(from_str("{\"a\""),
- Err(ParseError(~"EOF while parsing object", 1u, 5u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 5u)));
assert_eq!(from_str("{\"a\" "),
- Err(ParseError(~"EOF while parsing object", 1u, 6u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
assert_eq!(from_str("{\"a\" 1"),
- Err(ParseError(~"expected `:`", 1u, 6u)));
+ Err(ParseError("expected `:`".to_owned(), 1u, 6u)));
assert_eq!(from_str("{\"a\":"),
- Err(ParseError(~"EOF while parsing value", 1u, 6u)));
+ Err(ParseError("EOF while parsing value".to_owned(), 1u, 6u)));
assert_eq!(from_str("{\"a\":1"),
- Err(ParseError(~"EOF while parsing object", 1u, 7u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 7u)));
assert_eq!(from_str("{\"a\":1 1"),
- Err(ParseError(~"expected `,` or `}`", 1u, 8u)));
+ Err(ParseError("expected `,` or `}`".to_owned(), 1u, 8u)));
assert_eq!(from_str("{\"a\":1,"),
- Err(ParseError(~"EOF while parsing object", 1u, 8u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 1u, 8u)));
assert_eq!(from_str("{}").unwrap(), mk_object([]));
assert_eq!(from_str("{\"a\": 3}").unwrap(),
- mk_object([(~"a", Number(3.0))]));
+ mk_object([("a".to_owned(), Number(3.0))]));
assert_eq!(from_str(
"{ \"a\": null, \"b\" : true }").unwrap(),
mk_object([
- (~"a", Null),
- (~"b", Boolean(true))]));
+ ("a".to_owned(), Null),
+ ("b".to_owned(), Boolean(true))]));
assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
mk_object([
- (~"a", Null),
- (~"b", Boolean(true))]));
+ ("a".to_owned(), Null),
+ ("b".to_owned(), Boolean(true))]));
assert_eq!(from_str(
"{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
mk_object([
- (~"a", Number(1.0)),
- (~"b", List(~[Boolean(true)]))
+ ("a".to_owned(), Number(1.0)),
+ ("b".to_owned(), List(~[Boolean(true)]))
]));
assert_eq!(from_str(
- ~"{" +
+ "{".to_owned() +
"\"a\": 1.0, " +
"\"b\": [" +
"true," +
"]" +
"}").unwrap(),
mk_object([
- (~"a", Number(1.0)),
- (~"b", List(~[
+ ("a".to_owned(), Number(1.0)),
+ ("b".to_owned(), List(~[
Boolean(true),
- String(~"foo\nbar"),
+ String("foo\nbar".to_owned()),
mk_object([
- (~"c", mk_object([(~"d", Null)]))
+ ("c".to_owned(), mk_object([("d".to_owned(), Null)]))
])
]))
]));
#[test]
fn test_decode_struct() {
- let s = ~"{
+ let s = "{
\"inner\": [
{ \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
]
- }";
+ }".to_owned();
let mut decoder = Decoder::new(from_str(s).unwrap());
let v: Outer = Decodable::decode(&mut decoder).unwrap();
assert_eq!(
v,
Outer {
inner: ~[
- Inner { a: (), b: 2, c: ~[~"abc", ~"xyz"] }
+ Inner { a: (), b: 2, c: ~["abc".to_owned(), "xyz".to_owned()] }
]
}
);
let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(value, Some(~"jodhpurs"));
+ assert_eq!(value, Some("jodhpurs".to_owned()));
}
#[test]
let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
let mut decoder = Decoder::new(from_str(s).unwrap());
let value: Animal = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(value, Frog(~"Henry", 349));
+ assert_eq!(value, Frog("Henry".to_owned(), 349));
}
#[test]
fn test_decode_map() {
- let s = ~"{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\"fields\":[\"Henry\", 349]}}";
+ let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
+ \"fields\":[\"Henry\", 349]}}".to_owned();
let mut decoder = Decoder::new(from_str(s).unwrap());
let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(map.pop(&~"a"), Some(Dog));
- assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349)));
+ assert_eq!(map.pop(&"a".to_owned()), Some(Dog));
+ assert_eq!(map.pop(&"b".to_owned()), Some(Frog("Henry".to_owned(), 349)));
}
#[test]
fn test_multiline_errors() {
assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
- Err(ParseError(~"EOF while parsing object", 3u, 8u)));
+ Err(ParseError("EOF while parsing object".to_owned(), 3u, 8u)));
}
#[deriving(Decodable)]
}
#[test]
fn test_decode_errors_struct() {
- check_err::<DecodeStruct>("[]", ExpectedError(~"Object", ~"[]"));
+ check_err::<DecodeStruct>("[]", ExpectedError("Object".to_owned(), "[]".to_owned()));
check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
- ExpectedError(~"Number", ~"true"));
+ ExpectedError("Number".to_owned(), "true".to_owned()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
- ExpectedError(~"Boolean", ~"[]"));
+ ExpectedError("Boolean".to_owned(), "[]".to_owned()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
- ExpectedError(~"String", ~"{}"));
+ ExpectedError("String".to_owned(), "{}".to_owned()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
- ExpectedError(~"List", ~"null"));
+ ExpectedError("List".to_owned(), "null".to_owned()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
- MissingFieldError(~"w"));
+ MissingFieldError("w".to_owned()));
}
#[test]
fn test_decode_errors_enum() {
check_err::<DecodeEnum>("{}",
- MissingFieldError(~"variant"));
+ MissingFieldError("variant".to_owned()));
check_err::<DecodeEnum>("{\"variant\": 1}",
- ExpectedError(~"String", ~"1"));
+ ExpectedError("String".to_owned(), "1".to_owned()));
check_err::<DecodeEnum>("{\"variant\": \"A\"}",
- MissingFieldError(~"fields"));
+ MissingFieldError("fields".to_owned()));
check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
- ExpectedError(~"List", ~"null"));
+ ExpectedError("List".to_owned(), "null".to_owned()));
check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
- UnknownVariantError(~"C"));
+ UnknownVariantError("C".to_owned()));
}
#[test]
fn test_find(){
let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
- let found_str = json_value.find(&~"dog");
+ let found_str = json_value.find(&"dog".to_owned());
assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
}
#[test]
fn test_find_path(){
let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
- let found_str = json_value.find_path(&[&~"dog", &~"cat", &~"mouse"]);
+ let found_str = json_value.find_path(&[&"dog".to_owned(),
+ &"cat".to_owned(), &"mouse".to_owned()]);
assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
}
#[test]
fn test_search(){
let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
- let found_str = json_value.search(&~"mouse").and_then(|j| j.as_string());
+ let found_str = json_value.search(&"mouse".to_owned()).and_then(|j| j.as_string());
assert!(found_str.is_some());
assert!(found_str.unwrap() == &"cheese");
}
mod tests {
use prelude::*;
use super::*;
+ use str::StrSlice;
#[deriving(Eq, Show)]
struct Test;
fn test_show() {
let a = ~8u as ~Any;
let b = ~Test as ~Any;
- assert_eq!(format!("{}", a), ~"~Any");
- assert_eq!(format!("{}", b), ~"~Any");
+ assert_eq!(format!("{}", a), "~Any".to_owned());
+ assert_eq!(format!("{}", b), "~Any".to_owned());
let a = &8u as &Any;
let b = &Test as &Any;
- assert_eq!(format!("{}", a), ~"&Any");
- assert_eq!(format!("{}", b), ~"&Any");
+ assert_eq!(format!("{}", a), "&Any".to_owned());
+ assert_eq!(format!("{}", b), "&Any".to_owned());
}
}
use str::from_char;
use char::from_u32;
use vec::Vec;
+ use str::StrSlice;
macro_rules! v2ascii (
( [$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
// FIXME: #5475 borrowchk error, owned vectors do not live long enough
// if chained-from directly
let v = ~[40u8, 32u8, 59u8]; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
- let v = ~"( ;"; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
+ let v = "( ;".to_owned(); assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
- assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), ~"abcdef&?#");
- assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), ~"ABCDEF&?#");
+ assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_owned());
+ assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_owned());
- assert_eq!("".to_ascii().to_lower().into_str(), ~"");
- assert_eq!("YMCA".to_ascii().to_lower().into_str(), ~"ymca");
- assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), ~"ABCDEFXYZ:.;");
+ assert_eq!("".to_ascii().to_lower().into_str(), "".to_owned());
+ assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_owned());
+ assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_owned());
assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii()));
#[test]
fn test_ascii_vec_ng() {
- assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_lower()).into_str(), ~"abcdef&?#");
- assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_upper()).into_str(), ~"ABCDEF&?#");
-
- assert_eq!(Vec::from_slice("".to_ascii().to_lower()).into_str(), ~"");
- assert_eq!(Vec::from_slice("YMCA".to_ascii().to_lower()).into_str(), ~"ymca");
+ assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_lower()).into_str(),
+ "abcdef&?#".to_owned());
+ assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_upper()).into_str(),
+ "ABCDEF&?#".to_owned());
+ assert_eq!(Vec::from_slice("".to_ascii().to_lower()).into_str(), "".to_owned());
+ assert_eq!(Vec::from_slice("YMCA".to_ascii().to_lower()).into_str(), "ymca".to_owned());
assert_eq!(Vec::from_slice("abcDEFxyz:.;".to_ascii().to_upper()).into_str(),
- ~"ABCDEFXYZ:.;");
+ "ABCDEFXYZ:.;".to_owned());
}
#[test]
fn test_owned_ascii_vec() {
- assert_eq!((~"( ;").into_ascii(), v2ascii!(~[40, 32, 59]));
+ assert_eq!(("( ;".to_owned()).into_ascii(), v2ascii!(~[40, 32, 59]));
assert_eq!((~[40u8, 32u8, 59u8]).into_ascii(), v2ascii!(~[40, 32, 59]));
}
#[test]
fn test_ascii_into_str() {
- assert_eq!(v2ascii!(~[40, 32, 59]).into_str(), ~"( ;");
- assert_eq!(vec2ascii!(40, 32, 59).into_str(), ~"( ;");
+ assert_eq!(v2ascii!(~[40, 32, 59]).into_str(), "( ;".to_owned());
+ assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_owned());
}
#[test]
assert_eq!((~[40u8, 32u8, 59u8]).into_ascii_opt(), Some(v2ascii!(~[40, 32, 59])));
assert_eq!((~[127u8, 128u8, 255u8]).into_ascii_opt(), None);
- assert_eq!((~"( ;").into_ascii_opt(), Some(v2ascii!(~[40, 32, 59])));
- assert_eq!((~"zoä华").into_ascii_opt(), None);
+ assert_eq!(("( ;".to_owned()).into_ascii_opt(), Some(v2ascii!(~[40, 32, 59])));
+ assert_eq!(("zoä华".to_owned()).into_ascii_opt(), None);
}
#[test]
fn test_to_ascii_upper() {
- assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), ~"URL()URL()URL()üRL");
- assert_eq!("hıKß".to_ascii_upper(), ~"HıKß");
+ assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), "URL()URL()URL()üRL".to_owned());
+ assert_eq!("hıKß".to_ascii_upper(), "HıKß".to_owned());
let mut i = 0;
while i <= 500 {
#[test]
fn test_to_ascii_lower() {
- assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), ~"url()url()url()Ürl");
+ assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), "url()url()url()Ürl".to_owned());
// Dotted capital I, Kelvin sign, Sharp S.
- assert_eq!("HİKß".to_ascii_lower(), ~"hİKß");
+ assert_eq!("HİKß".to_ascii_lower(), "hİKß".to_owned());
let mut i = 0;
while i <= 500 {
#[test]
fn test_into_ascii_upper() {
- assert_eq!((~"url()URL()uRl()ürl").into_ascii_upper(), ~"URL()URL()URL()üRL");
- assert_eq!((~"hıKß").into_ascii_upper(), ~"HıKß");
+ assert_eq!(("url()URL()uRl()ürl".to_owned()).into_ascii_upper(),
+ "URL()URL()URL()üRL".to_owned());
+ assert_eq!(("hıKß".to_owned()).into_ascii_upper(), "HıKß".to_owned());
let mut i = 0;
while i <= 500 {
#[test]
fn test_into_ascii_lower() {
- assert_eq!((~"url()URL()uRl()Ürl").into_ascii_lower(), ~"url()url()url()Ürl");
+ assert_eq!(("url()URL()uRl()Ürl".to_owned()).into_ascii_lower(),
+ "url()url()url()Ürl".to_owned());
// Dotted capital I, Kelvin sign, Sharp S.
- assert_eq!((~"HİKß").into_ascii_lower(), ~"hİKß");
+ assert_eq!(("HİKß".to_owned()).into_ascii_lower(), "hİKß".to_owned());
let mut i = 0;
while i <= 500 {
#[test]
fn test_to_str() {
let s = Ascii{ chr: 't' as u8 }.to_str();
- assert_eq!(s, ~"t");
+ assert_eq!(s, "t".to_owned());
}
#[test]
fn test_show() {
let c = Ascii { chr: 't' as u8 };
- assert_eq!(format!("{}", c), ~"t");
+ assert_eq!(format!("{}", c), "t".to_owned());
}
}
mod tests {
use prelude::*;
use super::to_bit;
+ use str::StrSlice;
#[test]
fn test_to_bit() {
#[test]
fn test_to_str() {
- assert_eq!(false.to_str(), ~"false");
- assert_eq!(true.to_str(), ~"true");
+ assert_eq!(false.to_str(), "false".to_owned());
+ assert_eq!(true.to_str(), "true".to_owned());
}
#[test]
use super::*;
use libc;
use ptr;
+ use str::StrSlice;
#[test]
fn test_str_multistring_parsing() {
#[test]
fn test_clone_noleak() {
fn foo(f: |c: &CString|) {
- let s = ~"test";
+ let s = "test".to_owned();
let c = s.to_c_str();
// give the closure a non-owned CString
let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
mod tests {
use cast::{bump_box_refcount, transmute};
use raw;
+ use str::StrSlice;
#[test]
fn test_transmute_copy() {
#[test]
fn test_bump_managed_refcount() {
unsafe {
- let managed = @~"box box box"; // refcount 1
+ let managed = @"box box box".to_owned(); // refcount 1
bump_box_refcount(managed); // refcount 2
let ptr: *int = transmute(managed); // refcount 2
let _box1: @~str = ::cast::transmute_copy(&ptr);
let _box2: @~str = ::cast::transmute_copy(&ptr);
- assert!(*_box1 == ~"box box box");
- assert!(*_box2 == ~"box box box");
+ assert!(*_box1 == "box box box".to_owned());
+ assert!(*_box2 == "box box box".to_owned());
// Will destroy _box1 and _box2. Without the bump, this would
// use-after-free. With too many bumps, it would leak.
}
#[test]
fn test_transmute2() {
unsafe {
- assert_eq!(~[76u8], transmute(~"L"));
+ assert_eq!(~[76u8], transmute("L".to_owned()));
}
}
}
escape_default(c, |c| { result.push_char(c); });
return result.into_owned();
}
- assert_eq!(string('\n'), ~"\\n");
- assert_eq!(string('\r'), ~"\\r");
- assert_eq!(string('\''), ~"\\'");
- assert_eq!(string('"'), ~"\\\"");
- assert_eq!(string(' '), ~" ");
- assert_eq!(string('a'), ~"a");
- assert_eq!(string('~'), ~"~");
- assert_eq!(string('\x00'), ~"\\x00");
- assert_eq!(string('\x1f'), ~"\\x1f");
- assert_eq!(string('\x7f'), ~"\\x7f");
- assert_eq!(string('\xff'), ~"\\xff");
- assert_eq!(string('\u011b'), ~"\\u011b");
- assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
+ 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());
}
#[test]
escape_unicode(c, |c| { result.push_char(c); });
return result.into_owned();
}
- assert_eq!(string('\x00'), ~"\\x00");
- assert_eq!(string('\n'), ~"\\x0a");
- assert_eq!(string(' '), ~"\\x20");
- assert_eq!(string('a'), ~"\\x61");
- assert_eq!(string('\u011b'), ~"\\u011b");
- assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
+ 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());
}
#[test]
fn test_to_str() {
use to_str::ToStr;
let s = 't'.to_str();
- assert_eq!(s, ~"t");
+ assert_eq!(s, "t".to_owned());
}
#[test]
Some examples of the `format!` extension are:
```rust
-format!("Hello"); // => ~"Hello"
-format!("Hello, {:s}!", "world"); // => ~"Hello, world!"
-format!("The number is {:d}", 1); // => ~"The number is 1"
-format!("{:?}", ~[3, 4]); // => ~"~[3, 4]"
-format!("{value}", value=4); // => ~"4"
-format!("{} {}", 1, 2); // => ~"1 2"
+format!("Hello"); // => "Hello".to_owned()
+format!("Hello, {:s}!", "world"); // => "Hello, world!".to_owned()
+format!("The number is {:d}", 1); // => "The number is 1".to_owned()
+format!("{:?}", ~[3, 4]); // => "~[3, 4]".to_owned()
+format!("{value}", value=4); // => "4".to_owned()
+format!("{} {}", 1, 2); // => "1 2".to_owned()
```
From these, you can see that the first argument is a format string. It is
iterator advances. This leads to behavior like this:
```rust
-format!("{1} {} {0} {}", 1, 2); // => ~"2 1 1 2"
+format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2".to_owned()
```
The internal iterator over the argument has not been advanced by the time the
For example, the following `format!` expressions all use named argument:
```rust
-format!("{argument}", argument = "test"); // => ~"test"
-format!("{name} {}", 1, name = 2); // => ~"2 1"
-format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => ~"a 3 ()"
+format!("{argument}", argument = "test"); // => "test".to_owned()
+format!("{name} {}", 1, name = 2); // => "2 1".to_owned()
+format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => "a 3 ()".to_owned()
```
It is illegal to put positional parameters (those without names) after arguments
example:
```rust
-format!("{0, select, other{#}}", "hello"); // => ~"hello"
+format!("{0, select, other{#}}", "hello"); // => "hello".to_owned()
```
This example is the equivalent of `{0:s}` essentially.
/// use std::fmt;
///
/// let s = format_args!(fmt::format, "Hello, {}!", "world");
-/// assert_eq!(s, ~"Hello, world!");
+/// assert_eq!(s, "Hello, world!".to_owned());
/// ```
pub fn format(args: &Arguments) -> ~str {
unsafe { format_unsafe(args.fmt, args.args) }
///
/// ~~~
/// use std::fmt::radix;
-/// assert_eq!(format!("{}", radix(55, 36)), ~"1j");
+/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_owned());
/// ~~~
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
use fmt::radix;
use super::{Binary, Octal, Decimal, LowerHex, UpperHex};
use super::{GenericRadix, Radix};
+ use str::StrSlice;
#[test]
fn test_radix_base() {
// 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");
- assert_eq!(format!("{}", 1i8), ~"1");
- assert_eq!(format!("{}", 1i16), ~"1");
- assert_eq!(format!("{}", 1i32), ~"1");
- assert_eq!(format!("{}", 1i64), ~"1");
- assert_eq!(format!("{:d}", -1i), ~"-1");
- assert_eq!(format!("{:d}", -1i8), ~"-1");
- assert_eq!(format!("{:d}", -1i16), ~"-1");
- assert_eq!(format!("{:d}", -1i32), ~"-1");
- assert_eq!(format!("{:d}", -1i64), ~"-1");
- assert_eq!(format!("{:t}", 1i), ~"1");
- assert_eq!(format!("{:t}", 1i8), ~"1");
- assert_eq!(format!("{:t}", 1i16), ~"1");
- assert_eq!(format!("{:t}", 1i32), ~"1");
- assert_eq!(format!("{:t}", 1i64), ~"1");
- assert_eq!(format!("{:x}", 1i), ~"1");
- assert_eq!(format!("{:x}", 1i8), ~"1");
- assert_eq!(format!("{:x}", 1i16), ~"1");
- assert_eq!(format!("{:x}", 1i32), ~"1");
- assert_eq!(format!("{:x}", 1i64), ~"1");
- assert_eq!(format!("{:X}", 1i), ~"1");
- assert_eq!(format!("{:X}", 1i8), ~"1");
- assert_eq!(format!("{:X}", 1i16), ~"1");
- assert_eq!(format!("{:X}", 1i32), ~"1");
- assert_eq!(format!("{:X}", 1i64), ~"1");
- assert_eq!(format!("{:o}", 1i), ~"1");
- assert_eq!(format!("{:o}", 1i8), ~"1");
- assert_eq!(format!("{:o}", 1i16), ~"1");
- assert_eq!(format!("{:o}", 1i32), ~"1");
- assert_eq!(format!("{:o}", 1i64), ~"1");
-
- assert_eq!(format!("{}", 1u), ~"1");
- assert_eq!(format!("{}", 1u8), ~"1");
- assert_eq!(format!("{}", 1u16), ~"1");
- assert_eq!(format!("{}", 1u32), ~"1");
- assert_eq!(format!("{}", 1u64), ~"1");
- assert_eq!(format!("{:u}", 1u), ~"1");
- assert_eq!(format!("{:u}", 1u8), ~"1");
- assert_eq!(format!("{:u}", 1u16), ~"1");
- assert_eq!(format!("{:u}", 1u32), ~"1");
- assert_eq!(format!("{:u}", 1u64), ~"1");
- assert_eq!(format!("{:t}", 1u), ~"1");
- assert_eq!(format!("{:t}", 1u8), ~"1");
- assert_eq!(format!("{:t}", 1u16), ~"1");
- assert_eq!(format!("{:t}", 1u32), ~"1");
- assert_eq!(format!("{:t}", 1u64), ~"1");
- assert_eq!(format!("{:x}", 1u), ~"1");
- assert_eq!(format!("{:x}", 1u8), ~"1");
- assert_eq!(format!("{:x}", 1u16), ~"1");
- assert_eq!(format!("{:x}", 1u32), ~"1");
- assert_eq!(format!("{:x}", 1u64), ~"1");
- assert_eq!(format!("{:X}", 1u), ~"1");
- assert_eq!(format!("{:X}", 1u8), ~"1");
- assert_eq!(format!("{:X}", 1u16), ~"1");
- assert_eq!(format!("{:X}", 1u32), ~"1");
- assert_eq!(format!("{:X}", 1u64), ~"1");
- assert_eq!(format!("{:o}", 1u), ~"1");
- assert_eq!(format!("{:o}", 1u8), ~"1");
- assert_eq!(format!("{:o}", 1u16), ~"1");
- assert_eq!(format!("{:o}", 1u32), ~"1");
- assert_eq!(format!("{:o}", 1u64), ~"1");
+ 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());
// Test a larger number
- assert_eq!(format!("{:t}", 55), ~"110111");
- assert_eq!(format!("{:o}", 55), ~"67");
- assert_eq!(format!("{:d}", 55), ~"55");
- assert_eq!(format!("{:x}", 55), ~"37");
- assert_eq!(format!("{:X}", 55), ~"37");
+ 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());
}
#[test]
fn test_format_int_zero() {
- assert_eq!(format!("{}", 0i), ~"0");
- assert_eq!(format!("{:d}", 0i), ~"0");
- assert_eq!(format!("{:t}", 0i), ~"0");
- assert_eq!(format!("{:o}", 0i), ~"0");
- assert_eq!(format!("{:x}", 0i), ~"0");
- assert_eq!(format!("{:X}", 0i), ~"0");
-
- assert_eq!(format!("{}", 0u), ~"0");
- assert_eq!(format!("{:u}", 0u), ~"0");
- assert_eq!(format!("{:t}", 0u), ~"0");
- assert_eq!(format!("{:o}", 0u), ~"0");
- assert_eq!(format!("{:x}", 0u), ~"0");
- assert_eq!(format!("{:X}", 0u), ~"0");
+ 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());
}
#[test]
fn test_format_int_flags() {
- assert_eq!(format!("{:3d}", 1), ~" 1");
- assert_eq!(format!("{:>3d}", 1), ~" 1");
- assert_eq!(format!("{:>+3d}", 1), ~" +1");
- assert_eq!(format!("{:<3d}", 1), ~"1 ");
- assert_eq!(format!("{:#d}", 1), ~"1");
- assert_eq!(format!("{:#x}", 10), ~"0xa");
- assert_eq!(format!("{:#X}", 10), ~"0xA");
- assert_eq!(format!("{:#5x}", 10), ~" 0xa");
- assert_eq!(format!("{:#o}", 10), ~"0o12");
- assert_eq!(format!("{:08x}", 10), ~"0000000a");
- assert_eq!(format!("{:8x}", 10), ~" a");
- assert_eq!(format!("{:<8x}", 10), ~"a ");
- assert_eq!(format!("{:>8x}", 10), ~" a");
- assert_eq!(format!("{:#08x}", 10), ~"0x00000a");
- assert_eq!(format!("{:08d}", -10), ~"-0000010");
- assert_eq!(format!("{:x}", -1u8), ~"ff");
- assert_eq!(format!("{:X}", -1u8), ~"FF");
- assert_eq!(format!("{:t}", -1u8), ~"11111111");
- assert_eq!(format!("{:o}", -1u8), ~"377");
- assert_eq!(format!("{:#x}", -1u8), ~"0xff");
- assert_eq!(format!("{:#X}", -1u8), ~"0xFF");
- assert_eq!(format!("{:#t}", -1u8), ~"0b11111111");
- assert_eq!(format!("{:#o}", -1u8), ~"0o377");
+ 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());
}
#[test]
fn test_format_int_sign_padding() {
- assert_eq!(format!("{:+5d}", 1), ~" +1");
- assert_eq!(format!("{:+5d}", -1), ~" -1");
- assert_eq!(format!("{:05d}", 1), ~"00001");
- assert_eq!(format!("{:05d}", -1), ~"-0001");
- assert_eq!(format!("{:+05d}", 1), ~"+0001");
- assert_eq!(format!("{:+05d}", -1), ~"-0001");
+ 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());
}
#[test]
fn test_format_int_twos_complement() {
use {i8, i16, i32, i64};
- assert_eq!(format!("{}", i8::MIN), ~"-128");
- assert_eq!(format!("{}", i16::MIN), ~"-32768");
- assert_eq!(format!("{}", i32::MIN), ~"-2147483648");
- assert_eq!(format!("{}", i64::MIN), ~"-9223372036854775808");
+ 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());
}
#[test]
fn test_format_radix() {
- assert_eq!(format!("{:04}", radix(3, 2)), ~"0011");
- assert_eq!(format!("{}", radix(55, 36)), ~"1j");
+ assert_eq!(format!("{:04}", radix(3, 2)), "0011".to_owned());
+ assert_eq!(format!("{}", radix(55, 36)), "1j".to_owned());
}
#[test]
* phone: u64,
* }
*
- * let person1 = Person { id: 5, name: ~"Janet", phone: 555_666_7777 };
- * let person2 = Person { id: 5, name: ~"Bob", phone: 555_666_7777 };
+ * let person1 = Person { id: 5, name: "Janet".to_owned(), phone: 555_666_7777 };
+ * let person2 = Person { id: 5, name: "Bob".to_owned(), phone: 555_666_7777 };
*
* assert!(hash::hash(&person1) != hash::hash(&person2));
* ```
* }
* }
*
- * let person1 = Person { id: 5, name: ~"Janet", phone: 555_666_7777 };
- * let person2 = Person { id: 5, name: ~"Bob", phone: 555_666_7777 };
+ * let person1 = Person { id: 5, name: "Janet".to_owned(), phone: 555_666_7777 };
+ * let person2 = Person { id: 5, name: "Bob".to_owned(), phone: 555_666_7777 };
*
* assert!(hash::hash(&person1) == hash::hash(&person2));
* ```
extern crate test;
use prelude::*;
use num::ToStrRadix;
+ use option::{Some, None};
+ use str::{Str,StrSlice};
+ use strbuf::StrBuf;
+ use slice::{Vector, ImmutableVector, OwnedVector};
use self::test::Bencher;
use super::super::Hash;
let compound = Compound {
x: 1,
y: 2,
- z: ~"foobarbaz",
+ z: "foobarbaz".to_owned(),
};
b.iter(|| {
assert_eq!(hash(&compound), 15783192367317361799);
use super::*;
use super::super::mem::{MemReader, MemWriter, BufReader};
use self::test::Bencher;
+ use str::StrSlice;
/// A type, free to create, primarily intended for benchmarking creation of
/// wrappers that, just for construction, don't need a Reader/Writer that
fn test_read_line() {
let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc")));
let mut reader = BufferedReader::with_capacity(2, in_buf);
- assert_eq!(reader.read_line(), Ok(~"a\n"));
- assert_eq!(reader.read_line(), Ok(~"b\n"));
- assert_eq!(reader.read_line(), Ok(~"c"));
+ assert_eq!(reader.read_line(), Ok("a\n".to_owned()));
+ assert_eq!(reader.read_line(), Ok("b\n".to_owned()));
+ assert_eq!(reader.read_line(), Ok("c".to_owned()));
assert!(reader.read_line().is_err());
}
let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc")));
let mut reader = BufferedReader::with_capacity(2, in_buf);
let mut it = reader.lines();
- assert_eq!(it.next(), Some(Ok(~"a\n")));
- assert_eq!(it.next(), Some(Ok(~"b\n")));
- assert_eq!(it.next(), Some(Ok(~"c")));
+ assert_eq!(it.next(), Some(Ok("a\n".to_owned())));
+ assert_eq!(it.next(), Some(Ok("b\n".to_owned())));
+ assert_eq!(it.next(), Some(Ok("c".to_owned())));
assert_eq!(it.next(), None);
}
use option::{None, Option, Some};
use result::{Ok, Err};
use super::{Reader, Writer, IoResult};
+use str::StrSlice;
use slice::{bytes, CloneableVector, MutableVector, ImmutableVector};
/// Allows reading from a rx.
use path::Path;
use io;
use ops::Drop;
+ use str::StrSlice;
macro_rules! check( ($e:expr) => (
match $e {
use super::*;
use io::*;
use io;
+ use str::StrSlice;
#[test]
fn test_mem_writer() {
writer.write_line("testing").unwrap();
writer.write_str("testing").unwrap();
let mut r = BufReader::new(writer.get_ref());
- assert_eq!(r.read_to_str().unwrap(), ~"testingtesting\ntesting");
+ assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_owned());
}
#[test]
writer.write_char('\n').unwrap();
writer.write_char('ệ').unwrap();
let mut r = BufReader::new(writer.get_ref());
- assert_eq!(r.read_to_str().unwrap(), ~"a\nệ");
+ assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_owned());
}
#[test]
/// use std::io;
///
/// let mut reader = io::stdin();
- /// let input = reader.read_line().ok().unwrap_or(~"nothing");
+ /// let input = reader.read_line().ok().unwrap_or("nothing".to_owned());
/// ```
///
/// # Error
#[test]
fn ipv6_addr_to_str() {
let a1 = Ipv6Addr(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
- assert!(a1.to_str() == ~"::ffff:192.0.2.128" || a1.to_str() == ~"::FFFF:192.0.2.128");
- assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), ~"8:9:a:b:c:d:e:f");
+ assert!(a1.to_str() == "::ffff:192.0.2.128".to_owned() ||
+ a1.to_str() == "::FFFF:192.0.2.128".to_owned());
+ assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_owned());
}
}
/// ```should_fail
/// use std::io::Process;
///
-/// let mut child = match Process::new("/bin/cat", [~"file.txt"]) {
+/// let mut child = match Process::new("/bin/cat", ["file.txt".to_owned()]) {
/// Ok(child) => child,
/// Err(e) => fail!("failed to execute child: {}", e),
/// };
///
/// let config = ProcessConfig {
/// program: "/bin/sh",
-/// args: &[~"-c", ~"true"],
+/// args: &["-c".to_owned(), "true".to_owned()],
/// .. ProcessConfig::new()
/// };
/// ```
///
/// let config = ProcessConfig {
/// program: "/bin/sh",
- /// args: &[~"-c", ~"echo hello"],
+ /// args: &["-c".to_owned(), "echo hello".to_owned()],
/// .. ProcessConfig::new()
/// };
///
/// ```
/// use std::io::Process;
///
- /// let mut process = match Process::new("sh", &[~"c", ~"echo hello"]) {
+ /// let mut process = match Process::new("sh", &["c".to_owned(), "echo hello".to_owned()]) {
/// Ok(p) => p,
/// Err(e) => fail!("failed to execute process: {}", e),
/// };
/// use std::io::Process;
/// use std::str;
///
- /// let output = match Process::output("cat", [~"foo.txt"]) {
+ /// let output = match Process::output("cat", ["foo.txt".to_owned()]) {
/// Ok(output) => output,
/// Err(e) => fail!("failed to execute process: {}", e),
/// };
mod tests {
use io::process::{ProcessConfig, Process};
use prelude::*;
+ use str::StrSlice;
// FIXME(#10380) these tests should not all be ignored on android.
iotest!(fn signal_reported_right() {
let args = ProcessConfig {
program: "/bin/sh",
- args: &[~"-c", ~"kill -1 $$"],
+ args: &["-c".to_owned(), "kill -1 $$".to_owned()],
.. ProcessConfig::new()
};
let p = Process::configure(args);
iotest!(fn stdout_works() {
let args = ProcessConfig {
program: "echo",
- args: &[~"foobar"],
+ args: &["foobar".to_owned()],
stdout: CreatePipe(false, true),
.. ProcessConfig::new()
};
- assert_eq!(run_output(args), ~"foobar\n");
+ assert_eq!(run_output(args), "foobar\n".to_owned());
})
#[cfg(unix, not(target_os="android"))]
let cwd = Path::new("/");
let args = ProcessConfig {
program: "/bin/sh",
- args: &[~"-c", ~"pwd"],
+ args: &["-c".to_owned(), "pwd".to_owned()],
cwd: Some(&cwd),
stdout: CreatePipe(false, true),
.. ProcessConfig::new()
};
- assert_eq!(run_output(args), ~"/\n");
+ assert_eq!(run_output(args), "/\n".to_owned());
})
#[cfg(unix, not(target_os="android"))]
iotest!(fn stdin_works() {
let args = ProcessConfig {
program: "/bin/sh",
- args: &[~"-c", ~"read line; echo $line"],
+ args: &["-c".to_owned(), "read line; echo $line".to_owned()],
stdin: CreatePipe(true, false),
stdout: CreatePipe(false, true),
.. ProcessConfig::new()
drop(p.stdin.take());
let out = read_all(p.stdout.get_mut_ref() as &mut Reader);
assert!(p.wait().success());
- assert_eq!(out, ~"foobar\n");
+ assert_eq!(out, "foobar\n".to_owned());
})
#[cfg(not(target_os="android"))]
use libc;
let args = ProcessConfig {
program: "/bin/sh",
- args: &[~"-c", ~"true"],
+ args: &["-c".to_owned(), "true".to_owned()],
uid: Some(unsafe { libc::getuid() as uint }),
gid: Some(unsafe { libc::getgid() as uint }),
.. ProcessConfig::new()
iotest!(fn test_process_output_output() {
let ProcessOutput {status, output, error}
- = Process::output("echo", [~"hello"]).unwrap();
+ = Process::output("echo", ["hello".to_owned()]).unwrap();
let output_str = str::from_utf8(output.as_slice()).unwrap();
assert!(status.success());
- assert_eq!(output_str.trim().to_owned(), ~"hello");
+ assert_eq!(output_str.trim().to_owned(), "hello".to_owned());
// FIXME #7224
if !running_on_valgrind() {
assert_eq!(error, Vec::new());
#[cfg(not(target_os="android"))]
iotest!(fn test_process_output_error() {
let ProcessOutput {status, output, error}
- = Process::output("mkdir", [~"."]).unwrap();
+ = Process::output("mkdir", [".".to_owned()]).unwrap();
assert!(status.matches_exit_status(1));
assert_eq!(output, Vec::new());
#[cfg(not(target_os="android"))]
iotest!(fn test_wait_with_output_once() {
- let mut prog = Process::new("echo", [~"hello"]).unwrap();
+ let mut prog = Process::new("echo", ["hello".to_owned()]).unwrap();
let ProcessOutput {status, output, error} = prog.wait_with_output();
let output_str = str::from_utf8(output.as_slice()).unwrap();
assert!(status.success());
- assert_eq!(output_str.trim().to_owned(), ~"hello");
+ assert_eq!(output_str.trim().to_owned(), "hello".to_owned());
// FIXME #7224
if !running_on_valgrind() {
assert_eq!(error, Vec::new());
#[cfg(not(target_os="android"))]
iotest!(fn test_wait_with_output_twice() {
- let mut prog = Process::new("echo", [~"hello"]).unwrap();
+ let mut prog = Process::new("echo", ["hello".to_owned()]).unwrap();
let ProcessOutput {status, output, error} = prog.wait_with_output();
let output_str = str::from_utf8(output.as_slice()).unwrap();
assert!(status.success());
- assert_eq!(output_str.trim().to_owned(), ~"hello");
+ assert_eq!(output_str.trim().to_owned(), "hello".to_owned());
// FIXME #7224
if !running_on_valgrind() {
assert_eq!(error, Vec::new());
pub fn run_pwd(dir: Option<&Path>) -> Process {
Process::configure(ProcessConfig {
program: "/system/bin/sh",
- args: &[~"-c",~"pwd"],
+ args: &["-c".to_owned(),"pwd".to_owned()],
cwd: dir.map(|a| &*a),
.. ProcessConfig::new()
}).unwrap()
pub fn run_pwd(dir: Option<&Path>) -> Process {
Process::configure(ProcessConfig {
program: "cmd",
- args: &[~"/c", ~"cd"],
+ args: &["/c".to_owned(), "cd".to_owned()],
cwd: dir.map(|a| &*a),
.. ProcessConfig::new()
}).unwrap()
pub fn run_env(env: Option<~[(~str, ~str)]>) -> Process {
Process::configure(ProcessConfig {
program: "/system/bin/sh",
- args: &[~"-c",~"set"],
+ args: &["-c".to_owned(),"set".to_owned()],
env: env.as_ref().map(|e| e.as_slice()),
.. ProcessConfig::new()
}).unwrap()
pub fn run_env(env: Option<~[(~str, ~str)]>) -> Process {
Process::configure(ProcessConfig {
program: "cmd",
- args: &[~"/c", ~"set"],
+ args: &["/c".to_owned(), "set".to_owned()],
env: env.as_ref().map(|e| e.as_slice()),
.. ProcessConfig::new()
}).unwrap()
let r = os::env();
for &(ref k, ref v) in r.iter() {
// don't check android RANDOM variables
- if *k != ~"RANDOM" {
+ if *k != "RANDOM".to_owned() {
assert!(output.contains(format!("{}={}", *k, *v)) ||
output.contains(format!("{}=\'{}\'", *k, *v)));
}
})
iotest!(fn test_add_to_env() {
- let new_env = ~[(~"RUN_TEST_NEW_ENV", ~"123")];
+ let new_env = ~[("RUN_TEST_NEW_ENV".to_owned(), "123".to_owned())];
let mut prog = run_env(Some(new_env));
let result = prog.wait_with_output();
#[cfg(unix)]
pub fn sleeper() -> Process {
- Process::new("sleep", [~"1000"]).unwrap()
+ Process::new("sleep", ["1000".to_owned()]).unwrap()
}
#[cfg(windows)]
pub fn sleeper() -> Process {
// There's a `timeout` command on windows, but it doesn't like having
// its output piped, so instead just ping ourselves a few times with
// gaps inbetweeen so we're sure this process is alive for awhile
- Process::new("ping", [~"127.0.0.1", ~"-n", ~"1000"]).unwrap()
+ Process::new("ping", ["127.0.0.1".to_owned(), "-n".to_owned(), "1000".to_owned()]).unwrap()
}
iotest!(fn test_kill() {
set_stdout(~w);
println!("hello!");
});
- assert_eq!(r.read_to_str().unwrap(), ~"hello!\n");
+ assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_owned());
})
iotest!(fn capture_stderr() {
use prelude::*;
use super::*;
use task;
+ use str::StrSlice;
#[test]
fn test_tls_multitask() {
static my_key: Key<~str> = &Key;
- set(my_key, ~"parent data");
+ set(my_key, "parent data".to_owned());
task::spawn(proc() {
// TLS shouldn't carry over.
assert!(get(my_key, |k| k.map(|k| (*k).clone())).is_none());
- set(my_key, ~"child data");
+ set(my_key, "child data".to_owned());
assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() ==
- ~"child data");
+ "child data".to_owned());
// should be cleaned up for us
});
// Must work multiple times
- assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data");
- assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data");
- assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"parent data");
+ assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == "parent data".to_owned());
+ assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == "parent data".to_owned());
+ assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == "parent data".to_owned());
}
#[test]
fn test_tls_overwrite() {
static my_key: Key<~str> = &Key;
- set(my_key, ~"first data");
- set(my_key, ~"next data"); // Shouldn't leak.
- assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == ~"next data");
+ set(my_key, "first data".to_owned());
+ set(my_key, "next data".to_owned()); // Shouldn't leak.
+ assert!(get(my_key, |k| k.map(|k| (*k).clone())).unwrap() == "next data".to_owned());
}
#[test]
fn test_tls_pop() {
static my_key: Key<~str> = &Key;
- set(my_key, ~"weasel");
- assert!(pop(my_key).unwrap() == ~"weasel");
+ set(my_key, "weasel".to_owned());
+ assert!(pop(my_key).unwrap() == "weasel".to_owned());
// Pop must remove the data from the map.
assert!(pop(my_key).is_none());
}
modify(my_key, |data| {
match data {
Some(ref val) => fail!("unwelcome value: {}", *val),
- None => Some(~"first data")
+ None => Some("first data".to_owned())
}
});
modify(my_key, |data| {
match data.as_ref().map(|s| s.as_slice()) {
- Some("first data") => Some(~"next data"),
+ Some("first data") => Some("next data".to_owned()),
Some(ref val) => fail!("wrong value: {}", *val),
None => fail!("missing value")
}
});
- assert!(pop(my_key).unwrap() == ~"next data");
+ assert!(pop(my_key).unwrap() == "next data".to_owned());
}
#[test]
// a stack smaller than 1 MB.
static my_key: Key<~str> = &Key;
task::spawn(proc() {
- set(my_key, ~"hax");
+ set(my_key, "hax".to_owned());
});
}
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
- set(str_key, ~"string data");
+ set(str_key, "string data".to_owned());
set(box_key, @());
set(int_key, 42);
});
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
- set(str_key, ~"string data");
- set(str_key, ~"string data 2");
+ set(str_key, "string data".to_owned());
+ set(str_key, "string data 2".to_owned());
set(box_key, @());
set(box_key, @());
set(int_key, 42);
static str_key: Key<~str> = &Key;
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
- set(str_key, ~"parent data");
+ set(str_key, "parent data".to_owned());
set(box_key, @());
task::spawn(proc() {
// spawn_linked
- set(str_key, ~"string data");
+ set(str_key, "string data".to_owned());
set(box_key, @());
set(int_key, 42);
fail!();
mod tests {
use mem::*;
use option::{Some,None};
+ use str::StrSlice;
#[test]
fn size_of_basic() {
#[test]
fn test_replace() {
- let mut x = Some(~"test");
+ let mut x = Some("test".to_owned());
let y = replace(&mut x, None);
assert!(x.is_none());
assert!(y.is_some());
use num::Bitwise;
use num::CheckedDiv;
use num::ToStrRadix;
+ use str::StrSlice;
#[test]
fn test_overflows() {
#[test]
fn test_to_str() {
- assert_eq!((0 as $T).to_str_radix(10u), ~"0");
- assert_eq!((1 as $T).to_str_radix(10u), ~"1");
- assert_eq!((-1 as $T).to_str_radix(10u), ~"-1");
- assert_eq!((127 as $T).to_str_radix(16u), ~"7f");
- assert_eq!((100 as $T).to_str_radix(10u), ~"100");
+ assert_eq!((0 as $T).to_str_radix(10u), "0".to_owned());
+ assert_eq!((1 as $T).to_str_radix(10u), "1".to_owned());
+ assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_owned());
+ assert_eq!((127 as $T).to_str_radix(16u), "7f".to_owned());
+ assert_eq!((100 as $T).to_str_radix(10u), "100".to_owned());
}
#[test]
fn test_int_to_str_overflow() {
let mut i8_val: i8 = 127_i8;
- assert_eq!(i8_val.to_str(), ~"127");
+ assert_eq!(i8_val.to_str(), "127".to_owned());
i8_val += 1 as i8;
- assert_eq!(i8_val.to_str(), ~"-128");
+ assert_eq!(i8_val.to_str(), "-128".to_owned());
let mut i16_val: i16 = 32_767_i16;
- assert_eq!(i16_val.to_str(), ~"32767");
+ assert_eq!(i16_val.to_str(), "32767".to_owned());
i16_val += 1 as i16;
- assert_eq!(i16_val.to_str(), ~"-32768");
+ assert_eq!(i16_val.to_str(), "-32768".to_owned());
let mut i32_val: i32 = 2_147_483_647_i32;
- assert_eq!(i32_val.to_str(), ~"2147483647");
+ assert_eq!(i32_val.to_str(), "2147483647".to_owned());
i32_val += 1 as i32;
- assert_eq!(i32_val.to_str(), ~"-2147483648");
+ assert_eq!(i32_val.to_str(), "-2147483648".to_owned());
let mut i64_val: i64 = 9_223_372_036_854_775_807_i64;
- assert_eq!(i64_val.to_str(), ~"9223372036854775807");
+ assert_eq!(i64_val.to_str(), "9223372036854775807".to_owned());
i64_val += 1 as i64;
- assert_eq!(i64_val.to_str(), ~"-9223372036854775808");
+ assert_eq!(i64_val.to_str(), "-9223372036854775808".to_owned());
}
#[test]
use num::CheckedDiv;
use num::Bitwise;
use num::ToStrRadix;
+ use str::StrSlice;
use u16;
#[test]
#[test]
pub fn test_to_str() {
- assert_eq!((0 as $T).to_str_radix(10u), ~"0");
- assert_eq!((1 as $T).to_str_radix(10u), ~"1");
- assert_eq!((2 as $T).to_str_radix(10u), ~"2");
- assert_eq!((11 as $T).to_str_radix(10u), ~"11");
- assert_eq!((11 as $T).to_str_radix(16u), ~"b");
- assert_eq!((255 as $T).to_str_radix(16u), ~"ff");
- assert_eq!((0xff as $T).to_str_radix(10u), ~"255");
+ assert_eq!((0 as $T).to_str_radix(10u), "0".to_owned());
+ assert_eq!((1 as $T).to_str_radix(10u), "1".to_owned());
+ assert_eq!((2 as $T).to_str_radix(10u), "2".to_owned());
+ assert_eq!((11 as $T).to_str_radix(10u), "11".to_owned());
+ assert_eq!((11 as $T).to_str_radix(16u), "b".to_owned());
+ assert_eq!((255 as $T).to_str_radix(16u), "ff".to_owned());
+ assert_eq!((0xff as $T).to_str_radix(10u), "255".to_owned());
}
#[test]
#[test]
fn test_uint_to_str_overflow() {
let mut u8_val: u8 = 255_u8;
- assert_eq!(u8_val.to_str(), ~"255");
+ assert_eq!(u8_val.to_str(), "255".to_owned());
u8_val += 1 as u8;
- assert_eq!(u8_val.to_str(), ~"0");
+ assert_eq!(u8_val.to_str(), "0".to_owned());
let mut u16_val: u16 = 65_535_u16;
- assert_eq!(u16_val.to_str(), ~"65535");
+ assert_eq!(u16_val.to_str(), "65535".to_owned());
u16_val += 1 as u16;
- assert_eq!(u16_val.to_str(), ~"0");
+ assert_eq!(u16_val.to_str(), "0".to_owned());
let mut u32_val: u32 = 4_294_967_295_u32;
- assert_eq!(u32_val.to_str(), ~"4294967295");
+ assert_eq!(u32_val.to_str(), "4294967295".to_owned());
u32_val += 1 as u32;
- assert_eq!(u32_val.to_str(), ~"0");
+ assert_eq!(u32_val.to_str(), "0".to_owned());
let mut u64_val: u64 = 18_446_744_073_709_551_615_u64;
- assert_eq!(u64_val.to_str(), ~"18446744073709551615");
+ assert_eq!(u64_val.to_str(), "18446744073709551615".to_owned());
u64_val += 1 as u64;
- assert_eq!(u64_val.to_str(), ~"0");
+ assert_eq!(u64_val.to_str(), "0".to_owned());
}
#[test]
/// to the value inside the original.
///
/// ```
- /// let num_as_str: Option<~str> = Some(~"10");
+ /// let num_as_str: Option<~str> = Some("10".to_owned());
/// // First, cast `Option<~str>` to `Option<&~str>` with `as_ref`,
/// // then consume *that* with `map`, leaving `num_as_str` on the stack.
/// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
/// Convert an `Option<~str>` into an `Option<uint>`, consuming the original:
///
/// ```
- /// let num_as_str: Option<~str> = Some(~"10");
+ /// let num_as_str: Option<~str> = Some("10".to_owned());
/// // `Option::map` takes self *by value*, consuming `num_as_str`
/// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
/// ```
#[test]
fn test_get_str() {
- let x = ~"test";
+ let x = "test".to_owned();
let addr_x = x.as_ptr();
let opt = Some(x);
let y = opt.unwrap();
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
- assert_eq!(Some(~"hello").unwrap(), ~"hello");
+ assert_eq!(Some("hello".to_owned()).unwrap(), "hello".to_owned());
}
#[test]
fn make_rand_name() -> ~str {
let mut rng = rand::task_rng();
- let n = ~"TEST" + rng.gen_ascii_str(10u);
+ let n = "TEST".to_owned() + rng.gen_ascii_str(10u);
assert!(getenv(n).is_none());
n
}
fn test_setenv() {
let n = make_rand_name();
setenv(n, "VALUE");
- assert_eq!(getenv(n), option::Some(~"VALUE"));
+ assert_eq!(getenv(n), option::Some("VALUE".to_owned()));
}
#[test]
let n = make_rand_name();
setenv(n, "1");
setenv(n, "2");
- assert_eq!(getenv(n), option::Some(~"2"));
+ assert_eq!(getenv(n), option::Some("2".to_owned()));
setenv(n, "");
- assert_eq!(getenv(n), option::Some(~""));
+ assert_eq!(getenv(n), option::Some("".to_owned()));
}
// Windows GetEnvironmentVariable requires some extra work to make sure
#[test]
#[ignore]
fn test_getenv_big() {
- let mut s = ~"";
+ let mut s = "".to_owned();
let mut i = 0;
while i < 100 {
s = s + "aaaaaaaaaa";
let mut e = env();
setenv(n, "VALUE");
- assert!(!e.contains(&(n.clone(), ~"VALUE")));
+ assert!(!e.contains(&(n.clone(), "VALUE".to_owned())));
e = env();
- assert!(e.contains(&(n, ~"VALUE")));
+ assert!(e.contains(&(n, "VALUE".to_owned())));
}
#[test]
use prelude::*;
use super::*;
use str;
+ use str::StrSlice;
macro_rules! t(
(s: $path:expr, $exp:expr) => (
t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
t!(s: "a/b/c", ["d", "/e"], "/e");
t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
- t!(s: "a/b/c", [~"d", ~"e"], "a/b/c/d/e");
+ t!(s: "a/b/c", ["d".to_owned(), "e".to_owned()], "a/b/c/d/e");
t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e"));
t!(v: b!("a/b/c"), [b!("d"), b!("/e"), b!("f")], b!("/e/f"));
t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e"));
t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
t!(s: "a/b/c", ["..", "d"], "a/b/d");
t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
- t!(s: "a/b/c", [~"d", ~"e"], "a/b/c/d/e");
+ t!(s: "a/b/c", ["d".to_owned(), "e".to_owned()], "a/b/c/d/e");
t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e"));
t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e"));
}
#[test]
fn test_display_str() {
let path = Path::new("foo");
- assert_eq!(path.display().to_str(), ~"foo");
+ assert_eq!(path.display().to_str(), "foo".to_owned());
let path = Path::new(b!("\\"));
- assert_eq!(path.filename_display().to_str(), ~"");
+ assert_eq!(path.filename_display().to_str(), "".to_owned());
let path = Path::new("foo");
let mo = path.display().as_maybe_owned();
t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
t!(s: "a\\b\\c", ["d", "\\e"], "\\e");
t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
- t!(s: "a\\b\\c", [~"d", ~"e"], "a\\b\\c\\d\\e");
+ t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e");
t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
t!(v: b!("a\\b\\c"), [b!("d"), b!("\\e"), b!("f")], b!("\\e\\f"));
t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d");
t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
- t!(s: "a\\b\\c", [~"d", ~"e"], "a\\b\\c\\d\\e");
+ t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e");
t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
b!("a\\b\\c\\d\\e"));
exact_test(&false, "false");
exact_test(&1.234, "1.234f64");
exact_test(&(&"hello"), "\"hello\"");
- exact_test(&(~"he\u10f3llo"), "~\"he\\u10f3llo\"");
+ // FIXME What do I do about this one?
+ exact_test(&("he\u10f3llo".to_owned()), "~\"he\\u10f3llo\"");
exact_test(&(@10), "@10");
exact_test(&(~10), "~10");
"@repr::P{a: 10, b: 1.234f64}");
exact_test(&(~P{a:10, b:1.234}),
"~repr::P{a: 10, b: 1.234f64}");
- exact_test(&(10u8, ~"hello"),
+ exact_test(&(10u8, "hello".to_owned()),
"(10u8, ~\"hello\")");
- exact_test(&(10u16, ~"hello"),
+ exact_test(&(10u16, "hello".to_owned()),
"(10u16, ~\"hello\")");
- exact_test(&(10u32, ~"hello"),
+ exact_test(&(10u32, "hello".to_owned()),
"(10u32, ~\"hello\")");
- exact_test(&(10u64, ~"hello"),
+ exact_test(&(10u64, "hello".to_owned()),
"(10u64, ~\"hello\")");
exact_test(&(&[1, 2]), "&[1, 2]");
mod tests {
use super::*;
use prelude::*;
+ use str::StrSlice;
use iter::range;
pub fn op1() -> Result<int, ~str> { Ok(666) }
- pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
+ pub fn op2() -> Result<int, ~str> { Err("sadface".to_owned()) }
#[test]
pub fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
- assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");
+ assert_eq!(op1().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "bad".to_owned());
- assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
- assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
+ 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());
}
#[test]
pub fn test_and_then() {
assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
- assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
+ assert_eq!(op1().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
+ "bad".to_owned());
- assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
- assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
+ assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(),
+ "sadface".to_owned());
+ assert_eq!(op2().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
+ "sadface".to_owned());
}
#[test]
pub fn test_or() {
assert_eq!(op1().or(Ok(667)).unwrap(), 666);
- assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
+ assert_eq!(op1().or(Err("bad".to_owned())).unwrap(), 666);
assert_eq!(op2().or(Ok(667)).unwrap(), 667);
- assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
+ assert_eq!(op2().or(Err("bad".to_owned())).unwrap_err(), "bad".to_owned());
}
#[test]
assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
- assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
+ assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(),
+ "sadface!".to_owned());
}
#[test]
pub fn test_impl_map() {
- assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
- assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
+ 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()));
}
#[test]
pub fn test_impl_map_err() {
- assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
- assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
+ 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()));
}
#[test]
#[test]
pub fn test_to_str() {
let ok: Result<int, ~str> = Ok(100);
- let err: Result<int, ~str> = Err(~"Err");
+ let err: Result<int, ~str> = Err("Err".to_owned());
- assert_eq!(ok.to_str(), ~"Ok(100)");
- assert_eq!(err.to_str(), ~"Err(Err)");
+ assert_eq!(ok.to_str(), "Ok(100)".to_owned());
+ assert_eq!(err.to_str(), "Err(Err)".to_owned());
}
#[test]
pub fn test_fmt_default() {
let ok: Result<int, ~str> = Ok(100);
- let err: Result<int, ~str> = Err(~"Err");
+ let err: Result<int, ~str> = Err("Err".to_owned());
- assert_eq!(format!("{}", ok), ~"Ok(100)");
- assert_eq!(format!("{}", err), ~"Err(Err)");
+ assert_eq!(format!("{}", ok), "Ok(100)".to_owned());
+ assert_eq!(format!("{}", err), "Err(Err)".to_owned());
}
#[test]
pub fn test_unwrap_or() {
let ok: Result<int, ~str> = Ok(100);
- let ok_err: Result<int, ~str> = Err(~"Err");
+ let ok_err: Result<int, ~str> = Err("Err".to_owned());
assert_eq!(ok.unwrap_or(50), 100);
assert_eq!(ok_err.unwrap_or(50), 50);
#[test]
pub fn test_unwrap_or_else() {
fn handler(msg: ~str) -> int {
- if msg == ~"I got this." {
+ if msg == "I got this.".to_owned() {
50
} else {
fail!("BadBad")
}
let ok: Result<int, ~str> = Ok(100);
- let ok_err: Result<int, ~str> = Err(~"I got this.");
+ let ok_err: Result<int, ~str> = Err("I got this.".to_owned());
assert_eq!(ok.unwrap_or_handle(handler), 100);
assert_eq!(ok_err.unwrap_or_handle(handler), 50);
#[should_fail]
pub fn test_unwrap_or_else_failure() {
fn handler(msg: ~str) -> int {
- if msg == ~"I got this." {
+ if msg == "I got this.".to_owned() {
50
} else {
fail!("BadBad")
}
}
- let bad_err: Result<int, ~str> = Err(~"Unrecoverable mess.");
+ let bad_err: Result<int, ~str> = Err("Unrecoverable mess.".to_owned());
let _ : int = bad_err.unwrap_or_handle(handler);
}
}
use clone::Clone;
use option::{Option, Some, None};
use iter::Iterator;
+ use str::StrSlice;
use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
use mem;
#[cfg(not(test))] use ptr::RawPtr;
fn tls() {
use local_data;
local_data_key!(key: @~str)
- local_data::set(key, @~"data");
- assert!(*local_data::get(key, |k| k.map(|k| *k)).unwrap() == ~"data");
+ local_data::set(key, @"data".to_owned());
+ assert!(*local_data::get(key, |k| k.map(|k| *k)).unwrap() == "data".to_owned());
local_data_key!(key2: @~str)
- local_data::set(key2, @~"data");
- assert!(*local_data::get(key2, |k| k.map(|k| *k)).unwrap() == ~"data");
+ local_data::set(key2, @"data".to_owned());
+ assert!(*local_data::get(key2, |k| k.map(|k| *k)).unwrap() == "data".to_owned());
}
#[test]
/// # Examples
///
/// ```rust
- /// let v = ~[~"a", ~"b"];
+ /// let v = ~["a".to_owned(), "b".to_owned()];
/// for s in v.move_iter() {
/// // s has type ~str, not &~str
/// println!("{}", s);
/// # Example
///
/// ```rust
- /// let mut v = ~[~"foo", ~"bar", ~"baz"];
+ /// let mut v = ~["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
///
/// unsafe {
- /// // `~"baz"` is deallocated.
- /// v.unsafe_set(2, ~"qux");
+ /// // `"baz".to_owned()` is deallocated.
+ /// v.unsafe_set(2, "qux".to_owned());
///
/// // Out of bounds: could cause a crash, or overwriting
/// // other data, or something else.
- /// // v.unsafe_set(10, ~"oops");
+ /// // v.unsafe_set(10, "oops".to_owned());
/// }
/// ```
unsafe fn unsafe_set(self, index: uint, val: T);
/// # Example
///
/// ```rust
- /// let mut v = [~"foo", ~"bar"];
+ /// let mut v = ["foo".to_owned(), "bar".to_owned()];
///
- /// // memory leak! `~"bar"` is not deallocated.
- /// unsafe { v.init_elem(1, ~"baz"); }
+ /// // memory leak! `"bar".to_owned()` is not deallocated.
+ /// unsafe { v.init_elem(1, "baz".to_owned()); }
/// ```
unsafe fn init_elem(self, i: uint, val: T);
assert_eq!(it.next(), None);
}
{
- let v = [~"Hello"];
+ let v = ["Hello".to_owned()];
let mut it = v.permutations();
assert_eq!(it.next(), None);
}
})
)
let empty: ~[int] = ~[];
- test_show_vec!(empty, ~"[]");
- test_show_vec!(~[1], ~"[1]");
- test_show_vec!(~[1, 2, 3], ~"[1, 2, 3]");
- test_show_vec!(~[~[], ~[1u], ~[1u, 1u]], ~"[[], [1], [1, 1]]");
+ test_show_vec!(empty, "[]".to_owned());
+ test_show_vec!(~[1], "[1]".to_owned());
+ test_show_vec!(~[1, 2, 3], "[1, 2, 3]".to_owned());
+ test_show_vec!(~[~[], ~[1u], ~[1u, 1u]], "[[], [1], [1, 1]]".to_owned());
}
#[test]
let xs = vec![Foo, Foo, Foo];
assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
- ~"~[slice::tests::Foo, slice::tests::Foo]");
+ "~[slice::tests::Foo, slice::tests::Foo]".to_owned());
let xs: [Foo, ..3] = [Foo, Foo, Foo];
assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
- ~"~[slice::tests::Foo, slice::tests::Foo]");
+ "~[slice::tests::Foo, slice::tests::Foo]".to_owned());
cnt = 0;
for f in xs.iter() {
assert!(*f == Foo);
```rust
fn main() {
- let owned_string = ~"I am an owned string";
+ 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
}
impl<'a, S: Str> StrVector for &'a [S] {
fn concat(&self) -> ~str {
- if self.is_empty() { return ~""; }
+ if self.is_empty() { return "".to_owned(); }
// `len` calculation may overflow but push_str but will check boundaries
let len = self.iter().map(|s| s.as_slice().len()).sum();
}
fn connect(&self, sep: &str) -> ~str {
- if self.is_empty() { return ~""; }
+ if self.is_empty() { return "".to_owned(); }
// concat is faster
if sep.is_empty() { return self.concat(); }
/// // 𝄞music
/// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
-/// assert_eq!(str::from_utf16(v), Some(~"𝄞music"));
+/// assert_eq!(str::from_utf16(v), Some("𝄞music".to_owned()));
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
/// 0xD834];
///
/// assert_eq!(str::from_utf16_lossy(v),
-/// ~"𝄞mus\uFFFDic\uFFFD");
+/// "𝄞mus\uFFFDic\uFFFD".to_owned());
/// ```
pub fn from_utf16_lossy(v: &[u16]) -> ~str {
utf16_items(v).map(|c| c.to_char_lossy()).collect()
let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
let b = a.as_ptr();
let c = from_buf_len(b, 3u);
- assert_eq!(c, ~"AAA");
+ assert_eq!(c, "AAA".to_owned());
}
}
}
}
impl Default for ~str {
- fn default() -> ~str { ~"" }
+ fn default() -> ~str { "".to_owned() }
}
#[cfg(test)]
#[test]
fn test_eq() {
- assert!((eq(&~"", &~"")));
- assert!((eq(&~"foo", &~"foo")));
- assert!((!eq(&~"foo", &~"bar")));
+ assert!((eq(&"".to_owned(), &"".to_owned())));
+ assert!((eq(&"foo".to_owned(), &"foo".to_owned())));
+ assert!((!eq(&"foo".to_owned(), &"bar".to_owned())));
}
#[test]
#[test]
fn test_collect() {
- let empty = ~"";
+ let empty = "".to_owned();
let s: ~str = empty.chars().collect();
assert_eq!(empty, s);
- let data = ~"ประเทศไทย中";
+ let data = "ประเทศไทย中".to_owned();
let s: ~str = data.chars().collect();
assert_eq!(data, s);
}
#[test]
fn test_into_bytes() {
- let data = ~"asdf";
+ let data = "asdf".to_owned();
let buf = data.into_bytes();
assert_eq!(bytes!("asdf"), buf.as_slice());
}
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";
+ 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));
fn t(v: &[~str], s: &str) {
assert_eq!(v.concat(), s.to_str());
}
- t([~"you", ~"know", ~"I'm", ~"no", ~"good"], "youknowI'mnogood");
+ t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(),
+ "no".to_owned(), "good".to_owned()], "youknowI'mnogood");
let v: &[~str] = [];
t(v, "");
- t([~"hi"], "hi");
+ t(["hi".to_owned()], "hi");
}
#[test]
fn t(v: &[~str], sep: &str, s: &str) {
assert_eq!(v.connect(sep), s.to_str());
}
- t([~"you", ~"know", ~"I'm", ~"no", ~"good"],
+ 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] = [];
t(v, " ", "");
- t([~"hi"], " ", "hi");
+ t(["hi".to_owned()], " ", "hi");
}
#[test]
#[test]
fn test_repeat() {
- assert_eq!("x".repeat(4), ~"xxxx");
- assert_eq!("hi".repeat(4), ~"hihihihi");
- assert_eq!("ไท华".repeat(3), ~"ไท华ไท华ไท华");
- assert_eq!("".repeat(4), ~"");
- assert_eq!("hi".repeat(0), ~"");
+ assert_eq!("x".repeat(4), "xxxx".to_owned());
+ assert_eq!("hi".repeat(4), "hihihihi".to_owned());
+ assert_eq!("ไท华".repeat(3), "ไท华ไท华ไท华".to_owned());
+ assert_eq!("".repeat(4), "".to_owned());
+ assert_eq!("hi".repeat(0), "".to_owned());
}
#[test]
#[test]
fn test_replace() {
let a = "a";
- assert_eq!("".replace(a, "b"), ~"");
- assert_eq!("a".replace(a, "b"), ~"b");
- assert_eq!("ab".replace(a, "b"), ~"bb");
+ assert_eq!("".replace(a, "b"), "".to_owned());
+ assert_eq!("a".replace(a, "b"), "b".to_owned());
+ assert_eq!("ab".replace(a, "b"), "bb".to_owned());
let test = "test";
assert!(" test test ".replace(test, "toast") ==
- ~" toast toast ");
- assert_eq!(" test test ".replace(test, ""), ~" ");
+ " toast toast ".to_owned());
+ assert_eq!(" test test ".replace(test, ""), " ".to_owned());
}
#[test]
fn test_replace_2a() {
- let data = ~"ประเทศไทย中华";
- let repl = ~"دولة الكويت";
+ let data = "ประเทศไทย中华".to_owned();
+ let repl = "دولة الكويت".to_owned();
- let a = ~"ประเ";
- let a2 = ~"دولة الكويتทศไทย中华";
+ let a = "ประเ".to_owned();
+ let a2 = "دولة الكويتทศไทย中华".to_owned();
assert_eq!(data.replace(a, repl), a2);
}
#[test]
fn test_replace_2b() {
- let data = ~"ประเทศไทย中华";
- let repl = ~"دولة الكويت";
+ let data = "ประเทศไทย中华".to_owned();
+ let repl = "دولة الكويت".to_owned();
- let b = ~"ะเ";
- let b2 = ~"ปรدولة الكويتทศไทย中华";
+ let b = "ะเ".to_owned();
+ let b2 = "ปรدولة الكويتทศไทย中华".to_owned();
assert_eq!(data.replace(b, repl), b2);
}
#[test]
fn test_replace_2c() {
- let data = ~"ประเทศไทย中华";
- let repl = ~"دولة الكويت";
+ let data = "ประเทศไทย中华".to_owned();
+ let repl = "دولة الكويت".to_owned();
- let c = ~"中华";
- let c2 = ~"ประเทศไทยدولة الكويت";
+ let c = "中华".to_owned();
+ let c2 = "ประเทศไทยدولة الكويت".to_owned();
assert_eq!(data.replace(c, repl), c2);
}
#[test]
fn test_replace_2d() {
- let data = ~"ประเทศไทย中华";
- let repl = ~"دولة الكويت";
+ let data = "ประเทศไทย中华".to_owned();
+ let repl = "دولة الكويت".to_owned();
- let d = ~"ไท华";
+ let d = "ไท华".to_owned();
assert_eq!(data.replace(d, repl), data);
}
let a = ~[65, 65, 65, 65, 65, 65, 65, 0];
let b = a.as_ptr();
let c = raw::from_c_str(b);
- assert_eq!(c, ~"AAAAAAA");
+ assert_eq!(c, "AAAAAAA".to_owned());
}
}
fn test_as_bytes_fail() {
// Don't double free. (I'm not sure if this exercises the
// original problem code path anymore.)
- let s = ~"";
+ let s = "".to_owned();
let _bytes = s.as_bytes();
fail!();
}
#[test]
fn vec_str_conversions() {
- let s1: ~str = ~"All mimsy were the borogoves";
+ let s1: ~str = "All mimsy were the borogoves".to_owned();
let v: ~[u8] = s1.as_bytes().to_owned();
let s2: ~str = from_utf8(v).unwrap().to_owned();
assert!(!"abcde".contains("def"));
assert!(!"".contains("a"));
- let data = ~"ประเทศไทย中华Việt Nam";
+ let data = "ประเทศไทย中华Việt Nam".to_owned();
assert!(data.contains("ประเ"));
assert!(data.contains("ะเ"));
assert!(data.contains("中华"));
#[test]
fn test_utf16() {
let pairs =
- [(~"𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n",
+ [("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n".to_owned(),
~[0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
0xd800_u16, 0xdf30_u16, 0x000a_u16]),
- (~"𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n",
+ ("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n".to_owned(),
~[0xd801_u16, 0xdc12_u16, 0xd801_u16,
0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
0x000a_u16]),
- (~"𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n",
+ ("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n".to_owned(),
~[0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
- (~"𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n",
+ ("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n".to_owned(),
~[0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
0x000a_u16 ]),
// Issue #12318, even-numbered non-BMP planes
- (~"\U00020000",
+ ("\U00020000".to_owned(),
~[0xD840, 0xDC00])];
for p in pairs.iter() {
fn test_utf16_lossy() {
// completely positive cases tested above.
// lead + eof
- assert_eq!(from_utf16_lossy([0xD800]), ~"\uFFFD");
+ assert_eq!(from_utf16_lossy([0xD800]), "\uFFFD".to_owned());
// lead + lead
- assert_eq!(from_utf16_lossy([0xD800, 0xD800]), ~"\uFFFD\uFFFD");
+ assert_eq!(from_utf16_lossy([0xD800, 0xD800]), "\uFFFD\uFFFD".to_owned());
// isolated trail
- assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), ~"a\uFFFD");
+ assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), "a\uFFFD".to_owned());
// general
- assert_eq!(from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]), ~"\uFFFD𐒋\uFFFD");
+ assert_eq!(from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]), "\uFFFD𐒋\uFFFD".to_owned());
}
#[test]
#[test]
fn test_char_at() {
- let s = ~"ศไทย中华Việt Nam";
+ let s = "ศไทย中华Việt Nam".to_owned();
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
let mut pos = 0;
for ch in v.iter() {
#[test]
fn test_char_at_reverse() {
- let s = ~"ศไทย中华Việt Nam";
+ let s = "ศไทย中华Việt Nam".to_owned();
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
let mut pos = s.len();
for ch in v.rev_iter() {
#[test]
fn test_escape_unicode() {
- assert_eq!("abc".escape_unicode(), ~"\\x61\\x62\\x63");
- assert_eq!("a c".escape_unicode(), ~"\\x61\\x20\\x63");
- assert_eq!("\r\n\t".escape_unicode(), ~"\\x0d\\x0a\\x09");
- assert_eq!("'\"\\".escape_unicode(), ~"\\x27\\x22\\x5c");
- assert_eq!("\x00\x01\xfe\xff".escape_unicode(), ~"\\x00\\x01\\xfe\\xff");
- assert_eq!("\u0100\uffff".escape_unicode(), ~"\\u0100\\uffff");
- assert_eq!("\U00010000\U0010ffff".escape_unicode(), ~"\\U00010000\\U0010ffff");
- assert_eq!("ab\ufb00".escape_unicode(), ~"\\x61\\x62\\ufb00");
- assert_eq!("\U0001d4ea\r".escape_unicode(), ~"\\U0001d4ea\\x0d");
+ assert_eq!("abc".escape_unicode(), "\\x61\\x62\\x63".to_owned());
+ assert_eq!("a c".escape_unicode(), "\\x61\\x20\\x63".to_owned());
+ assert_eq!("\r\n\t".escape_unicode(), "\\x0d\\x0a\\x09".to_owned());
+ assert_eq!("'\"\\".escape_unicode(), "\\x27\\x22\\x5c".to_owned());
+ assert_eq!("\x00\x01\xfe\xff".escape_unicode(), "\\x00\\x01\\xfe\\xff".to_owned());
+ assert_eq!("\u0100\uffff".escape_unicode(), "\\u0100\\uffff".to_owned());
+ assert_eq!("\U00010000\U0010ffff".escape_unicode(), "\\U00010000\\U0010ffff".to_owned());
+ assert_eq!("ab\ufb00".escape_unicode(), "\\x61\\x62\\ufb00".to_owned());
+ assert_eq!("\U0001d4ea\r".escape_unicode(), "\\U0001d4ea\\x0d".to_owned());
}
#[test]
fn test_escape_default() {
- assert_eq!("abc".escape_default(), ~"abc");
- assert_eq!("a c".escape_default(), ~"a c");
- assert_eq!("\r\n\t".escape_default(), ~"\\r\\n\\t");
- assert_eq!("'\"\\".escape_default(), ~"\\'\\\"\\\\");
- assert_eq!("\u0100\uffff".escape_default(), ~"\\u0100\\uffff");
- assert_eq!("\U00010000\U0010ffff".escape_default(), ~"\\U00010000\\U0010ffff");
- assert_eq!("ab\ufb00".escape_default(), ~"ab\\ufb00");
- assert_eq!("\U0001d4ea\r".escape_default(), ~"\\U0001d4ea\\r");
+ assert_eq!("abc".escape_default(), "abc".to_owned());
+ assert_eq!("a c".escape_default(), "a c".to_owned());
+ assert_eq!("\r\n\t".escape_default(), "\\r\\n\\t".to_owned());
+ assert_eq!("'\"\\".escape_default(), "\\'\\\"\\\\".to_owned());
+ assert_eq!("\u0100\uffff".escape_default(), "\\u0100\\uffff".to_owned());
+ assert_eq!("\U00010000\U0010ffff".escape_default(), "\\U00010000\\U0010ffff".to_owned());
+ assert_eq!("ab\ufb00".escape_default(), "ab\\ufb00".to_owned());
+ assert_eq!("\U0001d4ea\r".escape_default(), "\\U0001d4ea\\r".to_owned());
}
#[test]
#[test]
fn test_char_range_at() {
- let data = ~"b¢€𤭢𤭢€¢b";
+ let data = "b¢€𤭢𤭢€¢b".to_owned();
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);
);
t!("foo", "bar", "foobar");
- t!("foo", ~"bar", "foobar");
+ t!("foo", "bar".to_owned(), "foobar");
t!("ศไทย中", "华Việt Nam", "ศไทย中华Việt Nam");
- 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";
+ let s = "ศไทย中华Việt Nam".to_owned();
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
let mut pos = 0;
#[test]
fn test_rev_iterator() {
use iter::*;
- let s = ~"ศไทย中华Việt Nam";
+ let s = "ศไทย中华Việt Nam".to_owned();
let v = ~['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
let mut pos = 0;
#[test]
fn test_bytesator() {
- let s = ~"ศไทย中华Việt Nam";
+ let s = "ศไทย中华Việt Nam".to_owned();
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,
#[test]
fn test_bytes_revator() {
- let s = ~"ศไทย中华Việt Nam";
+ let s = "ศไทย中华Việt Nam".to_owned();
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,
#[test]
fn test_nfd_chars() {
- assert_eq!("abc".nfd_chars().collect::<~str>(), ~"abc");
- assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<~str>(), ~"d\u0307\u01c4");
- assert_eq!("\u2026".nfd_chars().collect::<~str>(), ~"\u2026");
- assert_eq!("\u2126".nfd_chars().collect::<~str>(), ~"\u03a9");
- assert_eq!("\u1e0b\u0323".nfd_chars().collect::<~str>(), ~"d\u0323\u0307");
- assert_eq!("\u1e0d\u0307".nfd_chars().collect::<~str>(), ~"d\u0323\u0307");
- assert_eq!("a\u0301".nfd_chars().collect::<~str>(), ~"a\u0301");
- assert_eq!("\u0301a".nfd_chars().collect::<~str>(), ~"\u0301a");
- assert_eq!("\ud4db".nfd_chars().collect::<~str>(), ~"\u1111\u1171\u11b6");
- assert_eq!("\uac1c".nfd_chars().collect::<~str>(), ~"\u1100\u1162");
+ 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());
}
#[test]
fn test_nfkd_chars() {
- assert_eq!("abc".nfkd_chars().collect::<~str>(), ~"abc");
- assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<~str>(), ~"d\u0307DZ\u030c");
- assert_eq!("\u2026".nfkd_chars().collect::<~str>(), ~"...");
- assert_eq!("\u2126".nfkd_chars().collect::<~str>(), ~"\u03a9");
- assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<~str>(), ~"d\u0323\u0307");
- assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<~str>(), ~"d\u0323\u0307");
- assert_eq!("a\u0301".nfkd_chars().collect::<~str>(), ~"a\u0301");
- assert_eq!("\u0301a".nfkd_chars().collect::<~str>(), ~"\u0301a");
- assert_eq!("\ud4db".nfkd_chars().collect::<~str>(), ~"\u1111\u1171\u11b6");
- assert_eq!("\uac1c".nfkd_chars().collect::<~str>(), ~"\u1100\u1162");
+ 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());
}
#[test]
v.iter().map(|x| x.len()).sum()
}
- let s = ~"01234";
+ let s = "01234".to_owned();
assert_eq!(5, sum_len(["012", "", "34"]));
- assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
+ assert_eq!(5, sum_len(["01".to_owned(), "2".to_owned(), "34".to_owned(), "".to_owned()]));
assert_eq!(5, sum_len([s.as_slice()]));
}
#[test]
fn test_str_from_utf8_owned() {
let xs = bytes!("hello").to_owned();
- assert_eq!(from_utf8_owned(xs), Some(~"hello"));
+ assert_eq!(from_utf8_owned(xs), Some("hello".to_owned()));
let xs = bytes!("ศไทย中华Việt Nam").to_owned();
- assert_eq!(from_utf8_owned(xs), Some(~"ศไทย中华Việt Nam"));
+ assert_eq!(from_utf8_owned(xs), Some("ศไทย中华Việt Nam".to_owned()));
let xs = bytes!("hello", 0xff).to_owned();
assert_eq!(from_utf8_owned(xs), None);
assert_eq!(from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam"));
let xs = bytes!("Hello", 0xC2, " There", 0xFF, " Goodbye");
- assert_eq!(from_utf8_lossy(xs), Owned(~"Hello\uFFFD There\uFFFD Goodbye"));
+ assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD There\uFFFD Goodbye".to_owned()));
let xs = bytes!("Hello", 0xC0, 0x80, " There", 0xE6, 0x83, " Goodbye");
- assert_eq!(from_utf8_lossy(xs), Owned(~"Hello\uFFFD\uFFFD There\uFFFD Goodbye"));
+ assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD\uFFFD There\uFFFD Goodbye".to_owned()));
let xs = bytes!(0xF5, "foo", 0xF5, 0x80, "bar");
- assert_eq!(from_utf8_lossy(xs), Owned(~"\uFFFDfoo\uFFFD\uFFFDbar"));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFD\uFFFDbar".to_owned()));
let xs = bytes!(0xF1, "foo", 0xF1, 0x80, "bar", 0xF1, 0x80, 0x80, "baz");
- assert_eq!(from_utf8_lossy(xs), Owned(~"\uFFFDfoo\uFFFDbar\uFFFDbaz"));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFDbaz".to_owned()));
let xs = bytes!(0xF4, "foo", 0xF4, 0x80, "bar", 0xF4, 0xBF, "baz");
- assert_eq!(from_utf8_lossy(xs), Owned(~"\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz"));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz".to_owned()));
let xs = bytes!(0xF0, 0x80, 0x80, 0x80, "foo", 0xF0, 0x90, 0x80, 0x80, "bar");
- assert_eq!(from_utf8_lossy(xs), Owned(~"\uFFFD\uFFFD\uFFFD\uFFFDfoo\U00010000bar"));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFD\uFFFD\
+ foo\U00010000bar".to_owned()));
// surrogates
let xs = bytes!(0xED, 0xA0, 0x80, "foo", 0xED, 0xBF, 0xBF, "bar");
- assert_eq!(from_utf8_lossy(xs), Owned(~"\uFFFD\uFFFD\uFFFDfoo\uFFFD\uFFFD\uFFFDbar"));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFDfoo\
+ \uFFFD\uFFFD\uFFFDbar".to_owned()));
}
#[test]
fn test_from_str() {
let owned: Option<~str> = from_str(&"string");
- assert_eq!(owned, Some(~"string"));
+ assert_eq!(owned, Some("string".to_owned()));
}
#[test]
let s = Slice("abcde");
assert_eq!(s.len(), 5);
assert_eq!(s.as_slice(), "abcde");
- assert_eq!(s.to_str(), ~"abcde");
- assert_eq!(format!("{}", s), ~"abcde");
- assert!(s.lt(&Owned(~"bcdef")));
+ assert_eq!(s.to_str(), "abcde".to_owned());
+ assert_eq!(format!("{}", s), "abcde".to_owned());
+ assert!(s.lt(&Owned("bcdef".to_owned())));
assert_eq!(Slice(""), Default::default());
- let o = Owned(~"abcde");
+ let o = Owned("abcde".to_owned());
assert_eq!(o.len(), 5);
assert_eq!(o.as_slice(), "abcde");
- assert_eq!(o.to_str(), ~"abcde");
- assert_eq!(format!("{}", o), ~"abcde");
+ assert_eq!(o.to_str(), "abcde".to_owned());
+ assert_eq!(format!("{}", o), "abcde".to_owned());
assert!(o.lt(&Slice("bcdef")));
- assert_eq!(Owned(~""), Default::default());
+ assert_eq!(Owned("".to_owned()), Default::default());
assert!(s.cmp(&o) == Equal);
assert!(s.equiv(&o));
assert!(s.is_slice());
assert!(!s.is_owned());
- let o = Owned(~"abcde");
+ let o = Owned("abcde".to_owned());
assert!(!o.is_slice());
assert!(o.is_owned());
}
#[test]
fn test_maybe_owned_clone() {
- assert_eq!(Owned(~"abcde"), Slice("abcde").clone());
- assert_eq!(Owned(~"abcde"), Owned(~"abcde").clone());
+ assert_eq!(Owned("abcde".to_owned()), Slice("abcde").clone());
+ assert_eq!(Owned("abcde".to_owned()), Owned("abcde".to_owned()).clone());
assert_eq!(Slice("abcde"), Slice("abcde").clone());
- assert_eq!(Slice("abcde"), Owned(~"abcde").clone());
+ assert_eq!(Slice("abcde"), Owned("abcde".to_owned()).clone());
}
#[test]
fn test_maybe_owned_into_owned() {
- assert_eq!(Slice("abcde").into_owned(), ~"abcde");
- assert_eq!(Owned(~"abcde").into_owned(), ~"abcde");
+ assert_eq!(Slice("abcde").into_owned(), "abcde".to_owned());
+ assert_eq!(Owned("abcde".to_owned()).into_owned(), "abcde".to_owned());
}
#[test]
fn test_into_maybe_owned() {
assert_eq!("abcde".into_maybe_owned(), Slice("abcde"));
- assert_eq!((~"abcde").into_maybe_owned(), Slice("abcde"));
- assert_eq!("abcde".into_maybe_owned(), Owned(~"abcde"));
- assert_eq!((~"abcde").into_maybe_owned(), Owned(~"abcde"));
+ assert_eq!(("abcde".to_owned()).into_maybe_owned(), Slice("abcde"));
+ assert_eq!("abcde".into_maybe_owned(), Owned("abcde".to_owned()));
+ assert_eq!(("abcde".to_owned()).into_maybe_owned(), Owned("abcde".to_owned()));
}
}
#[test]
fn arclike_newN() {
// Tests that the many-refcounts-at-once constructors don't leak.
- let _ = UnsafeArc::new2(~~"hello");
- let x = UnsafeArc::newN(~~"hello", 0);
+ let _ = UnsafeArc::new2("hello".to_owned().to_owned());
+ let x = UnsafeArc::newN("hello".to_owned().to_owned(), 0);
assert_eq!(x.len(), 0)
- let x = UnsafeArc::newN(~~"hello", 1);
+ let x = UnsafeArc::newN("hello".to_owned().to_owned(), 1);
assert_eq!(x.len(), 1)
- let x = UnsafeArc::newN(~~"hello", 10);
+ let x = UnsafeArc::newN("hello".to_owned().to_owned(), 10);
assert_eq!(x.len(), 10)
}
}
#[cfg(test)] use any::{AnyOwnExt, AnyRefExt};
#[cfg(test)] use result;
+#[cfg(test)] use str::StrSlice;
/// Indicates the manner in which a task exited.
///
#[test]
fn test_owned_named_task() {
- task().named(~"ada lovelace").spawn(proc() {
+ task().named("ada lovelace".to_owned()).spawn(proc() {
with_task_name(|name| {
assert!(name.unwrap() == "ada lovelace");
})
#[test]
fn test_try_success() {
match try(proc() {
- ~"Success!"
+ "Success!".to_owned()
}).as_ref().map(|s| s.as_slice()) {
result::Ok("Success!") => (),
_ => fail!()
#[test]
fn test_try_fail_message_owned_str() {
match try(proc() {
- fail!(~"owned string");
+ fail!("owned string".to_owned());
}) {
Err(e) => {
type T = ~str;
assert!(e.is::<T>());
- assert_eq!(*e.move::<T>().unwrap(), ~"owned string");
+ assert_eq!(*e.move::<T>().unwrap(), "owned string".to_owned());
}
Ok(()) => fail!()
}
#[cfg(test)]
mod tests {
use super::*;
+ use str::StrSlice;
#[test]
fn test_simple_types() {
- assert_eq!(1i.to_str(), ~"1");
- assert_eq!((-1i).to_str(), ~"-1");
- assert_eq!(200u.to_str(), ~"200");
- assert_eq!(2u8.to_str(), ~"2");
- assert_eq!(true.to_str(), ~"true");
- assert_eq!(false.to_str(), ~"false");
- assert_eq!(().to_str(), ~"()");
- assert_eq!((~"hi").to_str(), ~"hi");
+ assert_eq!(1i.to_str(), "1".to_owned());
+ assert_eq!((-1i).to_str(), "-1".to_owned());
+ assert_eq!(200u.to_str(), "200".to_owned());
+ assert_eq!(2u8.to_str(), "2".to_owned());
+ assert_eq!(true.to_str(), "true".to_owned());
+ assert_eq!(false.to_str(), "false".to_owned());
+ assert_eq!(().to_str(), "()".to_owned());
+ assert_eq!(("hi".to_owned()).to_str(), "hi".to_owned());
}
#[test]
fn test_vectors() {
let x: ~[int] = ~[];
- assert_eq!(x.to_str(), ~"[]");
- assert_eq!((~[1]).to_str(), ~"[1]");
- assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
+ assert_eq!(x.to_str(), "[]".to_owned());
+ assert_eq!((~[1]).to_str(), "[1]".to_owned());
+ assert_eq!((~[1, 2, 3]).to_str(), "[1, 2, 3]".to_owned());
assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
- ~"[[], [1], [1, 1]]");
+ "[[], [1], [1, 1]]".to_owned());
}
}
use super::*;
use clone::Clone;
use cmp::*;
+ use str::StrSlice;
#[test]
fn test_clone() {
- let a = (1, ~"2");
+ let a = (1, "2".to_owned());
let b = a.clone();
assert_eq!(a, b);
}
#[test]
fn test_show() {
- assert_eq!(format!("{}", (1,)), ~"(1,)");
- assert_eq!(format!("{}", (1, true)), ~"(1, true)");
- assert_eq!(format!("{}", (1, ~"hi", true)), ~"(1, hi, true)");
+ 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());
}
}
/// # Example
///
/// ```rust
- /// let v = vec!(~"a", ~"b");
+ /// let v = vec!("a".to_owned(), "b".to_owned());
/// for s in v.move_iter() {
/// // s has type ~str, not &~str
/// println!("{}", s);
///
/// # Example
/// ```rust
- /// let mut v = vec!(~"foo", ~"bar", ~"baz", ~"qux");
+ /// let mut v = vec!("foo".to_owned(), "bar".to_owned(), "baz".to_owned(), "qux".to_owned());
///
- /// assert_eq!(v.swap_remove(1), Some(~"bar"));
- /// assert_eq!(v, vec!(~"foo", ~"qux", ~"baz"));
+ /// assert_eq!(v.swap_remove(1), Some("bar".to_owned()));
+ /// assert_eq!(v, vec!("foo".to_owned(), "qux".to_owned(), "baz".to_owned()));
///
- /// assert_eq!(v.swap_remove(0), Some(~"foo"));
- /// assert_eq!(v, vec!(~"baz", ~"qux"));
+ /// assert_eq!(v.swap_remove(0), Some("foo".to_owned()));
+ /// assert_eq!(v, vec!("baz".to_owned(), "qux".to_owned()));
///
/// assert_eq!(v.swap_remove(2), None);
/// ```
pub fn DuplexStream1() {
let (left, right) = duplex();
- left.send(~"abc");
+ left.send("abc".to_owned());
right.send(123);
assert!(left.recv() == 123);
- assert!(right.recv() == ~"abc");
+ assert!(right.recv() == "abc".to_owned());
}
}
#[test]
fn test_from_value() {
- let mut f = Future::from_value(~"snail");
- assert_eq!(f.get(), ~"snail");
+ let mut f = Future::from_value("snail".to_owned());
+ assert_eq!(f.get(), "snail".to_owned());
}
#[test]
fn test_from_receiver() {
let (tx, rx) = channel();
- tx.send(~"whale");
+ tx.send("whale".to_owned());
let mut f = Future::from_receiver(rx);
- assert_eq!(f.get(), ~"whale");
+ assert_eq!(f.get(), "whale".to_owned());
}
#[test]
fn test_from_fn() {
- let mut f = Future::from_fn(proc() ~"brail");
- assert_eq!(f.get(), ~"brail");
+ let mut f = Future::from_fn(proc() "brail".to_owned());
+ assert_eq!(f.get(), "brail".to_owned());
}
#[test]
fn test_interface_get() {
- let mut f = Future::from_value(~"fail");
- assert_eq!(f.get(), ~"fail");
+ let mut f = Future::from_value("fail".to_owned());
+ assert_eq!(f.get(), "fail".to_owned());
}
#[test]
fn test_interface_unwrap() {
- let f = Future::from_value(~"fail");
- assert_eq!(f.unwrap(), ~"fail");
+ let f = Future::from_value("fail".to_owned());
+ assert_eq!(f.unwrap(), "fail".to_owned());
}
#[test]
#[test]
fn test_spawn() {
- let mut f = Future::spawn(proc() ~"bale");
- assert_eq!(f.get(), ~"bale");
+ let mut f = Future::spawn(proc() "bale".to_owned());
+ assert_eq!(f.get(), "bale".to_owned());
}
#[test]
}
pub fn float_ty_to_str(t: FloatTy) -> ~str {
- match t { TyF32 => ~"f32", TyF64 => ~"f64" }
+ match t { TyF32 => "f32".to_owned(), TyF64 => "f64".to_owned() }
}
pub fn is_call_expr(e: @Expr) -> bool {
pub fn span_to_str(&self, sp: Span) -> ~str {
if self.files.borrow().len() == 0 && sp == DUMMY_SP {
- return ~"no-location";
+ return "no-location".to_owned();
}
let lo = self.lookup_char_pos_adj(sp.lo);
#[test]
fn t1 () {
let cm = CodeMap::new();
- let fm = cm.new_filemap(~"blork.rs",~"first line.\nsecond line");
+ let fm = cm.new_filemap("blork.rs".to_owned(),"first line.\nsecond line".to_owned());
fm.next_line(BytePos(0));
- assert_eq!(&fm.get_line(0),&~"first line.");
+ assert_eq!(&fm.get_line(0),&"first line.".to_owned());
// TESTING BROKEN BEHAVIOR:
fm.next_line(BytePos(10));
- assert_eq!(&fm.get_line(1),&~".");
+ assert_eq!(&fm.get_line(1),&".".to_owned());
}
#[test]
#[should_fail]
fn t2 () {
let cm = CodeMap::new();
- let fm = cm.new_filemap(~"blork.rs",~"first line.\nsecond line");
+ let fm = cm.new_filemap("blork.rs".to_owned(),"first line.\nsecond line".to_owned());
// TESTING *REALLY* BROKEN BEHAVIOR:
fm.next_line(BytePos(0));
fm.next_line(BytePos(10));
fn init_code_map() -> CodeMap {
let cm = CodeMap::new();
- let fm1 = cm.new_filemap(~"blork.rs",~"first line.\nsecond line");
- let fm2 = cm.new_filemap(~"empty.rs",~"");
- let fm3 = cm.new_filemap(~"blork2.rs",~"first line.\nsecond line");
+ let fm1 = cm.new_filemap("blork.rs".to_owned(),"first line.\nsecond line".to_owned());
+ let fm2 = cm.new_filemap("empty.rs".to_owned(),"".to_owned());
+ let fm3 = cm.new_filemap("blork2.rs".to_owned(),"first line.\nsecond line".to_owned());
fm1.next_line(BytePos(0));
fm1.next_line(BytePos(12));
let cm = init_code_map();
let fmabp1 = cm.lookup_byte_offset(BytePos(22));
- assert_eq!(fmabp1.fm.name, ~"blork.rs");
+ assert_eq!(fmabp1.fm.name, "blork.rs".to_owned());
assert_eq!(fmabp1.pos, BytePos(22));
let fmabp2 = cm.lookup_byte_offset(BytePos(24));
- assert_eq!(fmabp2.fm.name, ~"blork2.rs");
+ assert_eq!(fmabp2.fm.name, "blork2.rs".to_owned());
assert_eq!(fmabp2.pos, BytePos(0));
}
let cm = init_code_map();
let loc1 = cm.lookup_char_pos(BytePos(22));
- assert_eq!(loc1.file.name, ~"blork.rs");
+ assert_eq!(loc1.file.name, "blork.rs".to_owned());
assert_eq!(loc1.line, 2);
assert_eq!(loc1.col, CharPos(10));
let loc2 = cm.lookup_char_pos(BytePos(24));
- assert_eq!(loc2.file.name, ~"blork2.rs");
+ assert_eq!(loc2.file.name, "blork2.rs".to_owned());
assert_eq!(loc2.line, 1);
assert_eq!(loc2.col, CharPos(0));
}
fn init_code_map_mbc() -> CodeMap {
let cm = CodeMap::new();
// € is a three byte utf8 char.
- let fm1 = cm.new_filemap(~"blork.rs",~"fir€st €€€€ line.\nsecond line");
- let fm2 = cm.new_filemap(~"blork2.rs",~"first line€€.\n€ second line");
+ let fm1 = cm.new_filemap("blork.rs".to_owned(),"fir€st €€€€ line.\nsecond line".to_owned());
+ let fm2 = cm.new_filemap("blork2.rs".to_owned(),"first line€€.\n€ second line".to_owned());
fm1.next_line(BytePos(0));
fm1.next_line(BytePos(22));
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None};
let file_lines = cm.span_to_lines(span);
- assert_eq!(file_lines.file.name, ~"blork.rs");
+ assert_eq!(file_lines.file.name, "blork.rs".to_owned());
assert_eq!(file_lines.lines.len(), 1);
assert_eq!(*file_lines.lines.get(0), 1u);
}
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None};
let snippet = cm.span_to_snippet(span);
- assert_eq!(snippet, Some(~"second line"));
+ assert_eq!(snippet, Some("second line".to_owned()));
}
#[test]
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None};
let sstr = cm.span_to_str(span);
- assert_eq!(sstr, ~"blork.rs:2:1: 2:12");
+ assert_eq!(sstr, "blork.rs:2:1: 2:12".to_owned());
}
}
#[test]
fn bare_name() {
let crateid: CrateId = from_str("foo").expect("valid crateid");
- assert_eq!(crateid.name, ~"foo");
+ assert_eq!(crateid.name, "foo".to_owned());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, ~"foo");
+ assert_eq!(crateid.path, "foo".to_owned());
}
#[test]
fn bare_name_single_char() {
let crateid: CrateId = from_str("f").expect("valid crateid");
- assert_eq!(crateid.name, ~"f");
+ assert_eq!(crateid.name, "f".to_owned());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, ~"f");
+ assert_eq!(crateid.path, "f".to_owned());
}
#[test]
#[test]
fn simple_path() {
let crateid: CrateId = from_str("example.com/foo/bar").expect("valid crateid");
- assert_eq!(crateid.name, ~"bar");
+ assert_eq!(crateid.name, "bar".to_owned());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, ~"example.com/foo/bar");
+ assert_eq!(crateid.path, "example.com/foo/bar".to_owned());
}
#[test]
fn simple_version() {
let crateid: CrateId = from_str("foo#1.0").expect("valid crateid");
- assert_eq!(crateid.name, ~"foo");
- assert_eq!(crateid.version, Some(~"1.0"));
- assert_eq!(crateid.path, ~"foo");
+ assert_eq!(crateid.name, "foo".to_owned());
+ assert_eq!(crateid.version, Some("1.0".to_owned()));
+ assert_eq!(crateid.path, "foo".to_owned());
}
#[test]
#[test]
fn path_and_version() {
let crateid: CrateId = from_str("example.com/foo/bar#1.0").expect("valid crateid");
- assert_eq!(crateid.name, ~"bar");
- assert_eq!(crateid.version, Some(~"1.0"));
- assert_eq!(crateid.path, ~"example.com/foo/bar");
+ assert_eq!(crateid.name, "bar".to_owned());
+ assert_eq!(crateid.version, Some("1.0".to_owned()));
+ assert_eq!(crateid.path, "example.com/foo/bar".to_owned());
}
#[test]
fn single_chars() {
let crateid: CrateId = from_str("a/b#1").expect("valid crateid");
- assert_eq!(crateid.name, ~"b");
- assert_eq!(crateid.version, Some(~"1"));
- assert_eq!(crateid.path, ~"a/b");
+ assert_eq!(crateid.name, "b".to_owned());
+ assert_eq!(crateid.version, Some("1".to_owned()));
+ assert_eq!(crateid.path, "a/b".to_owned());
}
#[test]
fn missing_version() {
let crateid: CrateId = from_str("foo#").expect("valid crateid");
- assert_eq!(crateid.name, ~"foo");
+ assert_eq!(crateid.name, "foo".to_owned());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, ~"foo");
+ assert_eq!(crateid.path, "foo".to_owned());
}
#[test]
fn path_and_name() {
let crateid: CrateId = from_str("foo/rust-bar#bar:1.0").expect("valid crateid");
- assert_eq!(crateid.name, ~"bar");
- assert_eq!(crateid.version, Some(~"1.0"));
- assert_eq!(crateid.path, ~"foo/rust-bar");
+ assert_eq!(crateid.name, "bar".to_owned());
+ assert_eq!(crateid.version, Some("1.0".to_owned()));
+ assert_eq!(crateid.path, "foo/rust-bar".to_owned());
}
#[test]
fn empty_name() {
let crateid: CrateId = from_str("foo/bar#:1.0").expect("valid crateid");
- assert_eq!(crateid.name, ~"bar");
- assert_eq!(crateid.version, Some(~"1.0"));
- assert_eq!(crateid.path, ~"foo/bar");
+ assert_eq!(crateid.name, "bar".to_owned());
+ assert_eq!(crateid.version, Some("1.0".to_owned()));
+ assert_eq!(crateid.path, "foo/bar".to_owned());
}
fail!(ExplicitBug);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
- self.span_bug(sp, ~"unimplemented " + msg);
+ self.span_bug(sp, "unimplemented ".to_owned() + msg);
}
pub fn handler<'a>(&'a self) -> &'a Handler {
&self.handler
let s;
match self.err_count.get() {
0u => return,
- 1u => s = ~"aborting due to previous error",
+ 1u => s = "aborting due to previous error".to_owned(),
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
fail!(ExplicitBug);
}
pub fn unimpl(&self, msg: &str) -> ! {
- self.bug(~"unimplemented " + msg);
+ self.bug("unimplemented ".to_owned() + msg);
}
pub fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
sp: Span)
-> io::IoResult<()> {
for ei in sp.expn_info.iter() {
- let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span));
+ let ss = ei.callee.span.as_ref().map_or("".to_owned(), |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
let mut asm_str_style = None;
let mut outputs = Vec::new();
let mut inputs = Vec::new();
- let mut cons = ~"";
+ let mut cons = "".to_owned();
let mut volatile = false;
let mut alignstack = false;
let mut dialect = ast::AsmAtt;
fn decode(d: &D) -> Node {
d.read_struct("Node", 1, || {
Node {
- id: d.read_field(~"x", 0, || decode(d))
+ id: d.read_field("x".to_owned(), 0, || decode(d))
}
})
}
fn decode(d: &D) -> spanned<T> {
d.read_rec(|| {
{
- node: d.read_field(~"node", 0, || decode(d)),
- span: d.read_field(~"span", 1, || decode(d)),
+ node: d.read_field("node".to_owned(), 0, || decode(d)),
+ span: d.read_field("span".to_owned(), 1, || decode(d)),
}
})
}
} else { // there are still matches to create
let current_match_str = if match_count == 0 {
- ~"__self"
+ "__self".to_owned()
} else {
format!("__arg_{}", match_count)
};
// make sure that macros can leave scope
#[should_fail]
#[test] fn macros_cant_escape_fns_test () {
- let src = ~"fn bogus() {macro_rules! z (() => (3+4))}\
- fn inty() -> int { z!() }";
+ let src = "fn bogus() {macro_rules! z (() => (3+4))}\
+ fn inty() -> int { z!() }".to_owned();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- ~"<test>",
+ "<test>".to_owned(),
src,
Vec::new(), &sess);
// should fail:
// make sure that macros can leave scope for modules
#[should_fail]
#[test] fn macros_cant_escape_mods_test () {
- let src = ~"mod foo {macro_rules! z (() => (3+4))}\
- fn inty() -> int { z!() }";
+ let src = "mod foo {macro_rules! z (() => (3+4))}\
+ fn inty() -> int { z!() }".to_owned();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- ~"<test>",
+ "<test>".to_owned(),
src,
Vec::new(), &sess);
// should fail:
// macro_escape modules shouldn't cause macros to leave scope
#[test] fn macros_can_escape_flattened_mods_test () {
- let src = ~"#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
- fn inty() -> int { z!() }";
+ let src = "#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
+ fn inty() -> int { z!() }".to_owned();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- ~"<test>",
+ "<test>".to_owned(),
src,
Vec::new(), &sess);
// should fail:
//}
#[test] fn macro_tokens_should_match(){
- expand_crate_str(~"macro_rules! m((a)=>(13)) fn main(){m!(a);}");
+ expand_crate_str("macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_owned());
}
// renaming tests expand a crate and then check that the bindings match
}
#[test] fn fmt_in_macro_used_inside_module_macro() {
- let crate_str = ~"macro_rules! fmt_wrap(($b:expr)=>($b.to_str()))
+ let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_str()))
macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}))
foo_module!()
-";
+".to_owned();
let cr = expand_crate_str(crate_str);
// find the xx binding
let mut name_finder = new_name_finder(Vec::new());
#[test]
fn pat_idents(){
- let pat = string_to_pat(~"(a,Foo{x:c @ (b,9),y:Bar(4,d)})");
+ let pat = string_to_pat("(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_owned());
let mut pat_idents = new_name_finder(Vec::new());
pat_idents.visit_pat(pat, ());
assert_eq!(pat_idents.ident_accumulator,
LIT_INT(i, ity) => {
let s_ity = match ity {
- ast::TyI => ~"TyI",
- ast::TyI8 => ~"TyI8",
- ast::TyI16 => ~"TyI16",
- ast::TyI32 => ~"TyI32",
- ast::TyI64 => ~"TyI64"
+ ast::TyI => "TyI".to_owned(),
+ ast::TyI8 => "TyI8".to_owned(),
+ ast::TyI16 => "TyI16".to_owned(),
+ ast::TyI32 => "TyI32".to_owned(),
+ ast::TyI64 => "TyI64".to_owned()
};
let e_ity = cx.expr_ident(sp, id_ext(s_ity));
LIT_UINT(u, uty) => {
let s_uty = match uty {
- ast::TyU => ~"TyU",
- ast::TyU8 => ~"TyU8",
- ast::TyU16 => ~"TyU16",
- ast::TyU32 => ~"TyU32",
- ast::TyU64 => ~"TyU64"
+ ast::TyU => "TyU".to_owned(),
+ ast::TyU8 => "TyU8".to_owned(),
+ ast::TyU16 => "TyU16".to_owned(),
+ ast::TyU32 => "TyU32".to_owned(),
+ ast::TyU64 => "TyU64".to_owned()
};
let e_uty = cx.expr_ident(sp, id_ext(s_uty));
LIT_FLOAT(fident, fty) => {
let s_fty = match fty {
- ast::TyF32 => ~"TyF32",
- ast::TyF64 => ~"TyF64"
+ ast::TyF32 => "TyF32".to_owned(),
+ ast::TyF64 => "TyF64".to_owned()
};
let e_fty = cx.expr_ident(sp, id_ext(s_fty));
cx_expr: @ast::Expr,
expr: @ast::Expr) -> @ast::Expr {
let uses = vec!( cx.view_use_glob(sp, ast::Inherited,
- ids_ext(vec!(~"syntax",
- ~"ext",
- ~"quote",
- ~"rt"))) );
+ ids_ext(vec!("syntax".to_owned(),
+ "ext".to_owned(),
+ "quote".to_owned(),
+ "rt".to_owned()))) );
let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr);
}
return Success(nameize(sess, ms, v.as_slice()));
} else if eof_eis.len() > 1u {
- return Error(sp, ~"ambiguity: multiple successful parses");
+ return Error(sp, "ambiguity: multiple successful parses".to_owned());
} else {
- return Failure(sp, ~"unexpected end of macro invocation");
+ return Failure(sp, "unexpected end of macro invocation".to_owned());
}
} else {
if (bb_eis.len() > 0u && next_eis.len() > 0u)
token::IDENT(sn,b) => { p.bump(); token::NtIdent(~sn,b) }
_ => {
let token_str = token::to_str(&p.token);
- p.fatal(~"expected ident, found " + token_str)
+ p.fatal("expected ident, found ".to_owned() + token_str)
}
},
"path" => {
res
}
"matchers" => token::NtMatchers(p.parse_matchers()),
- _ => p.fatal(~"unsupported builtin nonterminal parser: " + name)
+ _ => p.fatal("unsupported builtin nonterminal parser: ".to_owned() + name)
}
}
// Which arm's failure should we report? (the one furthest along)
let mut best_fail_spot = DUMMY_SP;
- let mut best_fail_msg = ~"internal error: ran no matchers";
+ let mut best_fail_msg = "internal error: ran no matchers".to_owned();
for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
match **lhs {
#[test] fn ident_transformation () {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
- ~"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}");
+ "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_owned());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(matches_codepattern,
"matches_codepattern",
pprust::to_str(|s| fake_print_crate(s, &folded_crate)),
- ~"#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}");
+ "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_owned());
}
// even inside macro defs....
#[test] fn ident_transformation_in_defs () {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
- ~"macro_rules! a {(b $c:expr $(d $e:token)f+ => \
- (g $(d $d $e)+))} ");
+ "macro_rules! a {(b $c:expr $(d $e:token)f+ => \
+ (g $(d $d $e)+))} ".to_owned());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(matches_codepattern,
"matches_codepattern",
pprust::to_str(|s| fake_print_crate(s, &folded_crate)),
- ~"zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))");
+ "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))".to_owned());
}
}
Some(col) => {
if col < len {
s.slice(col, len).to_owned()
- } else { ~"" }
+ } else { "".to_owned() }
}
None => s,
};
while level > 0 {
debug!("=== block comment level {}", level);
if is_eof(rdr) {
- rdr.fatal(~"unterminated block comment");
+ rdr.fatal("unterminated block comment".to_owned());
}
if rdr.curr_is('\n') {
trim_whitespace_prefix_and_push_line(&mut lines,
#[test] fn test_block_doc_comment_1() {
let comment = "/**\n * Test \n ** Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
- assert_eq!(stripped, ~" Test \n* Test\n Test");
+ assert_eq!(stripped, " Test \n* Test\n Test".to_owned());
}
#[test] fn test_block_doc_comment_2() {
let comment = "/**\n * Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
- assert_eq!(stripped, ~" Test\n Test");
+ assert_eq!(stripped, " Test\n Test".to_owned());
}
#[test] fn test_block_doc_comment_3() {
let comment = "/**\n let a: *int;\n *a = 5;\n*/";
let stripped = strip_doc_comment_decoration(comment);
- assert_eq!(stripped, ~" let a: *int;\n *a = 5;");
+ assert_eq!(stripped, " let a: *int;\n *a = 5;".to_owned());
}
#[test] fn test_block_doc_comment_4() {
let comment = "/*******************\n test\n *********************/";
let stripped = strip_doc_comment_decoration(comment);
- assert_eq!(stripped, ~" test");
+ assert_eq!(stripped, " test".to_owned());
}
#[test] fn test_line_doc_comment() {
let stripped = strip_doc_comment_decoration("/// test");
- assert_eq!(stripped, ~" test");
+ assert_eq!(stripped, " test".to_owned());
let stripped = strip_doc_comment_decoration("///! test");
- assert_eq!(stripped, ~" test");
+ assert_eq!(stripped, " test".to_owned());
let stripped = strip_doc_comment_decoration("// test");
- assert_eq!(stripped, ~" test");
+ assert_eq!(stripped, " test".to_owned());
let stripped = strip_doc_comment_decoration("// test");
- assert_eq!(stripped, ~" test");
+ assert_eq!(stripped, " test".to_owned());
let stripped = strip_doc_comment_decoration("///test");
- assert_eq!(stripped, ~"test");
+ assert_eq!(stripped, "test".to_owned());
let stripped = strip_doc_comment_decoration("///!test");
- assert_eq!(stripped, ~"test");
+ assert_eq!(stripped, "test".to_owned());
let stripped = strip_doc_comment_decoration("//test");
- assert_eq!(stripped, ~"test");
+ assert_eq!(stripped, "test".to_owned());
}
}
while level > 0 {
if is_eof(rdr) {
let msg = if is_doc_comment {
- ~"unterminated block doc-comment"
+ "unterminated block doc-comment".to_owned()
} else {
- ~"unterminated block comment"
+ "unterminated block comment".to_owned()
};
fatal_span(rdr, start_bpos, rdr.last_pos, msg);
} else if rdr.curr_is('/') && nextch_is(rdr, '*') {
return Some(rslt.into_owned());
} else {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"scan_exponent: bad fp literal");
+ "scan_exponent: bad fp literal".to_owned());
}
} else { return None::<~str>; }
}
base: uint) {
match base {
16u => fatal_span(rdr, start_bpos, last_bpos,
- ~"hexadecimal float literal is not supported"),
+ "hexadecimal float literal is not supported".to_owned()),
8u => fatal_span(rdr, start_bpos, last_bpos,
- ~"octal float literal is not supported"),
+ "octal float literal is not supported".to_owned()),
2u => fatal_span(rdr, start_bpos, last_bpos,
- ~"binary float literal is not supported"),
+ "binary float literal is not supported".to_owned()),
_ => ()
}
}
}
if num_str.len() == 0u {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"no valid digits found for number");
+ "no valid digits found for number".to_owned());
}
let parsed = match from_str_radix::<u64>(num_str.as_slice(),
base as uint) {
Some(p) => p,
None => fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"int literal is too large")
+ "int literal is too large".to_owned())
};
match tp {
back-end. */
} else {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"expected `f32` or `f64` suffix");
+ "expected `f32` or `f64` suffix".to_owned());
}
}
if is_float {
} else {
if num_str.len() == 0u {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"no valid digits found for number");
+ "no valid digits found for number".to_owned());
}
let parsed = match from_str_radix::<u64>(num_str.as_slice(),
base as uint) {
Some(p) => p,
None => fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"int literal is too large")
+ "int literal is too large".to_owned())
};
debug!("lexing {} as an unsuffixed integer literal",
let n = rdr.curr;
if !is_hex_digit(n) {
fatal_span_char(rdr, rdr.last_pos, rdr.pos,
- ~"illegal character in numeric character escape",
+ "illegal character in numeric character escape".to_owned(),
n.unwrap());
}
bump(rdr);
}
if i != 0 && is_eof(rdr) {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"unterminated numeric character escape");
+ "unterminated numeric character escape".to_owned());
}
match char::from_u32(accum_int as u32) {
Some(x) => x,
None => fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"illegal numeric character escape")
+ "illegal numeric character escape".to_owned())
}
}
if token::is_keyword(token::keywords::Self, tok) {
fatal_span(rdr, start, rdr.last_pos,
- ~"invalid lifetime name: 'self is no longer a special lifetime");
+ "invalid lifetime name: 'self \
+ is no longer a special lifetime".to_owned());
} else if token::is_any_keyword(tok) &&
!token::is_keyword(token::keywords::Static, tok) {
fatal_span(rdr, start, rdr.last_pos,
- ~"invalid lifetime name");
+ "invalid lifetime name".to_owned());
} else {
return token::LIFETIME(ident);
}
'U' => scan_numeric_escape(rdr, 8u),
c2 => {
fatal_span_char(rdr, escaped_pos, rdr.last_pos,
- ~"unknown character escape", c2)
+ "unknown character escape".to_owned(), c2)
}
}
}
}
'\t' | '\n' | '\r' | '\'' => {
fatal_span_char(rdr, start, rdr.last_pos,
- ~"character constant must be escaped", c2);
+ "character constant must be escaped".to_owned(), c2);
}
_ => {}
}
// ascii single quote.
start - BytePos(1),
rdr.last_pos,
- ~"unterminated character constant");
+ "unterminated character constant".to_owned());
}
bump(rdr); // advance curr past token
return token::LIT_CHAR(c2 as u32);
while !rdr.curr_is('"') {
if is_eof(rdr) {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"unterminated double quote string");
+ "unterminated double quote string".to_owned());
}
let ch = rdr.curr.unwrap();
'\\' => {
if is_eof(rdr) {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"unterminated double quote string");
+ "unterminated double quote string".to_owned());
}
let escaped = rdr.curr.unwrap();
}
c2 => {
fatal_span_char(rdr, escaped_pos, rdr.last_pos,
- ~"unknown string escape", c2);
+ "unknown string escape".to_owned(), c2);
}
}
}
if is_eof(rdr) {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"unterminated raw string");
+ "unterminated raw string".to_owned());
} else if !rdr.curr_is('"') {
fatal_span_char(rdr, start_bpos, rdr.last_pos,
- ~"only `#` is allowed in raw string delimitation; \
- found illegal character",
+ "only `#` is allowed in raw string delimitation; \
+ found illegal character".to_owned(),
rdr.curr.unwrap());
}
bump(rdr);
'outer: loop {
if is_eof(rdr) {
fatal_span(rdr, start_bpos, rdr.last_pos,
- ~"unterminated raw string");
+ "unterminated raw string".to_owned());
}
if rdr.curr_is('"') {
content_end_bpos = rdr.last_pos;
'%' => { return binop(rdr, token::PERCENT); }
c => {
fatal_span_char(rdr, rdr.last_pos, rdr.pos,
- ~"unknown start of token", c);
+ "unknown start of token".to_owned(), c);
}
}
}
// open a string reader for the given string
fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
teststr: ~str) -> StringReader<'a> {
- let fm = span_handler.cm.new_filemap(~"zebra.rs", teststr);
+ let fm = span_handler.cm.new_filemap("zebra.rs".to_owned(), teststr);
new_string_reader(span_handler, fm)
}
#[test] fn t1 () {
let span_handler = mk_sh();
let mut string_reader = setup(&span_handler,
- ~"/* my source file */ \
- fn main() { println!(\"zebra\"); }\n");
+ "/* my source file */ \
+ fn main() { println!(\"zebra\"); }\n".to_owned());
let id = str_to_ident("fn");
let tok1 = string_reader.next_token();
let tok2 = TokenAndSpan{
}
#[test] fn doublecolonparsing () {
- check_tokenization(setup(&mk_sh(), ~"a b"),
+ check_tokenization(setup(&mk_sh(), "a b".to_owned()),
vec!(mk_ident("a",false),
mk_ident("b",false)));
}
#[test] fn dcparsing_2 () {
- check_tokenization(setup(&mk_sh(), ~"a::b"),
+ check_tokenization(setup(&mk_sh(), "a::b".to_owned()),
vec!(mk_ident("a",true),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn dcparsing_3 () {
- check_tokenization(setup(&mk_sh(), ~"a ::b"),
+ check_tokenization(setup(&mk_sh(), "a ::b".to_owned()),
vec!(mk_ident("a",false),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn dcparsing_4 () {
- check_tokenization(setup(&mk_sh(), ~"a:: b"),
+ check_tokenization(setup(&mk_sh(), "a:: b".to_owned()),
vec!(mk_ident("a",true),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn character_a() {
- assert_eq!(setup(&mk_sh(), ~"'a'").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'a'".to_owned()).next_token().tok,
token::LIT_CHAR('a' as u32));
}
#[test] fn character_space() {
- assert_eq!(setup(&mk_sh(), ~"' '").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "' '".to_owned()).next_token().tok,
token::LIT_CHAR(' ' as u32));
}
#[test] fn character_escaped() {
- assert_eq!(setup(&mk_sh(), ~"'\\n'").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'\\n'".to_owned()).next_token().tok,
token::LIT_CHAR('\n' as u32));
}
#[test] fn lifetime_name() {
- assert_eq!(setup(&mk_sh(), ~"'abc").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'abc".to_owned()).next_token().tok,
token::LIFETIME(token::str_to_ident("abc")));
}
#[test] fn raw_string() {
- assert_eq!(setup(&mk_sh(), ~"r###\"\"#a\\b\x00c\"\"###").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "r###\"\"#a\\b\x00c\"\"###".to_owned()).next_token().tok,
token::LIT_STR_RAW(token::str_to_ident("\"#a\\b\x00c\""), 3));
}
}
#[test] fn nested_block_comments() {
- assert_eq!(setup(&mk_sh(), ~"/* /* */ */'a'").next_token().tok,
+ assert_eq!(setup(&mk_sh(), "/* /* */ */'a'".to_owned()).next_token().tok,
token::LIT_CHAR('a' as u32));
}
}
#[test] fn path_exprs_1() {
- assert!(string_to_expr(~"a") ==
+ assert!(string_to_expr("a".to_owned()) ==
@ast::Expr{
id: ast::DUMMY_NODE_ID,
node: ast::ExprPath(ast::Path {
}
#[test] fn path_exprs_2 () {
- assert!(string_to_expr(~"::a::b") ==
+ assert!(string_to_expr("::a::b".to_owned()) ==
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprPath(ast::Path {
#[should_fail]
#[test] fn bad_path_expr_1() {
- string_to_expr(~"::abc::def::return");
+ string_to_expr("::abc::def::return".to_owned());
}
// check the token-tree-ization of macros
#[test] fn string_to_tts_macro () {
- let tts = string_to_tts(~"macro_rules! zip (($a)=>($a))");
+ let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_owned());
let tts: &[ast::TokenTree] = tts.as_slice();
match tts {
[ast::TTTok(_,_),
}
#[test] fn string_to_tts_1 () {
- let tts = string_to_tts(~"fn a (b : int) { b; }");
+ let tts = string_to_tts("fn a (b : int) { b; }".to_owned());
assert_eq!(to_json_str(&tts),
- ~"[\
+ "[\
{\
\"variant\":\"TTTok\",\
\"fields\":[\
]\
]\
}\
-]"
+]".to_owned()
);
}
#[test] fn ret_expr() {
- assert!(string_to_expr(~"return d") ==
+ assert!(string_to_expr("return d".to_owned()) ==
@ast::Expr{
id: ast::DUMMY_NODE_ID,
node:ast::ExprRet(Some(@ast::Expr{
}
#[test] fn parse_stmt_1 () {
- assert!(string_to_stmt(~"b;") ==
+ assert!(string_to_stmt("b;".to_owned()) ==
@Spanned{
node: ast::StmtExpr(@ast::Expr {
id: ast::DUMMY_NODE_ID,
#[test] fn parse_ident_pat () {
let sess = new_parse_sess();
- let mut parser = string_to_parser(&sess, ~"b");
+ let mut parser = string_to_parser(&sess, "b".to_owned());
assert!(parser.parse_pat() ==
@ast::Pat{id: ast::DUMMY_NODE_ID,
node: ast::PatIdent(
// check the contents of the tt manually:
#[test] fn parse_fundecl () {
// this test depends on the intern order of "fn" and "int"
- assert!(string_to_item(~"fn a (b : int) { b; }") ==
+ assert!(string_to_item("fn a (b : int) { b; }".to_owned()) ==
Some(
@ast::Item{ident:str_to_ident("a"),
attrs:Vec::new(),
#[test] fn parse_exprs () {
// just make sure that they parse....
- string_to_expr(~"3 + 4");
- string_to_expr(~"a::z.froob(b,@(987+3))");
+ string_to_expr("3 + 4".to_owned());
+ string_to_expr("a::z.froob(b,@(987+3))".to_owned());
}
#[test] fn attrs_fix_bug () {
- string_to_item(~"pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
+ string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
-> Result<@Writer, ~str> {
#[cfg(windows)]
fn wb() -> c_int {
fn wb() -> c_int { O_WRONLY as c_int }
let mut fflags: c_int = wb();
-}");
+}".to_owned());
}
}
fn tokens_to_str(tokens: &[token::Token]) -> ~str {
let mut i = tokens.iter();
// This might be a sign we need a connect method on Iterator.
- let b = i.next().map_or(~"", |t| Parser::token_to_str(t));
+ let b = i.next().map_or("".to_owned(), |t| Parser::token_to_str(t));
i.fold(b, |b,a| b + "`, `" + Parser::token_to_str(a))
}
if edible.contains(&self.token) {
pub fn binop_to_str(o: BinOp) -> ~str {
match o {
- PLUS => ~"+",
- MINUS => ~"-",
- STAR => ~"*",
- SLASH => ~"/",
- PERCENT => ~"%",
- CARET => ~"^",
- AND => ~"&",
- OR => ~"|",
- SHL => ~"<<",
- SHR => ~">>"
+ PLUS => "+".to_owned(),
+ MINUS => "-".to_owned(),
+ STAR => "*".to_owned(),
+ SLASH => "/".to_owned(),
+ PERCENT => "%".to_owned(),
+ CARET => "^".to_owned(),
+ AND => "&".to_owned(),
+ OR => "|".to_owned(),
+ SHL => "<<".to_owned(),
+ SHR => ">>".to_owned()
}
}
pub fn to_str(t: &Token) -> ~str {
match *t {
- EQ => ~"=",
- LT => ~"<",
- LE => ~"<=",
- EQEQ => ~"==",
- NE => ~"!=",
- GE => ~">=",
- GT => ~">",
- NOT => ~"!",
- TILDE => ~"~",
- OROR => ~"||",
- ANDAND => ~"&&",
+ EQ => "=".to_owned(),
+ LT => "<".to_owned(),
+ LE => "<=".to_owned(),
+ EQEQ => "==".to_owned(),
+ NE => "!=".to_owned(),
+ GE => ">=".to_owned(),
+ GT => ">".to_owned(),
+ NOT => "!".to_owned(),
+ TILDE => "~".to_owned(),
+ OROR => "||".to_owned(),
+ ANDAND => "&&".to_owned(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => binop_to_str(op) + "=",
/* Structural symbols */
- AT => ~"@",
- DOT => ~".",
- DOTDOT => ~"..",
- DOTDOTDOT => ~"...",
- COMMA => ~",",
- SEMI => ~";",
- COLON => ~":",
- MOD_SEP => ~"::",
- RARROW => ~"->",
- LARROW => ~"<-",
- DARROW => ~"<->",
- FAT_ARROW => ~"=>",
- LPAREN => ~"(",
- RPAREN => ~")",
- LBRACKET => ~"[",
- RBRACKET => ~"]",
- LBRACE => ~"{",
- RBRACE => ~"}",
- POUND => ~"#",
- DOLLAR => ~"$",
+ AT => "@".to_owned(),
+ DOT => ".".to_owned(),
+ DOTDOT => "..".to_owned(),
+ DOTDOTDOT => "...".to_owned(),
+ COMMA => ",".to_owned(),
+ SEMI => ";".to_owned(),
+ COLON => ":".to_owned(),
+ MOD_SEP => "::".to_owned(),
+ RARROW => "->".to_owned(),
+ LARROW => "<-".to_owned(),
+ DARROW => "<->".to_owned(),
+ FAT_ARROW => "=>".to_owned(),
+ LPAREN => "(".to_owned(),
+ RPAREN => ")".to_owned(),
+ LBRACKET => "[".to_owned(),
+ RBRACKET => "]".to_owned(),
+ LBRACE => "{".to_owned(),
+ RBRACE => "}".to_owned(),
+ POUND => "#".to_owned(),
+ DOLLAR => "$".to_owned(),
/* Literals */
LIT_CHAR(c) => {
LIFETIME(s) => {
format!("'{}", get_ident(s))
}
- UNDERSCORE => ~"_",
+ UNDERSCORE => "_".to_owned(),
/* Other */
DOC_COMMENT(s) => get_ident(s).get().to_str(),
- EOF => ~"<eof>",
+ EOF => "<eof>".to_owned(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
- ~"an interpolated " +
+ "an interpolated ".to_owned() +
match *nt {
- NtItem(..) => ~"item",
- NtBlock(..) => ~"block",
- NtStmt(..) => ~"statement",
- NtPat(..) => ~"pattern",
+ NtItem(..) => "item".to_owned(),
+ NtBlock(..) => "block".to_owned(),
+ NtStmt(..) => "statement".to_owned(),
+ NtPat(..) => "pattern".to_owned(),
NtMeta(..) => fail!("should have been handled"),
NtExpr(..) => fail!("should have been handled above"),
- NtTy(..) => ~"type",
- NtIdent(..) => ~"identifier",
- NtPath(..) => ~"path",
- NtTT(..) => ~"tt",
- NtMatchers(..) => ~"matcher sequence"
+ NtTy(..) => "type".to_owned(),
+ NtIdent(..) => "identifier".to_owned(),
+ NtPath(..) => "path".to_owned(),
+ NtTT(..) => "tt".to_owned(),
+ NtMatchers(..) => "matcher sequence".to_owned()
}
}
}
pub fn tok_str(t: Token) -> ~str {
match t {
String(s, len) => return format!("STR({},{})", s, len),
- Break(_) => return ~"BREAK",
- Begin(_) => return ~"BEGIN",
- End => return ~"END",
- Eof => return ~"EOF"
+ Break(_) => return "BREAK".to_owned(),
+ Begin(_) => return "BEGIN".to_owned(),
+ End => return "END".to_owned(),
+ Eof => return "EOF".to_owned()
}
}
let generics = ast_util::empty_generics();
assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
None, &generics),
- &~"fn abba()");
+ &"fn abba()".to_owned());
}
#[test]
});
let varstr = variant_to_str(&var);
- assert_eq!(&varstr,&~"pub principal_skinner");
+ assert_eq!(&varstr,&"pub principal_skinner".to_owned());
}
}
// map a string to tts, using a made-up filename:
pub fn string_to_tts(source_str: ~str) -> Vec<ast::TokenTree> {
let ps = new_parse_sess();
- filemap_to_tts(&ps, string_to_filemap(&ps, source_str,~"bogofile"))
+ filemap_to_tts(&ps, string_to_filemap(&ps, source_str,"bogofile".to_owned()))
}
// map string to parser (via tts)
pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: ~str) -> Parser<'a> {
- new_parser_from_source_str(ps, Vec::new(), ~"bogofile", source_str)
+ new_parser_from_source_str(ps, Vec::new(), "bogofile".to_owned(), source_str)
}
fn with_error_checking_parse<T>(s: ~str, f: |&mut Parser| -> T) -> T {
pub fn new(out: T) -> Result<Terminal<T>, ~str> {
let term = match os::getenv("TERM") {
Some(t) => t,
- None => return Err(~"TERM environment variable undefined")
+ None => return Err("TERM environment variable undefined".to_owned())
};
let mut file = match open(term) {
cap = self.ti.strings.find_equiv(&("op"));
}
}
- let s = cap.map_or(Err(~"can't find terminfo capability `sgr0`"), |op| {
+ let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_owned()), |op| {
expand(op.as_slice(), [], &mut Variables::new())
});
if s.is_ok() {
match stack.pop().unwrap() {
// if c is 0, use 0200 (128) for ncurses compatibility
Number(c) => output.push(if c == 0 { 128 } else { c } as u8),
- _ => return Err(~"a non-char was used with %c")
+ _ => return Err("a non-char was used with %c".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'p' => state = PushParam,
'P' => state = SetVar,
'g' => state = GetVar,
'l' => if stack.len() > 0 {
match stack.pop().unwrap() {
String(s) => stack.push(Number(s.len() as int)),
- _ => return Err(~"a non-str was used with %l")
+ _ => return Err("a non-str was used with %l".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'+' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x + y)),
- _ => return Err(~"non-numbers on stack with +")
+ _ => return Err("non-numbers on stack with +".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'-' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x - y)),
- _ => return Err(~"non-numbers on stack with -")
+ _ => return Err("non-numbers on stack with -".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'*' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x * y)),
- _ => return Err(~"non-numbers on stack with *")
+ _ => return Err("non-numbers on stack with *".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'/' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x / y)),
- _ => return Err(~"non-numbers on stack with /")
+ _ => return Err("non-numbers on stack with /".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'm' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x % y)),
- _ => return Err(~"non-numbers on stack with %")
+ _ => return Err("non-numbers on stack with %".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'&' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x & y)),
- _ => return Err(~"non-numbers on stack with &")
+ _ => return Err("non-numbers on stack with &".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'|' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x | y)),
- _ => return Err(~"non-numbers on stack with |")
+ _ => return Err("non-numbers on stack with |".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'^' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(x ^ y)),
- _ => return Err(~"non-numbers on stack with ^")
+ _ => return Err("non-numbers on stack with ^".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'=' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x == y { 1 }
else { 0 })),
- _ => return Err(~"non-numbers on stack with =")
+ _ => return Err("non-numbers on stack with =".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'>' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x > y { 1 }
else { 0 })),
- _ => return Err(~"non-numbers on stack with >")
+ _ => return Err("non-numbers on stack with >".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'<' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(y), Number(x)) => stack.push(Number(if x < y { 1 }
else { 0 })),
- _ => return Err(~"non-numbers on stack with <")
+ _ => return Err("non-numbers on stack with <".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'A' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(0), Number(_)) => stack.push(Number(0)),
(Number(_), Number(0)) => stack.push(Number(0)),
(Number(_), Number(_)) => stack.push(Number(1)),
- _ => return Err(~"non-numbers on stack with logical and")
+ _ => return Err("non-numbers on stack with logical and".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'O' => if stack.len() > 1 {
match (stack.pop().unwrap(), stack.pop().unwrap()) {
(Number(0), Number(0)) => stack.push(Number(0)),
(Number(_), Number(_)) => stack.push(Number(1)),
- _ => return Err(~"non-numbers on stack with logical or")
+ _ => return Err("non-numbers on stack with logical or".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'!' => if stack.len() > 0 {
match stack.pop().unwrap() {
Number(0) => stack.push(Number(1)),
Number(_) => stack.push(Number(0)),
- _ => return Err(~"non-number on stack with logical not")
+ _ => return Err("non-number on stack with logical not".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'~' => if stack.len() > 0 {
match stack.pop().unwrap() {
Number(x) => stack.push(Number(!x)),
- _ => return Err(~"non-number on stack with %~")
+ _ => return Err("non-number on stack with %~".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'i' => match (mparams[0].clone(), mparams[1].clone()) {
(Number(x), Number(y)) => {
mparams[0] = Number(x+1);
mparams[1] = Number(y+1);
},
- (_, _) => return Err(~"first two params not numbers with %i")
+ (_, _) => return Err("first two params not numbers with %i".to_owned())
},
// printf-style support for %doxXs
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags);
if res.is_err() { return res }
output.push_all(res.unwrap().as_slice())
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
':'|'#'|' '|'.'|'0'..'9' => {
let mut flags = Flags::new();
let mut fstate = FormatStateFlags;
match stack.pop().unwrap() {
Number(0) => state = SeekIfElse(0),
Number(_) => (),
- _ => return Err(~"non-number on stack with conditional")
+ _ => return Err("non-number on stack \
+ with conditional".to_owned())
}
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
'e' => state = SeekIfEnd(0),
';' => (),
// params are 1-indexed
stack.push(mparams[match char::to_digit(cur, 10) {
Some(d) => d - 1,
- None => return Err(~"bad param number")
+ None => return Err("bad param number".to_owned())
}].clone());
},
SetVar => {
if stack.len() > 0 {
let idx = (cur as u8) - ('A' as u8);
vars.sta[idx as uint] = stack.pop().unwrap();
- } else { return Err(~"stack is empty") }
+ } else { return Err("stack is empty".to_owned()) }
} else if cur >= 'a' && cur <= 'z' {
if stack.len() > 0 {
let idx = (cur as u8) - ('a' as u8);
vars.dyn[idx as uint] = stack.pop().unwrap();
- } else { return Err(~"stack is empty") }
+ } else { return Err("stack is empty".to_owned()) }
} else {
- return Err(~"bad variable name in %P");
+ return Err("bad variable name in %P".to_owned());
}
},
GetVar => {
let idx = (cur as u8) - ('a' as u8);
stack.push(vars.dyn[idx as uint].clone());
} else {
- return Err(~"bad variable name in %g");
+ return Err("bad variable name in %g".to_owned());
}
},
CharConstant => {
},
CharClose => {
if cur != '\'' {
- return Err(~"malformed character constant");
+ return Err("malformed character constant".to_owned());
}
},
IntConstant(i) => {
state = IntConstant(i*10 + (cur as int - '0' as int));
old_state = Nothing;
}
- _ => return Err(~"bad int constant")
+ _ => return Err("bad int constant".to_owned())
}
}
FormatPattern(ref mut flags, ref mut fstate) => {
if res.is_err() { return res }
output.push_all(res.unwrap().as_slice());
old_state = state; // will cause state to go to Nothing
- } else { return Err(~"stack is empty") },
+ } else { return Err("stack is empty".to_owned()) },
(FormatStateFlags,'#') => {
flags.alternate = true;
}
(FormatStateWidth,'0'..'9') => {
let old = flags.width;
flags.width = flags.width * 10 + (cur as uint - '0' as uint);
- if flags.width < old { return Err(~"format width overflow") }
+ if flags.width < old { return Err("format width overflow".to_owned()) }
}
(FormatStateWidth,'.') => {
*fstate = FormatStatePrecision;
(FormatStatePrecision,'0'..'9') => {
let old = flags.precision;
flags.precision = flags.precision * 10 + (cur as uint - '0' as uint);
- if flags.precision < old { return Err(~"format precision overflow") }
+ if flags.precision < old {
+ return Err("format precision overflow".to_owned())
+ }
}
- _ => return Err(~"invalid format specifier")
+ _ => return Err("invalid format specifier".to_owned())
}
}
SeekIfElse(level) => {
(FormatOctal, _) => format!("{:o}", d).into_bytes(),
(FormatHex, _) => format!("{:x}", d).into_bytes(),
(FormatHEX, _) => format!("{:X}", d).into_bytes(),
- (FormatString, _) => return Err(~"non-number on stack with %s"),
+ (FormatString, _) => return Err("non-number on stack with %s".to_owned()),
};
let mut s: Vec<u8> = s.move_iter().collect();
if flags.precision > s.len() {
let res = expand(cap.as_bytes(), [], vars);
assert!(res.is_err(),
"Op {} succeeded incorrectly with 0 stack entries", *cap);
- let p = if *cap == "%s" || *cap == "%l" { String(~"foo") } else { Number(97) };
+ let p = if *cap == "%s" || *cap == "%l" {
+ String("foo".to_owned())
+ } else {
+ Number(97)
+ };
let res = expand(bytes!("%p1").iter().map(|x| *x).collect::<Vec<_>>()
.append(cap.as_bytes()).as_slice(),
[p],
let mut varstruct = Variables::new();
let vars = &mut varstruct;
assert_eq!(expand(bytes!("%p1%s%p2%2s%p3%2s%p4%.2s"),
- [String(~"foo"), String(~"foo"), String(~"f"), String(~"foo")], vars),
+ [String("foo".to_owned()), String("foo".to_owned()),
+ String("f".to_owned()), String("foo".to_owned())], vars),
Ok(bytes!("foofoo ffo").iter().map(|x| *x).collect()));
- assert_eq!(expand(bytes!("%p1%:-4.2s"), [String(~"foo")], vars),
+ assert_eq!(expand(bytes!("%p1%:-4.2s"), [String("foo".to_owned())], vars),
Ok(bytes!("fo ").iter().map(|x| *x).collect()));
assert_eq!(expand(bytes!("%p1%d%p1%.3d%p1%5d%p1%:+d"), [Number(1)], vars),
assert!(names_bytes > 0);
if (bools_bytes as uint) > boolnames.len() {
- return Err(~"incompatible file: more booleans than expected");
+ return Err("incompatible file: more booleans than expected".to_owned());
}
if (numbers_count as uint) > numnames.len() {
- return Err(~"incompatible file: more numbers than expected");
+ return Err("incompatible file: more numbers than expected".to_owned());
}
if (string_offsets_count as uint) > stringnames.len() {
- return Err(~"incompatible file: more string offsets than expected");
+ return Err("incompatible file: more string offsets than expected".to_owned());
}
// don't read NUL
let bytes = try!(file.read_exact(names_bytes as uint - 1));
let names_str = match str::from_utf8(bytes.as_slice()) {
- Some(s) => s.to_owned(), None => return Err(~"input not utf-8"),
+ Some(s) => s.to_owned(), None => return Err("input not utf-8".to_owned()),
};
let term_names: Vec<~str> = names_str.split('|').map(|s| s.to_owned()).collect();
for i in range(0, bools_bytes) {
let b = try!(file.read_byte());
if b < 0 {
- return Err(~"error: expected more bools but hit EOF");
+ return Err("error: expected more bools but hit EOF".to_owned());
} else if b == 1 {
bools_map.insert(bnames[i as uint].to_owned(), true);
}
let string_table = try!(file.read_exact(string_table_bytes as uint));
if string_table.len() != string_table_bytes as uint {
- return Err(~"error: hit EOF before end of string table");
+ return Err("error: hit EOF before end of string table".to_owned());
}
for (i, v) in string_offsets.iter().enumerate() {
offset as uint + len)))
},
None => {
- return Err(~"invalid file: missing NUL in string_table");
+ return Err("invalid file: missing NUL in string_table".to_owned());
}
};
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> ~TermInfo {
let mut strings = HashMap::new();
- strings.insert(~"sgr0", Vec::from_slice(bytes!("\x1b[0m")));
- strings.insert(~"bold", Vec::from_slice(bytes!("\x1b[1m")));
- strings.insert(~"setaf", Vec::from_slice(bytes!("\x1b[3%p1%dm")));
- strings.insert(~"setab", Vec::from_slice(bytes!("\x1b[4%p1%dm")));
+ strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m")));
+ strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m")));
+ strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm")));
+ strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm")));
~TermInfo {
- names: vec!(~"cygwin"), // msys is a fork of an older cygwin version
+ names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: HashMap::new(),
strings: strings
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
p.as_str().unwrap().to_owned()
};
- assert!(x("screen") == ~"/usr/share/terminfo/s/screen");
+ assert!(x("screen") == "/usr/share/terminfo/s/screen".to_owned());
assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
- assert!(x("screen") == ~"/usr/share/terminfo/s/screen");
+ assert!(x("screen") == "/usr/share/terminfo/s/screen".to_owned());
unsetenv("TERMINFO_DIRS");
}
None => Ok(()),
Some(ref mut o) => {
let s = format!("{} {}\n", match *result {
- TrOk => ~"ok",
- TrFailed => ~"failed",
- TrIgnored => ~"ignored",
+ TrOk => "ok".to_owned(),
+ TrFailed => "failed".to_owned(),
+ TrIgnored => "ignored".to_owned(),
TrMetrics(ref mm) => fmt_metrics(mm),
TrBench(ref bs) => fmt_bench_samples(bs)
}, test.name.to_str());
} else {
let filter_str = match opts.filter {
Some(ref f) => (*f).clone(),
- None => ~""
+ None => "".to_owned()
};
fn filter_fn(test: TestDescAndFn, filter_str: &str) ->
impl ToJson for Metric {
fn to_json(&self) -> json::Json {
let mut map = ~TreeMap::new();
- map.insert(~"value", json::Number(self.value));
- map.insert(~"noise", json::Number(self.noise));
+ map.insert("value".to_owned(), json::Number(self.value));
+ map.insert("noise".to_owned(), json::Number(self.noise));
json::Object(map)
}
}
#[test]
fn first_free_arg_should_be_a_filter() {
- let args = vec!(~"progname", ~"filter");
+ let args = vec!("progname".to_owned(), "filter".to_owned());
let opts = match parse_opts(args.as_slice()) {
Some(Ok(o)) => o,
_ => fail!("Malformed arg in first_free_arg_should_be_a_filter")
#[test]
fn parse_ignored_flag() {
- let args = vec!(~"progname", ~"filter", ~"--ignored");
+ let args = vec!("progname".to_owned(), "filter".to_owned(), "--ignored".to_owned());
let opts = match parse_opts(args.as_slice()) {
Some(Ok(o)) => o,
_ => fail!("Malformed arg in parse_ignored_flag")
let filtered = filter_tests(&opts, tests);
assert_eq!(filtered.len(), 1);
- assert_eq!(filtered.get(0).desc.name.to_str(), ~"1");
+ assert_eq!(filtered.get(0).desc.name.to_str(), "1".to_owned());
assert!(filtered.get(0).desc.ignore == false);
}
};
let names =
- vec!(~"sha1::test", ~"int::test_to_str", ~"int::test_pow",
- ~"test::do_not_run_ignored_tests",
- ~"test::ignored_tests_result_in_ignored",
- ~"test::first_free_arg_should_be_a_filter",
- ~"test::parse_ignored_flag", ~"test::filter_for_ignored_option",
- ~"test::sort_tests");
+ vec!("sha1::test".to_owned(), "int::test_to_str".to_owned(), "int::test_pow".to_owned(),
+ "test::do_not_run_ignored_tests".to_owned(),
+ "test::ignored_tests_result_in_ignored".to_owned(),
+ "test::first_free_arg_should_be_a_filter".to_owned(),
+ "test::parse_ignored_flag".to_owned(), "test::filter_for_ignored_option".to_owned(),
+ "test::sort_tests".to_owned());
let tests =
{
fn testfn() { }
let filtered = filter_tests(&opts, tests);
let expected =
- vec!(~"int::test_pow", ~"int::test_to_str", ~"sha1::test",
- ~"test::do_not_run_ignored_tests",
- ~"test::filter_for_ignored_option",
- ~"test::first_free_arg_should_be_a_filter",
- ~"test::ignored_tests_result_in_ignored",
- ~"test::parse_ignored_flag",
- ~"test::sort_tests");
+ vec!("int::test_pow".to_owned(), "int::test_to_str".to_owned(), "sha1::test".to_owned(),
+ "test::do_not_run_ignored_tests".to_owned(),
+ "test::filter_for_ignored_option".to_owned(),
+ "test::first_free_arg_should_be_a_filter".to_owned(),
+ "test::ignored_tests_result_in_ignored".to_owned(),
+ "test::parse_ignored_flag".to_owned(),
+ "test::sort_tests".to_owned());
for (a, b) in expected.iter().zip(filtered.iter()) {
assert!(*a == b.desc.name.to_str());
let diff1 = m2.compare_to_old(&m1, None);
- assert_eq!(*(diff1.find(&~"in-both-noise").unwrap()), LikelyNoise);
- assert_eq!(*(diff1.find(&~"in-first-noise").unwrap()), MetricRemoved);
- assert_eq!(*(diff1.find(&~"in-second-noise").unwrap()), MetricAdded);
- assert_eq!(*(diff1.find(&~"in-both-want-downwards-but-regressed").unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-noise".to_owned()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff1.find(&"in-first-noise".to_owned()).unwrap()), MetricRemoved);
+ assert_eq!(*(diff1.find(&"in-second-noise".to_owned()).unwrap()), MetricAdded);
+ assert_eq!(*(diff1.find(&"in-both-want-downwards-but-regressed".to_owned()).unwrap()),
Regression(100.0));
- assert_eq!(*(diff1.find(&~"in-both-want-downwards-and-improved").unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-downwards-and-improved".to_owned()).unwrap()),
Improvement(50.0));
- assert_eq!(*(diff1.find(&~"in-both-want-upwards-but-regressed").unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-upwards-but-regressed".to_owned()).unwrap()),
Regression(50.0));
- assert_eq!(*(diff1.find(&~"in-both-want-upwards-and-improved").unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-upwards-and-improved".to_owned()).unwrap()),
Improvement(100.0));
assert_eq!(diff1.len(), 7);
let diff2 = m2.compare_to_old(&m1, Some(200.0));
- assert_eq!(*(diff2.find(&~"in-both-noise").unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&~"in-first-noise").unwrap()), MetricRemoved);
- assert_eq!(*(diff2.find(&~"in-second-noise").unwrap()), MetricAdded);
- assert_eq!(*(diff2.find(&~"in-both-want-downwards-but-regressed").unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&~"in-both-want-downwards-and-improved").unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&~"in-both-want-upwards-but-regressed").unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&~"in-both-want-upwards-and-improved").unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-both-noise".to_owned()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-first-noise".to_owned()).unwrap()), MetricRemoved);
+ assert_eq!(*(diff2.find(&"in-second-noise".to_owned()).unwrap()), MetricAdded);
+ assert_eq!(*(diff2.find(&"in-both-want-downwards-but-regressed".to_owned()).unwrap()),
+ LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-both-want-downwards-and-improved".to_owned()).unwrap()),
+ LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-both-want-upwards-but-regressed".to_owned()).unwrap()),
+ LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-both-want-upwards-and-improved".to_owned()).unwrap()),
+ LikelyNoise);
assert_eq!(diff2.len(), 7);
}
let (diff1, ok1) = m2.ratchet(&pth, None);
assert_eq!(ok1, false);
assert_eq!(diff1.len(), 2);
- assert_eq!(*(diff1.find(&~"runtime").unwrap()), Regression(10.0));
- assert_eq!(*(diff1.find(&~"throughput").unwrap()), LikelyNoise);
+ assert_eq!(*(diff1.find(&"runtime".to_owned()).unwrap()), Regression(10.0));
+ assert_eq!(*(diff1.find(&"throughput".to_owned()).unwrap()), LikelyNoise);
// Check that it was not rewritten.
let m3 = MetricMap::load(&pth);
let MetricMap(m3) = m3;
assert_eq!(m3.len(), 2);
- assert_eq!(*(m3.find(&~"runtime").unwrap()), Metric::new(1000.0, 2.0));
- assert_eq!(*(m3.find(&~"throughput").unwrap()), Metric::new(50.0, 2.0));
+ assert_eq!(*(m3.find(&"runtime".to_owned()).unwrap()), Metric::new(1000.0, 2.0));
+ assert_eq!(*(m3.find(&"throughput".to_owned()).unwrap()), Metric::new(50.0, 2.0));
// Ask for a ratchet with an explicit noise-percentage override,
// that should advance.
let (diff2, ok2) = m2.ratchet(&pth, Some(10.0));
assert_eq!(ok2, true);
assert_eq!(diff2.len(), 2);
- assert_eq!(*(diff2.find(&~"runtime").unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&~"throughput").unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"runtime".to_owned()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"throughput".to_owned()).unwrap()), LikelyNoise);
// Check that it was rewritten.
let m4 = MetricMap::load(&pth);
let MetricMap(m4) = m4;
assert_eq!(m4.len(), 2);
- assert_eq!(*(m4.find(&~"runtime").unwrap()), Metric::new(1100.0, 2.0));
- assert_eq!(*(m4.find(&~"throughput").unwrap()), Metric::new(50.0, 2.0));
+ assert_eq!(*(m4.find(&"runtime".to_owned()).unwrap()), Metric::new(1100.0, 2.0));
+ assert_eq!(*(m4.find(&"throughput".to_owned()).unwrap()), Metric::new(50.0, 2.0));
}
}
assert_eq!(out, expected);
}
- t(&Summary::new([-2.0, -1.0]), ~"-2 |[------******#*****---]| -1");
- t(&Summary::new([0.0, 2.0]), ~"0 |[-------*****#*******---]| 2");
- t(&Summary::new([-2.0, 0.0]), ~"-2 |[------******#******---]| 0");
+ t(&Summary::new([-2.0, -1.0]), "-2 |[------******#*****---]| -1".to_owned());
+ t(&Summary::new([0.0, 2.0]), "0 |[-------*****#*******---]| 2".to_owned());
+ t(&Summary::new([-2.0, 0.0]), "-2 |[------******#******---]| 0".to_owned());
}
#[test]
-> Result<uint, ~str> {
match ch {
'A' => match match_strs(s, pos, [
- (~"Sunday", 0_i32),
- (~"Monday", 1_i32),
- (~"Tuesday", 2_i32),
- (~"Wednesday", 3_i32),
- (~"Thursday", 4_i32),
- (~"Friday", 5_i32),
- (~"Saturday", 6_i32)
+ ("Sunday".to_owned(), 0_i32),
+ ("Monday".to_owned(), 1_i32),
+ ("Tuesday".to_owned(), 2_i32),
+ ("Wednesday".to_owned(), 3_i32),
+ ("Thursday".to_owned(), 4_i32),
+ ("Friday".to_owned(), 5_i32),
+ ("Saturday".to_owned(), 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(~"Invalid day")
+ None => Err("Invalid day".to_owned())
},
'a' => match match_strs(s, pos, [
- (~"Sun", 0_i32),
- (~"Mon", 1_i32),
- (~"Tue", 2_i32),
- (~"Wed", 3_i32),
- (~"Thu", 4_i32),
- (~"Fri", 5_i32),
- (~"Sat", 6_i32)
+ ("Sun".to_owned(), 0_i32),
+ ("Mon".to_owned(), 1_i32),
+ ("Tue".to_owned(), 2_i32),
+ ("Wed".to_owned(), 3_i32),
+ ("Thu".to_owned(), 4_i32),
+ ("Fri".to_owned(), 5_i32),
+ ("Sat".to_owned(), 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(~"Invalid day")
+ None => Err("Invalid day".to_owned())
},
'B' => match match_strs(s, pos, [
- (~"January", 0_i32),
- (~"February", 1_i32),
- (~"March", 2_i32),
- (~"April", 3_i32),
- (~"May", 4_i32),
- (~"June", 5_i32),
- (~"July", 6_i32),
- (~"August", 7_i32),
- (~"September", 8_i32),
- (~"October", 9_i32),
- (~"November", 10_i32),
- (~"December", 11_i32)
+ ("January".to_owned(), 0_i32),
+ ("February".to_owned(), 1_i32),
+ ("March".to_owned(), 2_i32),
+ ("April".to_owned(), 3_i32),
+ ("May".to_owned(), 4_i32),
+ ("June".to_owned(), 5_i32),
+ ("July".to_owned(), 6_i32),
+ ("August".to_owned(), 7_i32),
+ ("September".to_owned(), 8_i32),
+ ("October".to_owned(), 9_i32),
+ ("November".to_owned(), 10_i32),
+ ("December".to_owned(), 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err(~"Invalid month")
+ None => Err("Invalid month".to_owned())
},
'b' | 'h' => match match_strs(s, pos, [
- (~"Jan", 0_i32),
- (~"Feb", 1_i32),
- (~"Mar", 2_i32),
- (~"Apr", 3_i32),
- (~"May", 4_i32),
- (~"Jun", 5_i32),
- (~"Jul", 6_i32),
- (~"Aug", 7_i32),
- (~"Sep", 8_i32),
- (~"Oct", 9_i32),
- (~"Nov", 10_i32),
- (~"Dec", 11_i32)
+ ("Jan".to_owned(), 0_i32),
+ ("Feb".to_owned(), 1_i32),
+ ("Mar".to_owned(), 2_i32),
+ ("Apr".to_owned(), 3_i32),
+ ("May".to_owned(), 4_i32),
+ ("Jun".to_owned(), 5_i32),
+ ("Jul".to_owned(), 6_i32),
+ ("Aug".to_owned(), 7_i32),
+ ("Sep".to_owned(), 8_i32),
+ ("Oct".to_owned(), 9_i32),
+ ("Nov".to_owned(), 10_i32),
+ ("Dec".to_owned(), 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err(~"Invalid month")
+ None => Err("Invalid month".to_owned())
},
'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
99_i32) {
tm.tm_year += (v * 100_i32) - 1900_i32;
Ok(pos)
}
- None => Err(~"Invalid year")
+ None => Err("Invalid year".to_owned())
},
'c' => {
parse_type(s, pos, 'a', &mut *tm)
'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
31_i32) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
- None => Err(~"Invalid day of the month")
+ None => Err("Invalid day of the month".to_owned())
},
'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
31_i32) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
- None => Err(~"Invalid day of the month")
+ None => Err("Invalid day of the month".to_owned())
},
'f' => {
let (val, pos) = match_fractional_seconds(s, pos);
'H' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
}
}
'I' => {
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
}
}
'j' => {
tm.tm_yday = v - 1_i32;
Ok(pos)
}
- None => Err(~"Invalid day of year")
+ None => Err("Invalid day of year".to_owned())
}
}
'k' => {
match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
}
}
'l' => {
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
}
}
'M' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
- None => Err(~"Invalid minute")
+ None => Err("Invalid minute".to_owned())
}
}
'm' => {
tm.tm_mon = v - 1_i32;
Ok(pos)
}
- None => Err(~"Invalid month")
+ None => Err("Invalid month".to_owned())
}
}
'n' => parse_char(s, pos, '\n'),
'P' => match match_strs(s, pos,
- [(~"am", 0_i32), (~"pm", 12_i32)]) {
+ [("am".to_owned(), 0_i32), ("pm".to_owned(), 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
},
'p' => match match_strs(s, pos,
- [(~"AM", 0_i32), (~"PM", 12_i32)]) {
+ [("AM".to_owned(), 0_i32), ("PM".to_owned(), 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err(~"Invalid hour")
+ None => Err("Invalid hour".to_owned())
},
'R' => {
parse_type(s, pos, 'H', &mut *tm)
tm.tm_sec = v;
Ok(pos)
}
- None => Err(~"Invalid second")
+ None => Err("Invalid second".to_owned())
}
}
//'s' {}
tm.tm_wday = if v == 7 { 0 } else { v };
Ok(pos)
}
- None => Err(~"Invalid day of week")
+ None => Err("Invalid day of week".to_owned())
}
}
'v' => {
'w' => {
match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(~"Invalid day of week")
+ None => Err("Invalid day of week".to_owned())
}
}
'Y' => {
tm.tm_year = v - 1900_i32;
Ok(pos)
}
- None => Err(~"Invalid year")
+ None => Err("Invalid year".to_owned())
}
}
'y' => {
tm.tm_year = v;
Ok(pos)
}
- None => Err(~"Invalid year")
+ None => Err("Invalid year".to_owned())
}
}
'Z' => {
if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
tm.tm_gmtoff = 0_i32;
- tm.tm_zone = ~"UTC";
+ tm.tm_zone = "UTC".to_owned();
Ok(pos + 3u)
} else {
// It's odd, but to maintain compatibility with c's
let (v, pos) = item;
if v == 0_i32 {
tm.tm_gmtoff = 0_i32;
- tm.tm_zone = ~"UTC";
+ tm.tm_zone = "UTC".to_owned();
}
Ok(pos)
}
- None => Err(~"Invalid zone offset")
+ None => Err("Invalid zone offset".to_owned())
}
} else {
- Err(~"Invalid zone offset")
+ Err("Invalid zone offset".to_owned())
}
}
'%' => parse_char(s, pos, '%'),
tm_yday: 0_i32,
tm_isdst: 0_i32,
tm_gmtoff: 0_i32,
- tm_zone: ~"",
+ tm_zone: "".to_owned(),
tm_nsec: 0_i32,
};
let mut pos = 0u;
let len = s.len();
- let mut result = Err(~"Invalid time");
+ let mut result = Err("Invalid time".to_owned());
while pos < len {
let range = s.char_range_at(pos);
'G' => format!("{}", year),
'g' => format!("{:02d}", (year % 100 + 100) % 100),
'V' => format!("{:02d}", days / 7 + 1),
- _ => ~""
+ _ => "".to_owned()
}
}
let die = || format!("strftime: can't understand this format {} ", ch);
match ch {
'A' => match tm.tm_wday as int {
- 0 => ~"Sunday",
- 1 => ~"Monday",
- 2 => ~"Tuesday",
- 3 => ~"Wednesday",
- 4 => ~"Thursday",
- 5 => ~"Friday",
- 6 => ~"Saturday",
+ 0 => "Sunday".to_owned(),
+ 1 => "Monday".to_owned(),
+ 2 => "Tuesday".to_owned(),
+ 3 => "Wednesday".to_owned(),
+ 4 => "Thursday".to_owned(),
+ 5 => "Friday".to_owned(),
+ 6 => "Saturday".to_owned(),
_ => die()
},
'a' => match tm.tm_wday as int {
- 0 => ~"Sun",
- 1 => ~"Mon",
- 2 => ~"Tue",
- 3 => ~"Wed",
- 4 => ~"Thu",
- 5 => ~"Fri",
- 6 => ~"Sat",
+ 0 => "Sun".to_owned(),
+ 1 => "Mon".to_owned(),
+ 2 => "Tue".to_owned(),
+ 3 => "Wed".to_owned(),
+ 4 => "Thu".to_owned(),
+ 5 => "Fri".to_owned(),
+ 6 => "Sat".to_owned(),
_ => die()
},
'B' => match tm.tm_mon as int {
- 0 => ~"January",
- 1 => ~"February",
- 2 => ~"March",
- 3 => ~"April",
- 4 => ~"May",
- 5 => ~"June",
- 6 => ~"July",
- 7 => ~"August",
- 8 => ~"September",
- 9 => ~"October",
- 10 => ~"November",
- 11 => ~"December",
+ 0 => "January".to_owned(),
+ 1 => "February".to_owned(),
+ 2 => "March".to_owned(),
+ 3 => "April".to_owned(),
+ 4 => "May".to_owned(),
+ 5 => "June".to_owned(),
+ 6 => "July".to_owned(),
+ 7 => "August".to_owned(),
+ 8 => "September".to_owned(),
+ 9 => "October".to_owned(),
+ 10 => "November".to_owned(),
+ 11 => "December".to_owned(),
_ => die()
},
'b' | 'h' => match tm.tm_mon as int {
- 0 => ~"Jan",
- 1 => ~"Feb",
- 2 => ~"Mar",
- 3 => ~"Apr",
- 4 => ~"May",
- 5 => ~"Jun",
- 6 => ~"Jul",
- 7 => ~"Aug",
- 8 => ~"Sep",
- 9 => ~"Oct",
- 10 => ~"Nov",
- 11 => ~"Dec",
+ 0 => "Jan".to_owned(),
+ 1 => "Feb".to_owned(),
+ 2 => "Mar".to_owned(),
+ 3 => "Apr".to_owned(),
+ 4 => "May".to_owned(),
+ 5 => "Jun".to_owned(),
+ 6 => "Jul".to_owned(),
+ 7 => "Aug".to_owned(),
+ 8 => "Sep".to_owned(),
+ 9 => "Oct".to_owned(),
+ 10 => "Nov".to_owned(),
+ 11 => "Dec".to_owned(),
_ => die()
},
'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
}
'M' => format!("{:02d}", tm.tm_min),
'm' => format!("{:02d}", tm.tm_mon + 1),
- 'n' => ~"\n",
- 'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
- 'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
+ 'n' => "\n".to_owned(),
+ 'P' => if (tm.tm_hour as int) < 12 { "am".to_owned() } else { "pm".to_owned() },
+ 'p' => if (tm.tm_hour as int) < 12 { "AM".to_owned() } else { "PM".to_owned() },
'R' => {
format!("{}:{}",
parse_type('H', tm),
parse_type('M', tm),
parse_type('S', tm))
}
- 't' => ~"\t",
+ 't' => "\t".to_owned(),
'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
'u' => {
let i = tm.tm_wday as int;
format!("{}{:02d}{:02d}", sign, h, m)
}
'+' => tm.rfc3339(),
- '%' => ~"%",
+ '%' => "%".to_owned(),
_ => die()
}
}
assert_eq!(utc.tm_yday, 43_i32);
assert_eq!(utc.tm_isdst, 0_i32);
assert_eq!(utc.tm_gmtoff, 0_i32);
- assert_eq!(utc.tm_zone, ~"UTC");
+ assert_eq!(utc.tm_zone, "UTC".to_owned());
assert_eq!(utc.tm_nsec, 54321_i32);
}
// FIXME (#2350): We should probably standardize on the timezone
// abbreviation.
let zone = &local.tm_zone;
- assert!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
+ assert!(*zone == "PST".to_owned() || *zone == "Pacific Standard Time".to_owned());
assert_eq!(local.tm_nsec, 54321_i32);
}
assert!(tm.tm_wday == 0_i32);
assert!(tm.tm_isdst == 0_i32);
assert!(tm.tm_gmtoff == 0_i32);
- assert!(tm.tm_zone == ~"");
+ assert!(tm.tm_zone == "".to_owned());
assert!(tm.tm_nsec == 0_i32);
}
Err(_) => ()
}
let format = "%a %b %e %T.%f %Y";
- assert_eq!(strptime("", format), Err(~"Invalid time"));
+ assert_eq!(strptime("", format), Err("Invalid time".to_owned()));
assert!(strptime("Fri Feb 13 15:31:30", format)
- == Err(~"Invalid time"));
+ == Err("Invalid time".to_owned()));
match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
Err(e) => fail!(e),
assert!(tm.tm_yday == 0_i32);
assert!(tm.tm_isdst == 0_i32);
assert!(tm.tm_gmtoff == 0_i32);
- assert!(tm.tm_zone == ~"");
+ assert!(tm.tm_zone == "".to_owned());
assert!(tm.tm_nsec == 12340000_i32);
}
}
}
let days = [
- ~"Sunday",
- ~"Monday",
- ~"Tuesday",
- ~"Wednesday",
- ~"Thursday",
- ~"Friday",
- ~"Saturday"
+ "Sunday".to_owned(),
+ "Monday".to_owned(),
+ "Tuesday".to_owned(),
+ "Wednesday".to_owned(),
+ "Thursday".to_owned(),
+ "Friday".to_owned(),
+ "Saturday".to_owned()
];
for day in days.iter() {
assert!(test(*day, "%A"));
}
let days = [
- ~"Sun",
- ~"Mon",
- ~"Tue",
- ~"Wed",
- ~"Thu",
- ~"Fri",
- ~"Sat"
+ "Sun".to_owned(),
+ "Mon".to_owned(),
+ "Tue".to_owned(),
+ "Wed".to_owned(),
+ "Thu".to_owned(),
+ "Fri".to_owned(),
+ "Sat".to_owned()
];
for day in days.iter() {
assert!(test(*day, "%a"));
}
let months = [
- ~"January",
- ~"February",
- ~"March",
- ~"April",
- ~"May",
- ~"June",
- ~"July",
- ~"August",
- ~"September",
- ~"October",
- ~"November",
- ~"December"
+ "January".to_owned(),
+ "February".to_owned(),
+ "March".to_owned(),
+ "April".to_owned(),
+ "May".to_owned(),
+ "June".to_owned(),
+ "July".to_owned(),
+ "August".to_owned(),
+ "September".to_owned(),
+ "October".to_owned(),
+ "November".to_owned(),
+ "December".to_owned()
];
for day in months.iter() {
assert!(test(*day, "%B"));
}
let months = [
- ~"Jan",
- ~"Feb",
- ~"Mar",
- ~"Apr",
- ~"May",
- ~"Jun",
- ~"Jul",
- ~"Aug",
- ~"Sep",
- ~"Oct",
- ~"Nov",
- ~"Dec"
+ "Jan".to_owned(),
+ "Feb".to_owned(),
+ "Mar".to_owned(),
+ "Apr".to_owned(),
+ "May".to_owned(),
+ "Jun".to_owned(),
+ "Jul".to_owned(),
+ "Aug".to_owned(),
+ "Sep".to_owned(),
+ "Oct".to_owned(),
+ "Nov".to_owned(),
+ "Dec".to_owned()
];
for day in months.iter() {
assert!(test(*day, "%b"));
assert!(test("2009", "%Y"));
assert!(test("09", "%y"));
assert!(strptime("UTC", "%Z").unwrap().tm_zone ==
- ~"UTC");
+ "UTC".to_owned());
assert!(strptime("PST", "%Z").unwrap().tm_zone ==
- ~"");
+ "".to_owned());
assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
0);
assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
assert!(test("%", "%%"));
// Test for #7256
- assert_eq!(strptime("360", "%Y-%m-%d"), Err(~"Invalid year"))
+ assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_owned()))
}
fn test_ctime() {
debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
- assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
- assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
+ assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_owned());
+ assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_owned());
}
fn test_strftime() {
let utc = at_utc(time);
let local = at(time);
- assert_eq!(local.strftime(""), ~"");
- assert_eq!(local.strftime("%A"), ~"Friday");
- assert_eq!(local.strftime("%a"), ~"Fri");
- assert_eq!(local.strftime("%B"), ~"February");
- assert_eq!(local.strftime("%b"), ~"Feb");
- assert_eq!(local.strftime("%C"), ~"20");
- assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009");
- assert_eq!(local.strftime("%D"), ~"02/13/09");
- assert_eq!(local.strftime("%d"), ~"13");
- assert_eq!(local.strftime("%e"), ~"13");
- assert_eq!(local.strftime("%f"), ~"000054321");
- assert_eq!(local.strftime("%F"), ~"2009-02-13");
- assert_eq!(local.strftime("%G"), ~"2009");
- assert_eq!(local.strftime("%g"), ~"09");
- assert_eq!(local.strftime("%H"), ~"15");
- assert_eq!(local.strftime("%I"), ~"03");
- assert_eq!(local.strftime("%j"), ~"044");
- assert_eq!(local.strftime("%k"), ~"15");
- assert_eq!(local.strftime("%l"), ~" 3");
- assert_eq!(local.strftime("%M"), ~"31");
- assert_eq!(local.strftime("%m"), ~"02");
- assert_eq!(local.strftime("%n"), ~"\n");
- assert_eq!(local.strftime("%P"), ~"pm");
- assert_eq!(local.strftime("%p"), ~"PM");
- assert_eq!(local.strftime("%R"), ~"15:31");
- assert_eq!(local.strftime("%r"), ~"03:31:30 PM");
- assert_eq!(local.strftime("%S"), ~"30");
- assert_eq!(local.strftime("%s"), ~"1234567890");
- assert_eq!(local.strftime("%T"), ~"15:31:30");
- assert_eq!(local.strftime("%t"), ~"\t");
- assert_eq!(local.strftime("%U"), ~"06");
- assert_eq!(local.strftime("%u"), ~"5");
- assert_eq!(local.strftime("%V"), ~"07");
- assert_eq!(local.strftime("%v"), ~"13-Feb-2009");
- assert_eq!(local.strftime("%W"), ~"06");
- assert_eq!(local.strftime("%w"), ~"5");
- assert_eq!(local.strftime("%X"), ~"15:31:30"); // FIXME (#2350): support locale
- assert_eq!(local.strftime("%x"), ~"02/13/09"); // FIXME (#2350): support locale
- assert_eq!(local.strftime("%Y"), ~"2009");
- assert_eq!(local.strftime("%y"), ~"09");
- assert_eq!(local.strftime("%+"), ~"2009-02-13T15:31:30-08:00");
+ assert_eq!(local.strftime(""), "".to_owned());
+ assert_eq!(local.strftime("%A"), "Friday".to_owned());
+ assert_eq!(local.strftime("%a"), "Fri".to_owned());
+ assert_eq!(local.strftime("%B"), "February".to_owned());
+ assert_eq!(local.strftime("%b"), "Feb".to_owned());
+ assert_eq!(local.strftime("%C"), "20".to_owned());
+ assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_owned());
+ assert_eq!(local.strftime("%D"), "02/13/09".to_owned());
+ assert_eq!(local.strftime("%d"), "13".to_owned());
+ assert_eq!(local.strftime("%e"), "13".to_owned());
+ assert_eq!(local.strftime("%f"), "000054321".to_owned());
+ assert_eq!(local.strftime("%F"), "2009-02-13".to_owned());
+ assert_eq!(local.strftime("%G"), "2009".to_owned());
+ assert_eq!(local.strftime("%g"), "09".to_owned());
+ assert_eq!(local.strftime("%H"), "15".to_owned());
+ assert_eq!(local.strftime("%I"), "03".to_owned());
+ assert_eq!(local.strftime("%j"), "044".to_owned());
+ assert_eq!(local.strftime("%k"), "15".to_owned());
+ assert_eq!(local.strftime("%l"), " 3".to_owned());
+ assert_eq!(local.strftime("%M"), "31".to_owned());
+ assert_eq!(local.strftime("%m"), "02".to_owned());
+ assert_eq!(local.strftime("%n"), "\n".to_owned());
+ assert_eq!(local.strftime("%P"), "pm".to_owned());
+ assert_eq!(local.strftime("%p"), "PM".to_owned());
+ assert_eq!(local.strftime("%R"), "15:31".to_owned());
+ assert_eq!(local.strftime("%r"), "03:31:30 PM".to_owned());
+ assert_eq!(local.strftime("%S"), "30".to_owned());
+ assert_eq!(local.strftime("%s"), "1234567890".to_owned());
+ assert_eq!(local.strftime("%T"), "15:31:30".to_owned());
+ assert_eq!(local.strftime("%t"), "\t".to_owned());
+ assert_eq!(local.strftime("%U"), "06".to_owned());
+ assert_eq!(local.strftime("%u"), "5".to_owned());
+ assert_eq!(local.strftime("%V"), "07".to_owned());
+ assert_eq!(local.strftime("%v"), "13-Feb-2009".to_owned());
+ assert_eq!(local.strftime("%W"), "06".to_owned());
+ assert_eq!(local.strftime("%w"), "5".to_owned());
+ assert_eq!(local.strftime("%X"), "15:31:30".to_owned()); // FIXME (#2350): support locale
+ assert_eq!(local.strftime("%x"), "02/13/09".to_owned()); // FIXME (#2350): support locale
+ assert_eq!(local.strftime("%Y"), "2009".to_owned());
+ assert_eq!(local.strftime("%y"), "09".to_owned());
+ assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_owned());
// FIXME (#2350): We should probably standardize on the timezone
// abbreviation.
let zone = local.strftime("%Z");
- assert!(zone == ~"PST" || zone == ~"Pacific Standard Time");
+ assert!(zone == "PST".to_owned() || zone == "Pacific Standard Time".to_owned());
- assert_eq!(local.strftime("%z"), ~"-0800");
- assert_eq!(local.strftime("%%"), ~"%");
+ assert_eq!(local.strftime("%z"), "-0800".to_owned());
+ assert_eq!(local.strftime("%%"), "%".to_owned());
// FIXME (#2350): We should probably standardize on the timezone
// abbreviation.
let rfc822 = local.rfc822();
- let prefix = ~"Fri, 13 Feb 2009 15:31:30 ";
+ let prefix = "Fri, 13 Feb 2009 15:31:30 ".to_owned();
assert!(rfc822 == prefix + "PST" || rfc822 == prefix + "Pacific Standard Time");
- assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
- assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800");
- assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00");
+ assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_owned());
+ assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_owned());
+ assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_owned());
- assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
- assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT");
- assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000");
- assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z");
+ assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_owned());
+ assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_owned());
+ assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_owned());
+ assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_owned());
}
fn test_timespec_eq_ord() {
/// ```rust
/// use url::{Url, UserInfo};
///
-/// let url = Url { scheme: ~"https",
-/// user: Some(UserInfo { user: ~"username", pass: None }),
-/// host: ~"example.com",
-/// port: Some(~"8080"),
-/// path: ~"/foo/bar",
-/// query: vec!((~"baz", ~"qux")),
-/// fragment: Some(~"quz") };
+/// let url = Url { scheme: "https".to_owned(),
+/// user: Some(UserInfo { user: "username".to_owned(), pass: None }),
+/// host: "example.com".to_owned(),
+/// port: Some("8080".to_owned()),
+/// path: "/foo/bar".to_owned(),
+/// query: vec!(("baz".to_owned(), "qux".to_owned())),
+/// fragment: Some("quz".to_owned()) };
/// // https://username@example.com:8080/foo/bar?baz=qux#quz
/// ```
#[deriving(Clone, Eq, TotalEq)]
pub port: Option<~str>,
/// The path component of a URL, for example `/foo/bar`.
pub path: ~str,
- /// The query component of a URL. `vec!((~"baz", ~"qux"))` represents the
+ /// The query component of a URL. `vec!(("baz".to_owned(), "qux".to_owned()))` represents the
/// fragment `baz=qux` in the above example.
pub query: Query,
/// The fragment component, such as `quz`. Doesn't include the leading `#` character.
pub struct Path {
/// The path component of a URL, for example `/foo/bar`.
pub path: ~str,
- /// The query component of a URL. `vec!((~"baz", ~"qux"))` represents the
+ /// The query component of a URL. `vec!(("baz".to_owned(), "qux".to_owned()))` represents the
/// fragment `baz=qux` in the above example.
pub query: Query,
/// The fragment component, such as `quz`. Doesn't include the leading `#` character.
}
}
if index+mat == len {
- return (s.slice(0, index).to_owned(), ~"");
+ return (s.slice(0, index).to_owned(), "".to_owned());
} else {
return (s.slice(0, index).to_owned(),
s.slice(index + mat, s.len()).to_owned());
* # Example
*
* ```rust
- * let query = vec!((~"title", ~"The Village"), (~"north", ~"52.91"), (~"west", ~"4.10"));
+ * let query = vec!(("title".to_owned(), "The Village".to_owned()),
+ ("north".to_owned(), "52.91".to_owned()),
+ ("west".to_owned(), "4.10".to_owned()));
* println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10
* ```
*/
*
* let scheme = match get_scheme("https://example.com/") {
* Ok((sch, _)) => sch,
- * Err(_) => ~"(None)",
+ * Err(_) => "(None)".to_owned(),
* };
* println!("Scheme in use: {}.", scheme); // Scheme in use: https.
* ```
'A' .. 'Z' | 'a' .. 'z' => continue,
'0' .. '9' | '+' | '-' | '.' => {
if i == 0 {
- return Err(~"url: Scheme must begin with a letter.");
+ return Err("url: Scheme must begin with a letter.".to_owned());
}
continue;
}
':' => {
if i == 0 {
- return Err(~"url: Scheme cannot be empty.");
+ return Err("url: Scheme cannot be empty.".to_owned());
} else {
return Ok((rawurl.slice(0,i).to_owned(),
rawurl.slice(i+1,rawurl.len()).to_owned()));
}
}
_ => {
- return Err(~"url: Invalid character in scheme.");
+ return Err("url: Invalid character in scheme.".to_owned());
}
}
};
- return Err(~"url: Scheme must be terminated with a colon.");
+ return Err("url: Scheme must be terminated with a colon.".to_owned());
}
#[deriving(Clone, Eq)]
Result<(Option<UserInfo>, ~str, Option<~str>, ~str), ~str> {
if !rawurl.starts_with("//") {
// there is no authority.
- return Ok((None, ~"", None, rawurl.to_str()));
+ return Ok((None, "".to_owned(), None, rawurl.to_str()));
}
enum State {
let mut input = Digit; // most restricted, start here.
let mut userinfo = None;
- let mut host = ~"";
+ let mut host = "".to_owned();
let mut port = None;
let mut colon_count = 0;
// separators, don't change anything
}
_ => {
- return Err(~"Illegal character in authority");
+ return Err("Illegal character in authority".to_owned());
}
}
// multiple colons means ipv6 address.
if input == Unreserved {
return Err(
- ~"Illegal characters in IPv6 address.");
+ "Illegal characters in IPv6 address.".to_owned());
}
st = Ip6Host;
}
}
Ip6Port => {
if input == Unreserved {
- return Err(~"Illegal characters in authority.");
+ return Err("Illegal characters in authority.".to_owned());
}
st = Ip6Host;
}
}
}
_ => {
- return Err(~"Invalid ':' in authority.");
+ return Err("Invalid ':' in authority.".to_owned());
}
}
input = Digit; // reset input class
st = InHost;
}
_ => {
- return Err(~"Invalid '@' in authority.");
+ return Err("Invalid '@' in authority.".to_owned());
}
}
begin = i+1;
}
PassHostPort | Ip6Port => {
if input != Digit {
- return Err(~"Non-digit characters in port.");
+ return Err("Non-digit characters in port.".to_owned());
}
host = rawurl.slice(begin, pos).to_owned();
port = Some(rawurl.slice(pos+1, end).to_owned());
}
InPort => {
if input != Digit {
- return Err(~"Non-digit characters in port.");
+ return Err("Non-digit characters in port.".to_owned());
}
port = Some(rawurl.slice(pos+1, end).to_owned());
}
end = i;
break;
}
- _ => return Err(~"Invalid character in path.")
+ _ => return Err("Invalid character in path.".to_owned())
}
}
if authority {
if end != 0 && !rawurl.starts_with("/") {
- return Err(~"Non-empty path must begin with\
- '/' in presence of authority.");
+ return Err("Non-empty path must begin with\
+ '/' in presence of authority.".to_owned());
}
}
};
// path
- let has_authority = if host == ~"" { false } else { true };
+ let has_authority = if host == "".to_owned() { false } else { true };
let (path, rest) = match get_path(rest, has_authority) {
Ok(val) => val,
Err(e) => return Err(e),
#[test]
fn test_split_char_first() {
let (u,v) = split_char_first("hello, sweet world", ',');
- assert_eq!(u, ~"hello");
- assert_eq!(v, ~" sweet world");
+ assert_eq!(u, "hello".to_owned());
+ assert_eq!(v, " sweet world".to_owned());
let (u,v) = split_char_first("hello sweet world", ',');
- assert_eq!(u, ~"hello sweet world");
- assert_eq!(v, ~"");
+ assert_eq!(u, "hello sweet world".to_owned());
+ assert_eq!(v, "".to_owned());
}
#[test]
fn test_get_authority() {
let (u, h, p, r) = get_authority(
"//user:pass@rust-lang.org/something").unwrap();
- assert_eq!(u, Some(UserInfo::new(~"user", Some(~"pass"))));
- assert_eq!(h, ~"rust-lang.org");
+ assert_eq!(u, Some(UserInfo::new("user".to_owned(), Some("pass".to_owned()))));
+ assert_eq!(h, "rust-lang.org".to_owned());
assert!(p.is_none());
- assert_eq!(r, ~"/something");
+ assert_eq!(r, "/something".to_owned());
let (u, h, p, r) = get_authority(
"//rust-lang.org:8000?something").unwrap();
assert!(u.is_none());
- assert_eq!(h, ~"rust-lang.org");
- assert_eq!(p, Some(~"8000"));
- assert_eq!(r, ~"?something");
+ assert_eq!(h, "rust-lang.org".to_owned());
+ assert_eq!(p, Some("8000".to_owned()));
+ assert_eq!(r, "?something".to_owned());
let (u, h, p, r) = get_authority(
"//rust-lang.org#blah").unwrap();
assert!(u.is_none());
- assert_eq!(h, ~"rust-lang.org");
+ assert_eq!(h, "rust-lang.org".to_owned());
assert!(p.is_none());
- assert_eq!(r, ~"#blah");
+ assert_eq!(r, "#blah".to_owned());
// ipv6 tests
let (_, h, _, _) = get_authority(
"//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap();
- assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_owned());
let (_, h, p, _) = get_authority(
"//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap();
- assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
- assert_eq!(p, Some(~"8000"));
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_owned());
+ assert_eq!(p, Some("8000".to_owned()));
let (u, h, p, _) = get_authority(
"//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"
).unwrap();
- assert_eq!(u, Some(UserInfo::new(~"us", Some(~"p"))));
- assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
- assert_eq!(p, Some(~"8000"));
+ assert_eq!(u, Some(UserInfo::new("us".to_owned(), Some("p".to_owned()))));
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_owned());
+ assert_eq!(p, Some("8000".to_owned()));
// invalid authorities;
assert!(get_authority("//user:pass@rust-lang:something").is_err());
// these parse as empty, because they don't start with '//'
let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap();
- assert_eq!(h, ~"");
+ assert_eq!(h, "".to_owned());
let (_, h, _, _) = get_authority("rust-lang.org").unwrap();
- assert_eq!(h, ~"");
+ assert_eq!(h, "".to_owned());
}
#[test]
fn test_get_path() {
let (p, r) = get_path("/something+%20orother", true).unwrap();
- assert_eq!(p, ~"/something+ orother");
- assert_eq!(r, ~"");
+ assert_eq!(p, "/something+ orother".to_owned());
+ assert_eq!(r, "".to_owned());
let (p, r) = get_path("test@email.com#fragment", false).unwrap();
- assert_eq!(p, ~"test@email.com");
- assert_eq!(r, ~"#fragment");
+ assert_eq!(p, "test@email.com".to_owned());
+ assert_eq!(r, "#fragment".to_owned());
let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap();
- assert_eq!(p, ~"/gen/:addr=");
- assert_eq!(r, ~"?q=v");
+ assert_eq!(p, "/gen/:addr=".to_owned());
+ assert_eq!(r, "?q=v".to_owned());
//failure cases
assert!(get_path("something?q", true).is_err());
#[test]
fn test_url_parse() {
- let url = ~"http://user:pass@rust-lang.org:8080/doc/~u?s=v#something";
+ let url = "http://user:pass@rust-lang.org:8080/doc/~u?s=v#something".to_owned();
let up = from_str(url);
let u = up.unwrap();
- assert_eq!(&u.scheme, &~"http");
- assert_eq!(&u.user, &Some(UserInfo::new(~"user", Some(~"pass"))));
- assert_eq!(&u.host, &~"rust-lang.org");
- assert_eq!(&u.port, &Some(~"8080"));
- assert_eq!(&u.path, &~"/doc/~u");
- assert_eq!(&u.query, &vec!((~"s", ~"v")));
- assert_eq!(&u.fragment, &Some(~"something"));
+ assert_eq!(&u.scheme, &"http".to_owned());
+ assert_eq!(&u.user, &Some(UserInfo::new("user".to_owned(), Some("pass".to_owned()))));
+ assert_eq!(&u.host, &"rust-lang.org".to_owned());
+ assert_eq!(&u.port, &Some("8080".to_owned()));
+ assert_eq!(&u.path, &"/doc/~u".to_owned());
+ assert_eq!(&u.query, &vec!(("s".to_owned(), "v".to_owned())));
+ assert_eq!(&u.fragment, &Some("something".to_owned()));
}
#[test]
fn test_path_parse() {
- let path = ~"/doc/~u?s=v#something";
+ let path = "/doc/~u?s=v#something".to_owned();
let up = path_from_str(path);
let u = up.unwrap();
- assert_eq!(&u.path, &~"/doc/~u");
- assert_eq!(&u.query, &vec!((~"s", ~"v")));
- assert_eq!(&u.fragment, &Some(~"something"));
+ assert_eq!(&u.path, &"/doc/~u".to_owned());
+ assert_eq!(&u.query, &vec!(("s".to_owned(), "v".to_owned())));
+ assert_eq!(&u.fragment, &Some("something".to_owned()));
}
#[test]
fn test_url_parse_host_slash() {
- let urlstr = ~"http://0.42.42.42/";
+ let urlstr = "http://0.42.42.42/".to_owned();
let url = from_str(urlstr).unwrap();
- assert!(url.host == ~"0.42.42.42");
- assert!(url.path == ~"/");
+ assert!(url.host == "0.42.42.42".to_owned());
+ assert!(url.path == "/".to_owned());
}
#[test]
fn test_path_parse_host_slash() {
- let pathstr = ~"/";
+ let pathstr = "/".to_owned();
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == ~"/");
+ assert!(path.path == "/".to_owned());
}
#[test]
fn test_url_host_with_port() {
- let urlstr = ~"scheme://host:1234";
+ let urlstr = "scheme://host:1234".to_owned();
let url = from_str(urlstr).unwrap();
- assert_eq!(&url.scheme, &~"scheme");
- assert_eq!(&url.host, &~"host");
- assert_eq!(&url.port, &Some(~"1234"));
- assert_eq!(&url.path, &~""); // is empty path really correct? Other tests think so
- let urlstr = ~"scheme://host:1234/";
+ assert_eq!(&url.scheme, &"scheme".to_owned());
+ assert_eq!(&url.host, &"host".to_owned());
+ assert_eq!(&url.port, &Some("1234".to_owned()));
+ assert_eq!(&url.path, &"".to_owned()); // is empty path really correct? Other tests think so
+ let urlstr = "scheme://host:1234/".to_owned();
let url = from_str(urlstr).unwrap();
- assert_eq!(&url.scheme, &~"scheme");
- assert_eq!(&url.host, &~"host");
- assert_eq!(&url.port, &Some(~"1234"));
- assert_eq!(&url.path, &~"/");
+ assert_eq!(&url.scheme, &"scheme".to_owned());
+ assert_eq!(&url.host, &"host".to_owned());
+ assert_eq!(&url.port, &Some("1234".to_owned()));
+ assert_eq!(&url.path, &"/".to_owned());
}
#[test]
fn test_url_with_underscores() {
- let urlstr = ~"http://dotcom.com/file_name.html";
+ let urlstr = "http://dotcom.com/file_name.html".to_owned();
let url = from_str(urlstr).unwrap();
- assert!(url.path == ~"/file_name.html");
+ assert!(url.path == "/file_name.html".to_owned());
}
#[test]
fn test_path_with_underscores() {
- let pathstr = ~"/file_name.html";
+ let pathstr = "/file_name.html".to_owned();
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == ~"/file_name.html");
+ assert!(path.path == "/file_name.html".to_owned());
}
#[test]
fn test_url_with_dashes() {
- let urlstr = ~"http://dotcom.com/file-name.html";
+ let urlstr = "http://dotcom.com/file-name.html".to_owned();
let url = from_str(urlstr).unwrap();
- assert!(url.path == ~"/file-name.html");
+ assert!(url.path == "/file-name.html".to_owned());
}
#[test]
fn test_path_with_dashes() {
- let pathstr = ~"/file-name.html";
+ let pathstr = "/file-name.html".to_owned();
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == ~"/file-name.html");
+ assert!(path.path == "/file-name.html".to_owned());
}
#[test]
#[test]
fn test_full_url_parse_and_format() {
- let url = ~"http://user:pass@rust-lang.org/doc?s=v#something";
+ let url = "http://user:pass@rust-lang.org/doc?s=v#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_userless_url_parse_and_format() {
- let url = ~"http://rust-lang.org/doc?s=v#something";
+ let url = "http://rust-lang.org/doc?s=v#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_queryless_url_parse_and_format() {
- let url = ~"http://user:pass@rust-lang.org/doc#something";
+ let url = "http://user:pass@rust-lang.org/doc#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_empty_query_url_parse_and_format() {
- let url = ~"http://user:pass@rust-lang.org/doc?#something";
- let should_be = ~"http://user:pass@rust-lang.org/doc#something";
+ let url = "http://user:pass@rust-lang.org/doc?#something".to_owned();
+ let should_be = "http://user:pass@rust-lang.org/doc#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), should_be);
}
#[test]
fn test_fragmentless_url_parse_and_format() {
- let url = ~"http://user:pass@rust-lang.org/doc?q=v";
+ let url = "http://user:pass@rust-lang.org/doc?q=v".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_minimal_url_parse_and_format() {
- let url = ~"http://rust-lang.org/doc";
+ let url = "http://rust-lang.org/doc".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_url_with_port_parse_and_format() {
- let url = ~"http://rust-lang.org:80/doc";
+ let url = "http://rust-lang.org:80/doc".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_scheme_host_only_url_parse_and_format() {
- let url = ~"http://rust-lang.org";
+ let url = "http://rust-lang.org".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_pathless_url_parse_and_format() {
- let url = ~"http://user:pass@rust-lang.org?q=v#something";
+ let url = "http://user:pass@rust-lang.org?q=v#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_scheme_host_fragment_only_url_parse_and_format() {
- let url = ~"http://rust-lang.org#something";
+ let url = "http://rust-lang.org#something".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_url_component_encoding() {
- let url = ~"http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B";
+ let url = "http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B".to_owned();
let u = from_str(url).unwrap();
- assert!(u.path == ~"/doc uments");
- assert!(u.query == vec!((~"ba%d ", ~"#&+")));
+ assert!(u.path == "/doc uments".to_owned());
+ assert!(u.query == vec!(("ba%d ".to_owned(), "#&+".to_owned())));
}
#[test]
fn test_path_component_encoding() {
- let path = ~"/doc%20uments?ba%25d%20=%23%26%2B";
+ let path = "/doc%20uments?ba%25d%20=%23%26%2B".to_owned();
let p = path_from_str(path).unwrap();
- assert!(p.path == ~"/doc uments");
- assert!(p.query == vec!((~"ba%d ", ~"#&+")));
+ assert!(p.path == "/doc uments".to_owned());
+ assert!(p.query == vec!(("ba%d ".to_owned(), "#&+".to_owned())));
}
#[test]
fn test_url_without_authority() {
- let url = ~"mailto:test@email.com";
+ let url = "mailto:test@email.com".to_owned();
assert_eq!(from_str(url).unwrap().to_str(), url);
}
#[test]
fn test_encode() {
- assert_eq!(encode(""), ~"");
- assert_eq!(encode("http://example.com"), ~"http://example.com");
- assert_eq!(encode("foo bar% baz"), ~"foo%20bar%25%20baz");
- assert_eq!(encode(" "), ~"%20");
- assert_eq!(encode("!"), ~"!");
- assert_eq!(encode("\""), ~"\"");
- assert_eq!(encode("#"), ~"#");
- assert_eq!(encode("$"), ~"$");
- assert_eq!(encode("%"), ~"%25");
- assert_eq!(encode("&"), ~"&");
- assert_eq!(encode("'"), ~"%27");
- assert_eq!(encode("("), ~"(");
- assert_eq!(encode(")"), ~")");
- assert_eq!(encode("*"), ~"*");
- assert_eq!(encode("+"), ~"+");
- assert_eq!(encode(","), ~",");
- assert_eq!(encode("/"), ~"/");
- assert_eq!(encode(":"), ~":");
- assert_eq!(encode(";"), ~";");
- assert_eq!(encode("="), ~"=");
- assert_eq!(encode("?"), ~"?");
- assert_eq!(encode("@"), ~"@");
- assert_eq!(encode("["), ~"[");
- assert_eq!(encode("]"), ~"]");
+ assert_eq!(encode(""), "".to_owned());
+ assert_eq!(encode("http://example.com"), "http://example.com".to_owned());
+ assert_eq!(encode("foo bar% baz"), "foo%20bar%25%20baz".to_owned());
+ assert_eq!(encode(" "), "%20".to_owned());
+ assert_eq!(encode("!"), "!".to_owned());
+ assert_eq!(encode("\""), "\"".to_owned());
+ assert_eq!(encode("#"), "#".to_owned());
+ assert_eq!(encode("$"), "$".to_owned());
+ assert_eq!(encode("%"), "%25".to_owned());
+ assert_eq!(encode("&"), "&".to_owned());
+ assert_eq!(encode("'"), "%27".to_owned());
+ assert_eq!(encode("("), "(".to_owned());
+ assert_eq!(encode(")"), ")".to_owned());
+ assert_eq!(encode("*"), "*".to_owned());
+ assert_eq!(encode("+"), "+".to_owned());
+ assert_eq!(encode(","), ",".to_owned());
+ assert_eq!(encode("/"), "/".to_owned());
+ assert_eq!(encode(":"), ":".to_owned());
+ assert_eq!(encode(";"), ";".to_owned());
+ assert_eq!(encode("="), "=".to_owned());
+ assert_eq!(encode("?"), "?".to_owned());
+ assert_eq!(encode("@"), "@".to_owned());
+ assert_eq!(encode("["), "[".to_owned());
+ assert_eq!(encode("]"), "]".to_owned());
}
#[test]
fn test_encode_component() {
- assert_eq!(encode_component(""), ~"");
+ assert_eq!(encode_component(""), "".to_owned());
assert!(encode_component("http://example.com") ==
- ~"http%3A%2F%2Fexample.com");
+ "http%3A%2F%2Fexample.com".to_owned());
assert!(encode_component("foo bar% baz") ==
- ~"foo%20bar%25%20baz");
- assert_eq!(encode_component(" "), ~"%20");
- assert_eq!(encode_component("!"), ~"%21");
- assert_eq!(encode_component("#"), ~"%23");
- assert_eq!(encode_component("$"), ~"%24");
- assert_eq!(encode_component("%"), ~"%25");
- assert_eq!(encode_component("&"), ~"%26");
- assert_eq!(encode_component("'"), ~"%27");
- assert_eq!(encode_component("("), ~"%28");
- assert_eq!(encode_component(")"), ~"%29");
- assert_eq!(encode_component("*"), ~"%2A");
- assert_eq!(encode_component("+"), ~"%2B");
- assert_eq!(encode_component(","), ~"%2C");
- assert_eq!(encode_component("/"), ~"%2F");
- assert_eq!(encode_component(":"), ~"%3A");
- assert_eq!(encode_component(";"), ~"%3B");
- assert_eq!(encode_component("="), ~"%3D");
- assert_eq!(encode_component("?"), ~"%3F");
- assert_eq!(encode_component("@"), ~"%40");
- assert_eq!(encode_component("["), ~"%5B");
- assert_eq!(encode_component("]"), ~"%5D");
+ "foo%20bar%25%20baz".to_owned());
+ assert_eq!(encode_component(" "), "%20".to_owned());
+ assert_eq!(encode_component("!"), "%21".to_owned());
+ assert_eq!(encode_component("#"), "%23".to_owned());
+ assert_eq!(encode_component("$"), "%24".to_owned());
+ assert_eq!(encode_component("%"), "%25".to_owned());
+ assert_eq!(encode_component("&"), "%26".to_owned());
+ assert_eq!(encode_component("'"), "%27".to_owned());
+ assert_eq!(encode_component("("), "%28".to_owned());
+ assert_eq!(encode_component(")"), "%29".to_owned());
+ assert_eq!(encode_component("*"), "%2A".to_owned());
+ assert_eq!(encode_component("+"), "%2B".to_owned());
+ assert_eq!(encode_component(","), "%2C".to_owned());
+ assert_eq!(encode_component("/"), "%2F".to_owned());
+ assert_eq!(encode_component(":"), "%3A".to_owned());
+ assert_eq!(encode_component(";"), "%3B".to_owned());
+ assert_eq!(encode_component("="), "%3D".to_owned());
+ assert_eq!(encode_component("?"), "%3F".to_owned());
+ assert_eq!(encode_component("@"), "%40".to_owned());
+ assert_eq!(encode_component("["), "%5B".to_owned());
+ assert_eq!(encode_component("]"), "%5D".to_owned());
}
#[test]
fn test_decode() {
- assert_eq!(decode(""), ~"");
- assert_eq!(decode("abc/def 123"), ~"abc/def 123");
- assert_eq!(decode("abc%2Fdef%20123"), ~"abc%2Fdef 123");
- assert_eq!(decode("%20"), ~" ");
- assert_eq!(decode("%21"), ~"%21");
- assert_eq!(decode("%22"), ~"%22");
- assert_eq!(decode("%23"), ~"%23");
- assert_eq!(decode("%24"), ~"%24");
- assert_eq!(decode("%25"), ~"%");
- assert_eq!(decode("%26"), ~"%26");
- assert_eq!(decode("%27"), ~"'");
- assert_eq!(decode("%28"), ~"%28");
- assert_eq!(decode("%29"), ~"%29");
- assert_eq!(decode("%2A"), ~"%2A");
- assert_eq!(decode("%2B"), ~"%2B");
- assert_eq!(decode("%2C"), ~"%2C");
- assert_eq!(decode("%2F"), ~"%2F");
- assert_eq!(decode("%3A"), ~"%3A");
- assert_eq!(decode("%3B"), ~"%3B");
- assert_eq!(decode("%3D"), ~"%3D");
- assert_eq!(decode("%3F"), ~"%3F");
- assert_eq!(decode("%40"), ~"%40");
- assert_eq!(decode("%5B"), ~"%5B");
- assert_eq!(decode("%5D"), ~"%5D");
+ assert_eq!(decode(""), "".to_owned());
+ assert_eq!(decode("abc/def 123"), "abc/def 123".to_owned());
+ assert_eq!(decode("abc%2Fdef%20123"), "abc%2Fdef 123".to_owned());
+ assert_eq!(decode("%20"), " ".to_owned());
+ assert_eq!(decode("%21"), "%21".to_owned());
+ assert_eq!(decode("%22"), "%22".to_owned());
+ assert_eq!(decode("%23"), "%23".to_owned());
+ assert_eq!(decode("%24"), "%24".to_owned());
+ assert_eq!(decode("%25"), "%".to_owned());
+ assert_eq!(decode("%26"), "%26".to_owned());
+ assert_eq!(decode("%27"), "'".to_owned());
+ assert_eq!(decode("%28"), "%28".to_owned());
+ assert_eq!(decode("%29"), "%29".to_owned());
+ assert_eq!(decode("%2A"), "%2A".to_owned());
+ assert_eq!(decode("%2B"), "%2B".to_owned());
+ assert_eq!(decode("%2C"), "%2C".to_owned());
+ assert_eq!(decode("%2F"), "%2F".to_owned());
+ assert_eq!(decode("%3A"), "%3A".to_owned());
+ assert_eq!(decode("%3B"), "%3B".to_owned());
+ assert_eq!(decode("%3D"), "%3D".to_owned());
+ assert_eq!(decode("%3F"), "%3F".to_owned());
+ assert_eq!(decode("%40"), "%40".to_owned());
+ assert_eq!(decode("%5B"), "%5B".to_owned());
+ assert_eq!(decode("%5D"), "%5D".to_owned());
}
#[test]
fn test_decode_component() {
- assert_eq!(decode_component(""), ~"");
- assert_eq!(decode_component("abc/def 123"), ~"abc/def 123");
- assert_eq!(decode_component("abc%2Fdef%20123"), ~"abc/def 123");
- assert_eq!(decode_component("%20"), ~" ");
- assert_eq!(decode_component("%21"), ~"!");
- assert_eq!(decode_component("%22"), ~"\"");
- assert_eq!(decode_component("%23"), ~"#");
- assert_eq!(decode_component("%24"), ~"$");
- assert_eq!(decode_component("%25"), ~"%");
- assert_eq!(decode_component("%26"), ~"&");
- assert_eq!(decode_component("%27"), ~"'");
- assert_eq!(decode_component("%28"), ~"(");
- assert_eq!(decode_component("%29"), ~")");
- assert_eq!(decode_component("%2A"), ~"*");
- assert_eq!(decode_component("%2B"), ~"+");
- assert_eq!(decode_component("%2C"), ~",");
- assert_eq!(decode_component("%2F"), ~"/");
- assert_eq!(decode_component("%3A"), ~":");
- assert_eq!(decode_component("%3B"), ~";");
- assert_eq!(decode_component("%3D"), ~"=");
- assert_eq!(decode_component("%3F"), ~"?");
- assert_eq!(decode_component("%40"), ~"@");
- assert_eq!(decode_component("%5B"), ~"[");
- assert_eq!(decode_component("%5D"), ~"]");
+ assert_eq!(decode_component(""), "".to_owned());
+ assert_eq!(decode_component("abc/def 123"), "abc/def 123".to_owned());
+ assert_eq!(decode_component("abc%2Fdef%20123"), "abc/def 123".to_owned());
+ assert_eq!(decode_component("%20"), " ".to_owned());
+ assert_eq!(decode_component("%21"), "!".to_owned());
+ assert_eq!(decode_component("%22"), "\"".to_owned());
+ assert_eq!(decode_component("%23"), "#".to_owned());
+ assert_eq!(decode_component("%24"), "$".to_owned());
+ assert_eq!(decode_component("%25"), "%".to_owned());
+ assert_eq!(decode_component("%26"), "&".to_owned());
+ assert_eq!(decode_component("%27"), "'".to_owned());
+ assert_eq!(decode_component("%28"), "(".to_owned());
+ assert_eq!(decode_component("%29"), ")".to_owned());
+ assert_eq!(decode_component("%2A"), "*".to_owned());
+ assert_eq!(decode_component("%2B"), "+".to_owned());
+ assert_eq!(decode_component("%2C"), ",".to_owned());
+ assert_eq!(decode_component("%2F"), "/".to_owned());
+ assert_eq!(decode_component("%3A"), ":".to_owned());
+ assert_eq!(decode_component("%3B"), ";".to_owned());
+ assert_eq!(decode_component("%3D"), "=".to_owned());
+ assert_eq!(decode_component("%3F"), "?".to_owned());
+ assert_eq!(decode_component("%40"), "@".to_owned());
+ assert_eq!(decode_component("%5B"), "[".to_owned());
+ assert_eq!(decode_component("%5D"), "]".to_owned());
}
#[test]
fn test_encode_form_urlencoded() {
let mut m = HashMap::new();
- assert_eq!(encode_form_urlencoded(&m), ~"");
+ assert_eq!(encode_form_urlencoded(&m), "".to_owned());
- m.insert(~"", vec!());
- m.insert(~"foo", vec!());
- assert_eq!(encode_form_urlencoded(&m), ~"");
+ m.insert("".to_owned(), vec!());
+ m.insert("foo".to_owned(), vec!());
+ assert_eq!(encode_form_urlencoded(&m), "".to_owned());
let mut m = HashMap::new();
- m.insert(~"foo", vec!(~"bar", ~"123"));
- assert_eq!(encode_form_urlencoded(&m), ~"foo=bar&foo=123");
+ m.insert("foo".to_owned(), vec!("bar".to_owned(), "123".to_owned()));
+ assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_owned());
let mut m = HashMap::new();
- m.insert(~"foo bar", vec!(~"abc", ~"12 = 34"));
+ m.insert("foo bar".to_owned(), vec!("abc".to_owned(), "12 = 34".to_owned()));
assert!(encode_form_urlencoded(&m) ==
- ~"foo+bar=abc&foo+bar=12+%3D+34");
+ "foo+bar=abc&foo+bar=12+%3D+34".to_owned());
}
#[test]
let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes();
let form = decode_form_urlencoded(s);
assert_eq!(form.len(), 2);
- assert_eq!(form.get(&~"a"), &vec!(~"1"));
- assert_eq!(form.get(&~"foo bar"), &vec!(~"abc", ~"12 = 34"));
+ assert_eq!(form.get(&"a".to_owned()), &vec!("1".to_owned()));
+ assert_eq!(form.get(&"foo bar".to_owned()), &vec!("abc".to_owned(), "12 = 34".to_owned()));
}
}
let u = Uuid::from_fields(d1, d2, d3, d4.as_slice());
- let expected = ~"a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
+ let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_owned();
let result = u.to_simple_str();
assert!(result == expected);
}
0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 );
let u = Uuid::from_bytes(b.as_slice()).unwrap();
- let expected = ~"a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
+ let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_owned();
assert!(u.to_simple_str() == expected);
}
return pth;
}
- let pth = make_path(~"foo.c");
+ let pth = make_path("foo.c".to_owned());
File::create(&pth).write(bytes!("int main() { return 0; }")).unwrap();
- let db_path = make_path(~"db.json");
+ let db_path = make_path("db.json".to_owned());
let cx = Context::new(Arc::new(RWLock::new(Database::new(db_path))),
Arc::new(TreeMap::new()));
// FIXME (#9639): This needs to handle non-utf8 paths
prep.declare_input("file", pth.as_str().unwrap(), file_content);
prep.exec(proc(_exe) {
- let out = make_path(~"foo.o");
+ let out = make_path("foo.o".to_owned());
let compiler = if cfg!(windows) {"gcc"} else {"cc"};
// FIXME (#9639): This needs to handle non-utf8 paths
Process::status(compiler, [pth.as_str().unwrap().to_owned(),
- ~"-o",
+ "-o".to_owned(),
out.as_str().unwrap().to_owned()]).unwrap();
let _proof_of_concept = subcx.prep("subfn");
The new parser will be smaller, faster, safer and most importantly, more consistent.
-Please stay tuned.
\ No newline at end of file
+Please stay tuned.
pub struct NameVal { pub name: ~str, pub val: int }
pub fn struct_nameval() -> NameVal {
- NameVal { name: ~"crateresolve5", val: 10 }
+ NameVal { name: "crateresolve5".to_owned(), val: 10 }
}
pub enum e {
pub struct NameVal { pub name: ~str, pub val: int }
pub fn struct_nameval() -> NameVal {
- NameVal { name: ~"crateresolve5", val: 10 }
+ NameVal { name: "crateresolve5".to_owned(), val: 10 }
}
pub enum e {
// the unused ty param is necessary so this gets monomorphized
pub fn request<T>(req: &header_map) {
- let _x = (**((**req.get(&~"METHOD")).clone()).borrow().clone().get(0)).clone();
+ let _x = (**((**req.get(&"METHOD".to_owned())).clone()).borrow().clone().get(0)).clone();
}
pub static THREE: P = P { p: 3 };
}
-pub static A: S = S { p: private::THREE };
\ No newline at end of file
+pub static A: S = S { p: private::THREE };
impl Bort {
pub fn bort() -> ~str {
- ~"bort()"
+ "bort()".to_owned()
}
}
}
if os::getenv("RUST_BENCH").is_some() {
run_test = true
} else if argv.len() > 0 {
- run_test = argv.iter().any(|x| x == &~"all") || argv.iter().any(|x| x == &name)
+ run_test = argv.iter().any(|x| x == &"all".to_owned()) || argv.iter().any(|x| x == &name)
}
if !run_test {
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"10000000")
+ vec!("".to_owned(), "10000000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"100000")
+ vec!("".to_owned(), "100000".to_owned())
} else {
args.move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"1000000", ~"10000")
+ vec!("".to_owned(), "1000000".to_owned(), "10000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10000", ~"4")
+ vec!("".to_owned(), "10000".to_owned(), "4".to_owned())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"1000000", ~"8")
+ vec!("".to_owned(), "1000000".to_owned(), "8".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10000", ~"4")
+ vec!("".to_owned(), "10000".to_owned(), "4".to_owned())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"100", ~"10000")
+ vec!("".to_owned(), "100".to_owned(), "10000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10", ~"100")
+ vec!("".to_owned(), "10".to_owned(), "100".to_owned())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"100", ~"10000")
+ vec!("".to_owned(), "100".to_owned(), "10000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10", ~"100")
+ vec!("".to_owned(), "10".to_owned(), "100".to_owned())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"12")
+ vec!("".to_owned(), "12".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"8")
+ vec!("".to_owned(), "8".to_owned())
} else {
args.move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"200000")
+ vec!("".to_owned(), "200000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"600")
+ vec!("".to_owned(), "600".to_owned())
} else {
args.move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"40")
+ vec!("".to_owned(), "40".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"30")
+ vec!("".to_owned(), "30".to_owned())
} else {
args.move_iter().collect()
};
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
- 3u => { format!("{}\t{}", find(&freqs, ~"GGT"), "GGT") }
- 4u => { format!("{}\t{}", find(&freqs, ~"GGTA"), "GGTA") }
- 6u => { format!("{}\t{}", find(&freqs, ~"GGTATT"), "GGTATT") }
- 12u => { format!("{}\t{}", find(&freqs, ~"GGTATTTTAATT"), "GGTATTTTAATT") }
- 18u => { format!("{}\t{}", find(&freqs, ~"GGTATTTTAATTTATAGT"), "GGTATTTTAATTTATAGT") }
- _ => { ~"" }
+ 3u => { format!("{}\t{}", find(&freqs, "GGT".to_owned()), "GGT") }
+ 4u => { format!("{}\t{}", find(&freqs, "GGTA".to_owned()), "GGTA") }
+ 6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_owned()), "GGTATT") }
+ 12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_owned()), "GGTATTTTAATT") }
+ 18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_owned()),
+ "GGTATTTTAATTTATAGT") }
+ _ => { "".to_owned() }
};
to_parent.send(buffer);
};
let masks = make_masks();
let masks = filter_masks(masks.as_slice());
- let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
+ let mut data = Data {stop_after: stop_after, nb: 0, min: "".to_owned(), max: "".to_owned()};
search(masks.as_slice(), 0, 0, Nil, &mut data);
println!("{} solutions found", data.nb);
print_sol(data.min);
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"1000")
+ vec!("".to_owned(), "1000".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"1000")
+ vec!("".to_owned(), "1000".to_owned())
} else {
args.move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"20")
+ vec!("".to_owned(), "20".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"8")
+ vec!("".to_owned(), "8".to_owned())
} else {
args.move_iter().collect()
};
use std::from_str::FromStr;
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"2000000", ~"503")
+ vec!("".to_owned(), "2000000".to_owned(), "503".to_owned())
} else {
os::args().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"100000", ~"100")
+ vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10000", ~"50")
+ vec!("".to_owned(), "10000".to_owned(), "50".to_owned())
} else {
args.move_iter().collect()
};
}
pub fn read(mut reader: BufferedReader<StdReader>) -> Sudoku {
- assert!(reader.read_line().unwrap() == ~"9,9"); /* assert first line is exactly "9,9" */
+ /* assert first line is exactly "9,9" */
+ assert!(reader.read_line().unwrap() == "9,9".to_owned());
let mut g = Vec::from_fn(10u, { |_i| vec!(0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8) });
for line in reader.lines() {
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"100000")
+ vec!("".to_owned(), "100000".to_owned())
} else if args.len() <= 1 {
- vec!(~"", ~"100")
+ vec!("".to_owned(), "100".to_owned())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"30")
+ vec!("".to_owned(), "30".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10")
+ vec!("".to_owned(), "10".to_owned())
} else {
args
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!(~"", ~"400")
+ vec!("".to_owned(), "400".to_owned())
} else if args.len() <= 1u {
- vec!(~"", ~"10")
+ vec!("".to_owned(), "10".to_owned())
} else {
args.move_iter().collect()
};
// error-pattern:`^` cannot be applied to type `~str`
-fn main() { let x = ~"a" ^ ~"b"; }
+fn main() { let x = "a".to_owned() ^ "b".to_owned(); }
}
fn let_pat() {
- let &_x = &~"hi";
+ let &_x = &"hi".to_owned();
//~^ ERROR cannot move out of dereference of `&`-pointer
}
use std::rc::Rc;
pub fn main() {
- let _x = *Rc::new(~"hi");
+ let _x = *Rc::new("hi".to_owned());
//~^ ERROR cannot move out of dereference of `&`-pointer
}
}
fn move_in_match() {
- match S {f:~"foo"} {
+ match S {f:"foo".to_owned()} {
S {f:_s} => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
- let S {f:_s} = S {f:~"foo"};
+ let S {f:_s} = S {f:"foo".to_owned()};
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_match() {
- match S(~"foo") {
+ match S("foo".to_owned()) {
S(_s) => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
- let S(_s) = S(~"foo");
+ let S(_s) = S("foo".to_owned());
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
pub fn main() {
let x = vec!(
- Foo { string: ~"foo" },
- Foo { string: ~"bar" },
- Foo { string: ~"baz" }
+ Foo { string: "foo".to_owned() },
+ Foo { string: "bar".to_owned() },
+ Foo { string: "baz".to_owned() }
);
let x: &[Foo] = x.as_slice();
match x {
fn main() {
let msg;
- match Some(~"Hello") {
+ match Some("Hello".to_owned()) {
Some(ref m) => { //~ ERROR borrowed value does not live long enough
msg = m;
},
fn f(x: ~str) {}
fn main() {
- let s = S { x: Bar(~"hello") };
+ let s = S { x: Bar("hello".to_owned()) };
match &s.x {
&Foo => {}
&Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
static STATIC10: UnsafeStruct = UnsafeStruct;
//~^ ERROR static items are not allowed to have destructor
-static STATIC11: ~str = ~"Owned pointers are not allowed either";
+struct MyOwned;
+
+static STATIC11: ~MyOwned = ~MyOwned;
//~^ ERROR static items are not allowed to have owned pointers
// The following examples test that mutable structs are just forbidden
static mut STATIC13: SafeStruct = SafeStruct{field1: Variant1, field2: Variant3(WithDtor)};
//~^ ERROR mutable static items are not allowed to have destructors
-static mut STATIC14: SafeStruct = SafeStruct{field1: Variant1, field2: Variant4(~"str")};
+static mut STATIC14: SafeStruct = SafeStruct{field1: Variant1, field2: Variant4("str".to_owned())};
//~^ ERROR mutable static items are not allowed to have destructors
-static STATIC15: &'static [~str] = &'static [~"str", ~"str"];
+static STATIC15: &'static [~MyOwned] = &'static [~MyOwned, ~MyOwned];
//~^ ERROR static items are not allowed to have owned pointers
//~^^ ERROR static items are not allowed to have owned pointers
-static STATIC16: (~str, ~str) = (~"str", ~"str");
+static STATIC16: (&'static ~MyOwned, &'static ~MyOwned) = (&'static ~MyOwned, &'static ~MyOwned);
//~^ ERROR static items are not allowed to have owned pointers
//~^^ ERROR static items are not allowed to have owned pointers
mod circular_modules_hello; //~ERROR: circular modules
pub fn hi_str() -> ~str {
- ~"Hi!"
+ "Hi!".to_owned()
}
fn main() {
}
fn main() {
- let nyan: ~noisy = ~cat(0, 2, ~"nyan") as ~noisy;
+ let nyan: ~noisy = ~cat(0, 2, "nyan".to_owned()) as ~noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
}
fn main() {
- let x = X { x: ~"hello" };
+ let x = X { x: "hello".to_owned() };
let y = unwrap(x);
println!("contents: {}", y);
}
}
fn main() {
- let x = X { x: ~"hello" };
+ let x = X { x: "hello".to_owned() };
match x {
X { x: y } => println!("contents: {}", y)
pub fn main() {
let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5);
- let s: ~str = ~"abcdef";
+ let s: ~str = "abcdef".to_owned();
assert_eq!(v.as_slice()[3u], 3);
assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types
assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types
fn main() {
println!("hello");
- let x = ~"foo";
+ let x = "foo".to_owned();
let y = x;
println!("{}", y);
}
// the compiler to attempt autoderef and then
// try to resolve the method.
impl to_str_2 for t {
- fn my_to_str() -> ~str { ~"t" }
+ fn my_to_str() -> ~str { "t".to_owned() }
}
fn new_t(x: t) {
// except according to those terms.
fn foo(b: bool) -> Result<bool,~str> {
- Err(~"bar"); //~ ERROR: cannot determine a type for this expression: unconstrained type
+ Err("bar".to_owned());
+ //~^ ERROR: cannot determine a type for this expression: unconstrained type
}
fn main() {
fn new(s: &str) -> CrateId {
CrateId {
local_path: s.to_owned(),
- junk: ~"wutevs"
+ junk: "wutevs".to_owned()
}
}
}
~2; //~ ERROR type uses owned
fn g(_: ~Clone) {} //~ ERROR type uses owned
- ~""; //~ ERROR type uses owned
- //~^ ERROR type uses owned
+ "".to_owned(); //~ ERROR type uses owned
proc() {}; //~ ERROR type uses owned
}
// except according to those terms.
fn main() {
- match ~"foo" {
+ match "foo".to_owned() {
['f', 'o', ..] => { } //~ ERROR mismatched types: expected `~str` but found a vector pattern
_ => { }
}
_ => ()
}
- let x: Vec<~str> = vec!(~"foo", ~"bar", ~"baz");
+ let x: Vec<~str> = vec!("foo".to_owned(), "bar".to_owned(), "baz".to_owned());
let x: &[~str] = x.as_slice();
match x {
[a, _, _, ..] => { println!("{}", a); }
// error-pattern:cannot apply unary operator `-` to type `~str`
-fn main() { -~"foo"; }
+fn main() { -"foo".to_owned(); }
fn touch<A>(_a: &A) {}
fn f10() {
- let x = Foo { f: ~"hi", y: 3 };
+ let x = Foo { f: "hi".to_owned(), y: 3 };
consume(x.f);
touch(&x.y); //~ ERROR use of partially moved value: `x`
}
fn f20() {
- let x = vec!(~"hi");
+ let x = vec!("hi".to_owned());
consume(x.move_iter().next().unwrap());
touch(x.get(0)); //~ ERROR use of moved value: `x`
}
use std::task;
fn main() {
- let x = ~"Hello world!";
+ let x = "Hello world!".to_owned();
task::spawn(proc() {
println!("{}", x);
});
fn touch<A>(_a: &A) {}
fn f00() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:x }; //~ NOTE `x` moved here
touch(&x); //~ ERROR use of moved value: `x`
}
fn f05() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:(((x))) }; //~ NOTE `x` moved here
touch(&x); //~ ERROR use of moved value: `x`
}
fn f10() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:x.clone() };
touch(&x);
}
fn f20() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:(x).clone() };
touch(&x);
}
fn f30() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:((x)).clone() };
touch(&x);
}
fn f40() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:(((((((x)).clone()))))) };
touch(&x);
}
fn touch<A>(_a: &A) {}
fn f10() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = (x, 3);
touch(&x); //~ ERROR use of moved value: `x`
}
}
fn f30(cond: bool) {
- let x = ~"hi";
- let y = ~"ho";
+ let x = "hi".to_owned();
+ let y = "ho".to_owned();
let _y = if cond {
x
} else {
}
fn f40(cond: bool) {
- let x = ~"hi";
- let y = ~"ho";
+ let x = "hi".to_owned();
+ let y = "ho".to_owned();
let _y = match cond {
true => x,
false => y
}
fn f50(cond: bool) {
- let x = ~"hi";
- let y = ~"ho";
+ let x = "hi".to_owned();
+ let y = "ho".to_owned();
let _y = match cond {
_ if guard(x) => 10,
true => 10,
}
fn f70() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
- let x = ~"hi";
+ let x = "hi".to_owned();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
- let x = vec!(~"hi");
+ let x = vec!("hi".to_owned());
let _y = x.move_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
- let x = vec!(~"hi");
+ let x = vec!("hi".to_owned());
let _y = [x.move_iter().next().unwrap(), ..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
- let mut x = vec!(~"hi", ~"ho");
+ let mut x = vec!("hi".to_owned(), "ho".to_owned());
x.as_mut_slice().swap(0, 1);
touch(x.get(0));
touch(x.get(1));
fn touch<A>(_a: &A) {}
fn f10() {
- let x = Foo {f: ~"hi"};
+ let x = Foo {f: "hi".to_owned()};
let y = match x {
Foo {f} => {} //~ NOTE moved here
}
fn innocent_looking_victim() {
- let mut x = Some(~"hello");
+ let mut x = Some("hello".to_owned());
conspirator(|f, writer| {
if writer {
x = None;
impl Cmp, ToStr for S { //~ ERROR: expected `{` but found `,`
fn eq(&&other: S) { false }
- fn to_str(&self) -> ~str { ~"hi" }
+ fn to_str(&self) -> ~str { "hi".to_owned() }
}
}
fn main () {
- let f : argparse::Flag = argparse::flag(~"flag", ~"My flag");
- let updated_flag = f.set_desc(~"My new flag");
+ 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");
}
#![feature(concat_idents)]
pub fn main() {
- let asdf_fdsa = ~"<.<";
- assert_eq!(concat_idents!(asd, f_f, dsa), ~"<.<");
+ let asdf_fdsa = "<.<".to_owned();
+ assert_eq!(concat_idents!(asd, f_f, dsa), "<.<".to_owned());
//~^ ERROR: unresolved name `asdf_fdsa`
assert!(stringify!(use_mention_distinction) ==
}
fn main() {
- let person = ~"Fred";
+ let person = "Fred".to_owned();
let person: &str = person; //~ ERROR `person[..]` does not live long enough
let s: ~Trait<&'static str> = ~Struct { person: person };
}
// except according to those terms.
fn main() {
- let mut s = ~"test";
+ let mut s = "test".to_owned();
s[0] = 3; //~ ERROR: not allowed
s[0] += 3; //~ ERROR: not allowed
{
}
fn main() {
- let cat = ~"kitty";
+ let cat = "kitty".to_owned();
let (tx, _) = channel(); //~ ERROR does not fulfill `Send`
tx.send(foo(42, @(cat))); //~ ERROR does not fulfill `Send`
}
// except according to those terms.
fn main() {
- let x = ~"Hello!";
+ let x = "Hello!".to_owned();
let _y = x;
println!("{}", x); //~ ERROR use of moved value
}
zzz();
}
-fn zzz() {()}
\ No newline at end of file
+fn zzz() {()}
let _y =
match x {
Some(_) =>
- ~"some" + "very" + "very" + "very" + "very" + "very" + "very" +
- "very" + "very" + "long" + "string",
- None => ~"none"
+ "some".to_owned() + "very" + "very" + "very" + "very" + "very" +
+ "very" + "very" + "very" + "long" + "string",
+ None => "none".to_owned()
};
}
let x = Some(3);
let _y =
match x {
- Some(_) => [~"some(_)", ~"not", ~"SO", ~"long", ~"string"],
- None => [~"none", ~"a", ~"a", ~"a", ~"a"]
+ Some(_) =>
+ ["some(_)".to_owned(), "not".to_owned(), "SO".to_owned(),
+ "long".to_owned(), "string".to_owned()],
+ None =>
+ ["none".to_owned(), "a".to_owned(), "a".to_owned(),
+ "a".to_owned(), "a".to_owned()]
};
}
fn main() {
let x = Some(3);
- let _y = match x { Some(_) => ~"some(_)", None => ~"none" };
+ let _y =
+ match x {
+ Some(_) => "some(_)".to_owned(),
+ None => "none".to_owned()
+ };
}
// error-pattern:failed at 'test-assert-owned'
fn main() {
- assert!(false, ~"test-assert-owned");
+ assert!(false, "test-assert-owned".to_owned());
}
// error-pattern:quux
fn my_err(s: ~str) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { 3u == my_err(~"bye"); }
+fn main() { 3u == my_err("bye".to_owned()); }
// error-pattern:quux
fn my_err(s: ~str) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { 3u == my_err(~"bye"); }
+fn main() { 3u == my_err("bye".to_owned()); }
fn main() {
let mut a = 1;
if 1 == 1 { a = 2; }
- fail!(~"woooo" + "o");
+ fail!("woooo".to_owned() + "o");
}
use std::task;
fn main() {
- task::task().named(~"owned name").try(proc() {
+ task::task().named("owned name".to_owned()).try(proc() {
fail!("test");
1
}).unwrap()
// error-pattern:meh
-fn main() { let str_var: ~str = ~"meh"; fail!("{}", str_var); }
+fn main() { let str_var: ~str = "meh".to_owned(); fail!("{}", str_var); }
// error-pattern:quux
fn my_err(s: ~str) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { if my_err(~"bye") { } }
+fn main() { if my_err("bye".to_owned()) { } }
let y = vec!(3);
fail!("so long");
x.push_all_move(y);
- ~"good" + ~"bye";
+ "good".to_owned() + "bye".to_owned();
}
use std::result;
fn main() {
- println!("{:?}", result::Err::<int,~str>(~"kitty").unwrap());
+ println!("{:?}", result::Err::<int,~str>("kitty".to_owned()).unwrap());
}
// error-pattern:index out of bounds: the len is 5 but the index is 5
fn main() {
- let s: ~str = ~"hello";
+ let s: ~str = "hello".to_owned();
// Bounds-check failure.
assert_eq!(s[5], 0x0 as u8);
}
fn main() {
- let x = @~"hi";
+ let x = @"hi".to_owned();
failfn();
println!("{:?}", x);
}
// error-pattern:fail
fn main() {
- let cheese = ~"roquefort";
- let carrots = @~"crunchy";
+ let cheese = "roquefort".to_owned();
+ let carrots = @"crunchy".to_owned();
let result: |@~str, |~str||: 'static = (|tasties, macerate| {
macerate((*tasties).clone());
@0;
}
fn test_str() {
- let res = match false { true => { ~"happy" },
+ let res = match false { true => { "happy".to_owned() },
_ => fail!("non-exhaustive match failure") };
- assert_eq!(res, ~"happy");
+ assert_eq!(res, "happy".to_owned());
}
fn main() {
test_box();
let mut map = collections::HashMap::new();
let mut arr = Vec::new();
for _i in range(0u, 10u) {
- arr.push(@~"key stuff");
+ arr.push(@"key stuff".to_owned());
map.insert(arr.clone(),
- arr.clone().append([@~"value stuff"]));
+ arr.clone().append([@"value stuff".to_owned()]));
if arr.len() == 5 {
fail!();
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
- let result = Process::output("sh", [~"-c", rustc + " " + main_file_str]).unwrap();
+ let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
- let result = Process::output("sh", [~"-c", rustc + " " + main_file_str]).unwrap();
+ let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
- check_pp(ext_cx, abc, pprust::print_expr, ~"23");
+ check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
let ty = quote_ty!(cx, int);
- check_pp(ext_cx, ty, pprust::print_type, ~"int");
+ check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
let item = quote_item!(cx, static x : int = 10;).get();
- check_pp(ext_cx, item, pprust::print_item, ~"static x: int = 10;");
+ check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
let stmt = quote_stmt!(cx, let x = 20;);
- check_pp(ext_cx, *stmt, pprust::print_stmt, ~"let x = 20;");
+ check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
let pat = quote_pat!(cx, Some(_));
- check_pp(ext_cx, pat, pprust::print_pat, ~"Some(_)");
+ check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
}
pp::eof(pp.s);
});
stdout().write_line(s);
- if expect != ~"" {
+ if expect != "".to_owned() {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
}
pub fn main() {
assert_eq!(14,14);
- assert_eq!(~"abc",~"abc");
+ assert_eq!("abc".to_owned(),"abc".to_owned());
assert_eq!(~Point{x:34},~Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(@Point{x:34},@Point{x:34});
(vec!(1)).as_slice().test_imm();
(&[1]).test_imm();
("test").test_imm();
- (~"test").test_imm();
+ ("test".to_owned()).test_imm();
(&"test").test_imm();
// FIXME: Other types of mutable vecs don't currently exist
pub fn main() {
assert_eq!(g(f), 1);
let f1: |Vec<~str> | -> ~str = f;
- assert_eq!(f1(vec!(~"x", ~"y", ~"z")), ~"x");
+ assert_eq!(f1(vec!("x".to_owned(), "y".to_owned(), "z".to_owned())), "x".to_owned());
}
pub fn main() {
let x = @3u;
- assert_eq!(x.foo(), ~"@3");
+ assert_eq!(x.foo(), "@3".to_owned());
}
Some(i) => { env.remove(i); }
None => {}
}
- env.push((~"RUST_BACKTRACE", ~"1"));
+ env.push(("RUST_BACKTRACE".to_owned(), "1".to_owned()));
// Make sure that the stack trace is printed
let mut p = Process::configure(ProcessConfig {
program: me,
- args: [~"fail"],
+ args: ["fail".to_owned()],
env: Some(env.as_slice()),
.. ProcessConfig::new()
}).unwrap();
// Make sure the stack trace is *not* printed
let mut p = Process::configure(ProcessConfig {
program: me,
- args: [~"fail"],
+ args: ["fail".to_owned()],
.. ProcessConfig::new()
}).unwrap();
let out = p.wait_with_output();
// Make sure a stack trace is printed
let mut p = Process::configure(ProcessConfig {
program: me,
- args: [~"double-fail"],
+ args: ["double-fail".to_owned()],
.. ProcessConfig::new()
}).unwrap();
let out = p.wait_with_output();
// Make sure a stack trace isn't printed too many times
let mut p = Process::configure(ProcessConfig {
program: me,
- args: [~"double-fail"],
+ args: ["double-fail".to_owned()],
env: Some(env.as_slice()),
.. ProcessConfig::new()
}).unwrap();
pub fn main() {
fn as_buf<T>(s: ~str, f: |~str| -> T) -> T { f(s) }
- as_buf(~"foo", |foo: ~str| -> () println!("{}", foo) );
+ as_buf("foo".to_owned(), |foo: ~str| -> () println!("{}", foo) );
}
}
pub fn main() {
- assert!(foo(&~"kitty"));
- assert!(!foo(&~"gata"));
+ assert!(foo(&"kitty".to_owned()));
+ assert!(!foo(&"gata".to_owned()));
}
pub fn main() {
assert!((@1 < @3));
- assert!((@@~"hello " > @@~"hello"));
- assert!((@@@~"hello" != @@@~"there"));
+ assert!((@@"hello ".to_owned() > @@"hello".to_owned()));
+ assert!((@@@"hello".to_owned() != @@@"there".to_owned()));
}
fn say(&self, s:&str) -> ~str {
match *self {
None => format!("{} - none", s),
- Some(ref x) => { ~"something!" + x.say(s) }
+ Some(ref x) => { "something!".to_owned() + x.say(s) }
}
}
}
pub fn main() {
- assert_eq!(3.hi(), ~"hello: 3");
- assert_eq!(Some(Some(3)).hi(), ~"something!something!hello: 3");
- assert_eq!(None::<int>.hi(), ~"hello - none");
+ assert_eq!(3.hi(), "hello: 3".to_owned());
+ assert_eq!(Some(Some(3)).hi(), "something!something!hello: 3".to_owned());
+ assert_eq!(None::<int>.hi(), "hello - none".to_owned());
- assert_eq!(Some(None::<int>).hi(), ~"something!hello - none");
- assert_eq!(Some(3).hi(), ~"something!hello: 3");
+ assert_eq!(Some(None::<int>).hi(), "something!hello - none".to_owned());
+ assert_eq!(Some(3).hi(), "something!hello: 3".to_owned());
}
}
pub fn main() {
- assert_eq!(atol(~"1024") * 10, atol(~"10240"));
- assert!((atoll(~"11111111111111111") * 10) == atoll(~"111111111111111110"));
+ assert_eq!(atol("1024".to_owned()) * 10, atol("10240".to_owned()));
+ assert!((atoll("11111111111111111".to_owned()) * 10) == atoll("111111111111111110".to_owned()));
}
debug!("debug");
info!("info");
});
- assert_eq!(r.read_to_str().unwrap(), ~"info\n");
+ assert_eq!(r.read_to_str().unwrap(), "info\n".to_owned());
}
pub fn main() {
let lst = new_int_alist();
- alist_add(&lst, 22, ~"hi");
- alist_add(&lst, 44, ~"ho");
- assert_eq!(alist_get(&lst, 22), ~"hi");
- assert_eq!(alist_get(&lst, 44), ~"ho");
+ alist_add(&lst, 22, "hi".to_owned());
+ alist_add(&lst, 44, "ho".to_owned());
+ assert_eq!(alist_get(&lst, 22), "hi".to_owned());
+ assert_eq!(alist_get(&lst, 44), "ho".to_owned());
let lst = new_int_alist_2();
- alist_add(&lst, 22, ~"hi");
- alist_add(&lst, 44, ~"ho");
- assert_eq!(alist_get(&lst, 22), ~"hi");
- assert_eq!(alist_get(&lst, 44), ~"ho");
+ alist_add(&lst, 22, "hi".to_owned());
+ alist_add(&lst, 44, "ho".to_owned());
+ assert_eq!(alist_get(&lst, 22), "hi".to_owned());
+ assert_eq!(alist_get(&lst, 44), "ho".to_owned());
}
fn child2(_s: ~str) { }
pub fn main() {
- let _x = task::spawn(proc() child2(~"hi"));
+ let _x = task::spawn(proc() child2("hi".to_owned()));
}
#[cat_maker]
fn cat(name: ~str) -> cat { cat{name: name,} }
-pub fn main() { let _kitty = cat(~"Spotty"); }
+pub fn main() { let _kitty = cat("Spotty".to_owned()); }
}
pub fn main() {
- let _kitty = cat(~"Spotty");
+ let _kitty = cat("Spotty".to_owned());
}
}
pub fn main() {
- let nyan: ~ToStr = ~cat(0u, 2, ~"nyan") as ~ToStr;
- print_out(nyan, ~"nyan");
+ let nyan: ~ToStr = ~cat(0u, 2, "nyan".to_owned()) as ~ToStr;
+ print_out(nyan, "nyan".to_owned());
}
}
pub fn main() {
- let mut nyan: cat = cat(0u, 2, ~"nyan");
+ let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
let mut whitefang: dog = dog();
annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
pub fn main() {
- let mut nyan = cat(0u, 2, ~"nyan");
+ let mut nyan = cat(0u, 2, "nyan".to_owned());
let mut nyan: &mut noisy = &mut nyan;
nyan.speak();
}
}
pub fn main() {
- assert_eq!(cat(~"Spreckles").get_name(), ~"Spreckles");
+ assert_eq!(cat("Spreckles".to_owned()).get_name(), "Spreckles".to_owned());
}
}
pub fn main() {
- let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan");
+ let mut nyan: cat<~str> = cat::new(0, 2, "nyan".to_owned());
for _ in range(1u, 5) { nyan.speak(); }
- assert!(*nyan.find(&1).unwrap() == ~"nyan");
+ assert!(*nyan.find(&1).unwrap() == "nyan".to_owned());
assert_eq!(nyan.find(&10), None);
let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo);
for _ in range(0u, 6) { spotty.speak(); }
pub fn main() {
- let mut nyan = cat(0u, 2, ~"nyan");
+ let mut nyan = cat(0u, 2, "nyan".to_owned());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
}
pub fn main() {
- let mut nyan = cat(0u, 2, ~"nyan");
+ let mut nyan = cat(0u, 2, "nyan".to_owned());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) {
pub fn main() {
let mut nyan : cat<char> = cat::<char>(52u, 99, vec!('p'));
- let mut kitty = cat(1000u, 2, vec!(~"tabby"));
+ let mut kitty = cat(1000u, 2, vec!("tabby".to_owned()));
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec!(1u,2u,3u));
assert_eq!(nyan.meow_count(), 55u);
- kitty.speak(vec!(~"meow", ~"mew", ~"purr", ~"chirp"));
+ kitty.speak(vec!("meow".to_owned(), "mew".to_owned(), "purr".to_owned(), "chirp".to_owned()));
assert_eq!(kitty.meow_count(), 1004u);
}
pub fn main() {
let mut nyan : cat<int> = cat::<int>(52u, 99, vec!(9));
- let mut kitty = cat(1000u, 2, vec!(~"tabby"));
+ let mut kitty = cat(1000u, 2, vec!("tabby".to_owned()));
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec!(1,2,3));
assert_eq!(nyan.meow_count(), 55u);
- kitty.speak(vec!(~"meow", ~"mew", ~"purr", ~"chirp"));
+ kitty.speak(vec!("meow".to_owned(), "mew".to_owned(), "purr".to_owned(), "chirp".to_owned()));
assert_eq!(kitty.meow_count(), 1004u);
}
}
pub fn main() {
- let nyan: ~ToStr = ~cat(0u, 2, ~"nyan") as ~ToStr;
- print_out(nyan, ~"nyan");
+ let nyan: ~ToStr = ~cat(0u, 2, "nyan".to_owned()) as ~ToStr;
+ print_out(nyan, "nyan".to_owned());
}
}
pub fn main() {
- let _nyan = cat(~"nyan");
+ let _nyan = cat("nyan".to_owned());
}
use cci_class_4::kitties::cat;
pub fn main() {
- let mut nyan = cat(0u, 2, ~"nyan");
+ let mut nyan = cat(0u, 2, "nyan".to_owned());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
}
pub fn main() {
- let mut nyan = cat(0u, 2, ~"nyan");
+ let mut nyan = cat(0u, 2, "nyan".to_owned());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
pub fn main() {
let args = os::args();
- // Here, the rvalue `~"signal"` requires cleanup. Older versions
+ // Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
// of the code had a problem that the cleanup scope for this
- // expression was the end of the `if`, and as the `~"signal"`
+ // expression was the end of the `if`, and as the `"signal".to_owned()`
// expression was never evaluated, we wound up trying to clean
// uninitialized memory.
- if args.len() >= 2 && args[1] == ~"signal" {
+ if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
}
use std::io::stdio::println;
fn call_it(f: proc(~str) -> ~str) {
- println!("{}", f(~"Fred"))
+ println!("{}", f("Fred".to_owned()))
}
fn call_a_thunk(f: ||) {
pub fn main() {
// Procs
- let greeting = ~"Hello ";
+ let greeting = "Hello ".to_owned();
call_it(proc(s) {
greeting + s
});
- let greeting = ~"Goodbye ";
+ let greeting = "Goodbye ".to_owned();
call_it(proc(s) greeting + s);
- let greeting = ~"How's life, ";
+ let greeting = "How's life, ".to_owned();
call_it(proc(s: ~str) -> ~str {
greeting + s
});
fn putint(_i: int) {
let mut i: int = 33;
- while i < 36 { putstr(~"hi"); i = i + 1; }
+ while i < 36 { putstr("hi".to_owned()); i = i + 1; }
}
fn zerg(i: int) -> int { return i; }
fn foo(x: int) -> int {
let mut y: t = x + 2;
- putstr(~"hello");
+ putstr("hello".to_owned());
while y < 10 { putint(y); if y * 3 == 4 { y = y + 2; nothing(); } }
let mut z: t;
z = 0x55;
// except according to those terms.
pub fn main() {
- assert_eq!(format!(concat!("foo", "bar", "{}"), "baz"), ~"foobarbaz");
- assert_eq!(format!(concat!()), ~"");
+ assert_eq!(format!(concat!("foo", "bar", "{}"), "baz"), "foobarbaz".to_owned());
+ assert_eq!(format!(concat!()), "".to_owned());
assert_eq!(
concat!(1, 2i, 3u, 4f32, 4.0, 'a', true, ()),
pub fn main() {
/*foo(1);
- foo(~"hi");
+ foo("hi".to_owned());
foo(~[1, 2, 3]);
foo(F{field: 42});
foo((1, 2u));
unsafe {
let foo = &A as *u8;
assert_eq!(str::raw::from_utf8(A), "hi");
- assert_eq!(str::raw::from_buf_len(foo, A.len()), ~"hi");
- assert_eq!(str::raw::from_buf_len(C, B.len()), ~"hi");
+ assert_eq!(str::raw::from_buf_len(foo, A.len()), "hi".to_owned());
+ assert_eq!(str::raw::from_buf_len(C, B.len()), "hi".to_owned());
assert!(*C == A[0]);
assert!(*(&B[0] as *u8) == A[0]);
let bar = str::raw::from_utf8(A).to_c_str();
- assert_eq!(bar.with_ref(|buf| str::raw::from_c_str(buf)), ~"hi");
+ assert_eq!(bar.with_ref(|buf| str::raw::from_c_str(buf)), "hi".to_owned());
}
}
#[cfg(unix)]
pub fn sleeper() -> Process {
- Process::new("sleep", [~"1000"]).unwrap()
+ Process::new("sleep", ["1000".to_owned()]).unwrap()
}
#[cfg(windows)]
pub fn sleeper() -> Process {
// There's a `timeout` command on windows, but it doesn't like having
// its output piped, so instead just ping ourselves a few times with
// gaps inbetweeen so we're sure this process is alive for awhile
- Process::new("ping", [~"127.0.0.1", ~"-n", ~"1000"]).unwrap()
+ Process::new("ping", ["127.0.0.1".to_owned(), "-n".to_owned(), "1000".to_owned()]).unwrap()
}
iotest!(fn test_destroy_twice() {
let x = @();
x.cx();
let y = ();
- y.add(~"hi");
+ y.add("hi".to_owned());
}
}
fn main() {
- let person1 = Person { id: 5, name: ~"Janet", phone: 555_666_7777 };
- let person2 = Person { id: 5, name: ~"Bob", phone: 555_666_7777 };
+ let person1 = Person { id: 5, name: "Janet".to_owned(), phone: 555_666_7777 };
+ let person2 = Person { id: 5, name: "Bob".to_owned(), phone: 555_666_7777 };
assert!(hash::hash(&person1) == hash::hash(&person1));
assert!(hash::hash(&person1) != hash::hash(&person2));
}
}
pub fn main() {
- assert_eq!(B1.to_str(), ~"B1");
- assert_eq!(B2.to_str(), ~"B2");
- assert_eq!(C1(3).to_str(), ~"C1(3)");
- assert_eq!(C2(B2).to_str(), ~"C2(B2)");
- assert_eq!(D1{ a: 2 }.to_str(), ~"D1 { a: 2 }");
- assert_eq!(E.to_str(), ~"E");
- assert_eq!(F(3).to_str(), ~"F(3)");
- assert_eq!(G(3, 4).to_str(), ~"G(3, 4)");
- assert_eq!(G(3, 4).to_str(), ~"G(3, 4)");
- assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I { a: 2, b: 4 }");
- assert_eq!(J(Custom).to_str(), ~"J(yay)");
+ assert_eq!(B1.to_str(), "B1".to_owned());
+ assert_eq!(B2.to_str(), "B2".to_owned());
+ assert_eq!(C1(3).to_str(), "C1(3)".to_owned());
+ assert_eq!(C2(B2).to_str(), "C2(B2)".to_owned());
+ assert_eq!(D1{ a: 2 }.to_str(), "D1 { a: 2 }".to_owned());
+ assert_eq!(E.to_str(), "E".to_owned());
+ assert_eq!(F(3).to_str(), "F(3)".to_owned());
+ assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_owned());
+ assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_owned());
+ assert_eq!(I{ a: 2, b: 4 }.to_str(), "I { a: 2, b: 4 }".to_owned());
+ assert_eq!(J(Custom).to_str(), "J(yay)".to_owned());
}
struct Foo(int, int, ~str);
pub fn main() {
- let a1 = Foo(5, 6, ~"abc");
- let a2 = Foo(5, 6, ~"abc");
- let b = Foo(5, 7, ~"def");
+ let a1 = Foo(5, 6, "abc".to_owned());
+ let a2 = Foo(5, 6, "abc".to_owned());
+ let b = Foo(5, 7, "def".to_owned());
assert!(a1 == a1);
assert!(a2 == a1);
fn f() -> int {
if true {
- let _s: ~str = ~"should not leak";
+ let _s: ~str = "should not leak".to_owned();
return 1;
}
return 0;
assert_eq!(size_of::<E>(), size_of::<$t>());
assert_eq!(V as $t, $v);
assert_eq!(C as $t, $v);
- assert_eq!(format!("{:?}", V), ~"V");
- assert_eq!(format!("{:?}", C), ~"V");
+ assert_eq!(format!("{:?}", V), "V".to_owned());
+ assert_eq!(format!("{:?}", C), "V".to_owned());
}
}
$m::check();
enum color { red = 1, green, blue, imaginary = -1, }
pub fn main() {
- test_color(red, 1, ~"red");
- test_color(green, 2, ~"green");
- test_color(blue, 3, ~"blue");
- test_color(imaginary, -1, ~"imaginary");
+ test_color(red, 1, "red".to_owned());
+ test_color(green, 2, "green".to_owned());
+ test_color(blue, 3, "blue".to_owned());
+ test_color(imaginary, -1, "imaginary".to_owned());
}
fn test_color(color: color, val: int, _name: ~str) {
}
pub fn main() {
- let mut a: Animal = Dog(~"Cocoa", 37.2);
- a = Cat{ name: ~"Spotty", weight: 2.7 };
+ let mut a: Animal = Dog("Cocoa".to_owned(), 37.2);
+ a = Cat{ name: "Spotty".to_owned(), weight: 2.7 };
// permuting the fields should work too
- let _c = Cat { weight: 3.1, name: ~"Spreckles" };
+ let _c = Cat { weight: 3.1, name: "Spreckles".to_owned() };
}
#![allow(dead_assignment)]
pub fn main() {
- let x : ~str = ~"hello";
- let _y : ~str = ~"there";
- let mut z = ~"thing";
+ let x : ~str = "hello".to_owned();
+ let _y : ~str = "there".to_owned();
+ let mut z = "thing".to_owned();
z = x;
assert_eq!(z[0], ('h' as u8));
assert_eq!(z[4], ('o' as u8));
use std::os;
pub fn main() {
- assert_eq!(os::getenv("TEST_EXEC_ENV"), Some(~"22"));
+ assert_eq!(os::getenv("TEST_EXEC_ENV"), Some("22".to_owned()));
}
use explicit_self_xcrate::{Foo, Bar};
pub fn main() {
- let x = Bar { x: ~"hello" };
+ let x = Bar { x: "hello".to_owned() };
x.f();
}
}
fn test_str() {
- let rs = if true { ~"happy" } else { ~"sad" };
- assert_eq!(rs, ~"happy");
+ let rs = if true { "happy".to_owned() } else { "sad".to_owned() };
+ assert_eq!(rs, "happy".to_owned());
}
pub fn main() { test_box(); test_str(); }
}
fn test_str() {
- let res = match true { true => { ~"happy" },
+ let res = match true { true => { "happy".to_owned() },
_ => fail!("not happy at all") };
- assert_eq!(res, ~"happy");
+ assert_eq!(res, "happy".to_owned());
}
pub fn main() { test_box(); test_str(); }
let arr = [1,2,3];
let struc = Struc {a: 13u8, b: arr, c: 42};
let s = repr::repr_to_str(&struc);
- assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}");
+ assert_eq!(s, "Struc{a: 13u8, b: [1, 2, 3], c: 42}".to_owned());
}
}
pub fn main() {
- let len = strlen(~"Rust");
+ let len = strlen("Rust".to_owned());
assert_eq!(len, 4u);
}
let name = RefCell::new("rust");
let what = RefCell::new("rocks");
let msg = format!("{name:?} {:?}", &*what.borrow(), name=&*name.borrow());
- assert_eq!(msg, ~"&\"rust\" &\"rocks\"");
+ assert_eq!(msg, "&\"rust\" &\"rocks\"".to_owned());
}
// This used to cause memory corruption in stage 0.
enum thing<K> { some(K), }
-pub fn main() { let _x = some(~"hi"); }
+pub fn main() { let _x = some("hi".to_owned()); }
This originally came from the word-count benchmark.
*/
-pub fn map(filename: ~str, emit: map_reduce::putter) { emit(filename, ~"1"); }
+pub fn map(filename: ~str, emit: map_reduce::putter) { emit(filename, "1".to_owned()); }
mod map_reduce {
use collections::HashMap;
}
pub fn main() {
- map_reduce::map_reduce(vec!(~"../src/test/run-pass/hashmap-memory.rs"));
+ map_reduce::map_reduce(vec!("../src/test/run-pass/hashmap-memory.rs".to_owned()));
}
) => (
parse_node!(
[$(: $tags ($(:$tag_nodes),*))*];
- [$(:$nodes,)* :text(~".")];
+ [$(:$nodes,)* :text(".".to_owned())];
$($rest)*
)
);
t!(format!("{}", 1.0f32), "1");
t!(format!("{}", 1.0f64), "1");
t!(format!("{}", "a"), "a");
- t!(format!("{}", ~"a"), "a");
+ t!(format!("{}", "a".to_owned()), "a");
t!(format!("{}", false), "false");
t!(format!("{}", 'a'), "a");
t!(format!("{:x}", 10u), "a");
t!(format!("{:X}", 10u), "A");
t!(format!("{:s}", "foo"), "foo");
- t!(format!("{:s}", ~"foo"), "foo");
+ t!(format!("{:s}", "foo".to_owned()), "foo");
t!(format!("{:p}", 0x1234 as *int), "0x1234");
t!(format!("{:p}", 0x1234 as *mut int), "0x1234");
t!(format!("{:d}", A), "aloha");
}
assert_eq!(format!("{} {} {a} {b} {} {c}",
foo(), foo(), foo(), a=foo(), b=foo(), c=foo()),
- ~"1 2 4 5 3 6");
+ "1 2 4 5 3 6".to_owned());
}
pub fn main() {
let x = 2;
let x_message = match x {
- 0 .. 1 => { ~"not many" }
- _ => { ~"lots" }
+ 0 .. 1 => { "not many".to_owned() }
+ _ => { "lots".to_owned() }
};
- assert_eq!(x_message, ~"lots");
+ assert_eq!(x_message, "lots".to_owned());
let y = 2i;
let y_message = match y {
- 0 .. 1 => { ~"not many" }
- _ => { ~"lots" }
+ 0 .. 1 => { "not many".to_owned() }
+ _ => { "lots".to_owned() }
};
- assert_eq!(y_message, ~"lots");
+ assert_eq!(y_message, "lots".to_owned());
let z = 1u64;
let z_message = match z {
- 0 .. 1 => { ~"not many" }
- _ => { ~"lots" }
+ 0 .. 1 => { "not many".to_owned() }
+ _ => { "lots".to_owned() }
};
- assert_eq!(z_message, ~"not many");
+ assert_eq!(z_message, "not many".to_owned());
}
pub fn main () {
let args = os::args();
- if args.len() > 1 && args[1] == ~"child" {
+ if args.len() > 1 && args[1] == "child".to_owned() {
for _ in range(0, 1000) {
println!("hello?");
}
let config = process::ProcessConfig {
program : args[0].as_slice(),
- args : &[~"child"],
+ args : &["child".to_owned()],
stdout: process::Ignored,
stderr: process::Ignored,
.. process::ProcessConfig::new()
// except according to those terms.
pub fn main () {
- let mut line = ~"";
+ let mut line = "".to_owned();
let mut i = 0;
- while line != ~"exit" {
- line = if i == 9 { ~"exit" } else { ~"notexit" };
+ while line != "exit".to_owned() {
+ line = if i == 9 { "exit".to_owned() } else { "notexit".to_owned() };
i += 1;
}
}
rx.recv();
}
} else {
- parent(~"green");
- parent(~"native");
+ parent("green".to_owned());
+ parent("native".to_owned());
let (tx, rx) = channel();
native::task::spawn(proc() {
- parent(~"green");
- parent(~"native");
+ parent("green".to_owned());
+ parent("native".to_owned());
tx.send(());
});
rx.recv();
fn parent(flavor: ~str) {
let args = os::args();
- let mut p = io::Process::new(args[0].as_slice(), [~"child", flavor]).unwrap();
+ let mut p = io::Process::new(args[0].as_slice(), ["child".to_owned(), flavor]).unwrap();
p.stdin.get_mut_ref().write_str("test1\ntest2\ntest3").unwrap();
let out = p.wait_with_output();
assert!(out.status.success());
fn noise(a: animal) -> Option<~str> {
match a {
- cat(..) => { Some(~"meow") }
- dog(..) => { Some(~"woof") }
+ cat(..) => { Some("meow".to_owned()) }
+ dog(..) => { Some("woof".to_owned()) }
rabbit(..) => { None }
- tiger(..) => { Some(~"roar") }
+ tiger(..) => { Some("roar".to_owned()) }
}
}
pub fn main() {
- assert_eq!(noise(cat(tabby)), Some(~"meow"));
- assert_eq!(noise(dog(pug)), Some(~"woof"));
- assert_eq!(noise(rabbit(~"Hilbert", upright)), None);
- assert_eq!(noise(tiger), Some(~"roar"));
+ assert_eq!(noise(cat(tabby)), Some("meow".to_owned()));
+ assert_eq!(noise(dog(pug)), Some("woof".to_owned()));
+ assert_eq!(noise(rabbit("Hilbert".to_owned(), upright)), None);
+ assert_eq!(noise(tiger), Some("roar".to_owned()));
}
// Issue 1974
// Don't double free the condition allocation
pub fn main() {
- let s = ~"hej";
- while s != ~"" {
+ let s = "hej".to_owned();
+ while s != "".to_owned() {
return;
}
}
use collections::HashMap;
pub fn main() {
- let v = vec!(@~"hi");
+ let v = vec!(@"hi".to_owned());
let mut m: req::header_map = HashMap::new();
- m.insert(~"METHOD", @RefCell::new(v));
+ m.insert("METHOD".to_owned(), @RefCell::new(v));
request::<int>(&m);
}
use collections::HashMap;
fn add_interfaces(managed_ip: ~str, device: HashMap<~str, int>) {
- println!("{}, {:?}", managed_ip, device.get(&~"interfaces"));
+ println!("{}, {:?}", managed_ip, device.get(&"interfaces".to_owned()));
}
pub fn main() {}
{
match &data {
&json::Object(ref interface) => {
- let name = lookup((*interface).clone(), ~"ifDescr", ~"");
+ let name = lookup((*interface).clone(), "ifDescr".to_owned(), "".to_owned());
let label = format!("{}-{}", managed_ip, name);
(label, bool_value(false))
}
_ => {
println!("Expected dict for {} interfaces but found {:?}", managed_ip, data);
- (~"gnos:missing-interface", bool_value(true))
+ ("gnos:missing-interface".to_owned(), bool_value(true))
}
}
}
fn add_interfaces(store: int, managed_ip: ~str, device: HashMap<~str, json::Json>)
-> Vec<(~str, object)> {
- match device.get(&~"interfaces")
+ match device.get(&"interfaces".to_owned())
{
&json::List(ref interfaces) =>
{
_ =>
{
println!("Expected list for {} interfaces but found {:?}", managed_ip,
- device.get(&~"interfaces"));
+ device.get(&"interfaces".to_owned()));
Vec::new()
}
}
impl fmt::Show for square {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", match *self {
- bot => { ~"R" }
- wall => { ~"#" }
- rock => { ~"*" }
- lambda => { ~"\\" }
- closed_lift => { ~"L" }
- open_lift => { ~"O" }
- earth => { ~"." }
- empty => { ~" " }
+ bot => { "R".to_owned() }
+ wall => { "#".to_owned() }
+ rock => { "*".to_owned() }
+ lambda => { "\\".to_owned() }
+ closed_lift => { "L".to_owned() }
+ open_lift => { "O".to_owned() }
+ earth => { ".".to_owned() }
+ empty => { " ".to_owned() }
})
}
}
content: Vec::new(),
children: Vec::new()
};
- let v = vec!(~"123", ~"abc");
- node.content = vec!(~"123", ~"abc");
+ let v = vec!("123".to_owned(), "abc".to_owned());
+ node.content = vec!("123".to_owned(), "abc".to_owned());
print_str_vector(v);
print_str_vector(node.content.clone());
fn tester()
{
- let loader: rsrc_loader = proc(_path) {result::Ok(~"more blah")};
+ let loader: rsrc_loader = proc(_path) {result::Ok("more blah".to_owned())};
let path = path::Path::new("blah");
assert!(loader(&path).is_ok());
pub fn main()
{
-// assert!(check_strs(fmt!("%?", Text(@~"foo")), "Text(@~\"foo\")"));
-// assert!(check_strs(fmt!("%?", ETag(@~[~"foo"], @~"bar")), "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
+// assert!(check_strs(fmt!("%?", Text(@"foo".to_owned())), "Text(@~\"foo\")"));
+// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_owned()], @"bar".to_owned())),
+// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
- let t = Text(@~"foo");
- let u = Section(@vec!(~"alpha"), true, @vec!(t), @~"foo", @~"foo", @~"foo", @~"foo", @~"foo");
+ let t = Text(@"foo".to_owned());
+ let u = Section(@vec!("alpha".to_owned()), true, @vec!(t), @"foo".to_owned(),
+ @"foo".to_owned(), @"foo".to_owned(), @"foo".to_owned(),
+ @"foo".to_owned());
let v = format!("{:?}", u); // this is the line that causes the seg fault
assert!(v.len() > 0);
}
pub fn main() {
let mut table = HashMap::new();
- table.insert(~"one", 1);
- table.insert(~"two", 2);
+ table.insert("one".to_owned(), 1);
+ table.insert("two".to_owned(), 2);
assert!(check_strs(table.to_str(), "{one: 1, two: 2}") ||
check_strs(table.to_str(), "{two: 2, one: 1}"));
}
pub fn main()
{
assert!(compare("foo", "foo"));
- assert!(compare(~"foo", ~"foo"));
+ assert!(compare("foo".to_owned(), "foo".to_owned()));
}
}
pub fn main() {
- let town_bike = Bike { name: ~"schwinn" };
- let my_bike = Bike { name: ~"surly" };
+ let town_bike = Bike { name: "schwinn".to_owned() };
+ let my_bike = Bike { name: "surly".to_owned() };
assert!(town_bike != my_bike);
}
}
priv fn cmd_to_str(cmd: ~[~str]) -> ~str {
- let mut res = ~"*";
+ let mut res = "*".to_owned();
res.push_str(cmd.len().to_str());
res.push_str("\r\n");
for s in cmd.iter() {
- res.push_str([~"$", s.len().to_str(), ~"\r\n",
- (*s).clone(), ~"\r\n"].concat() );
+ res.push_str(["$".to_owned(), s.len().to_str(), "\r\n".to_owned(),
+ (*s).clone(), "\r\n".to_owned()].concat() );
}
res
}
fn query2(cmd: ~[~str]) -> Result {
let _cmd = cmd_to_str(cmd);
- io::with_str_reader(~"$3\r\nXXX\r\n")(|sb| {
+ io::with_str_reader("$3\r\nXXX\r\n".to_owned())(|sb| {
let res = parse_response(@sb as @io::Reader);
println!("{:?}", res);
res
n += 1;
}
- return ~""
+ return "".to_owned()
}
pub fn main() {
}
impl Thing {
- fn new() -> Thing { Thing { name: ~"dummy" } }
+ fn new() -> Thing { Thing { name: "dummy".to_owned() } }
}
impl Debuggable for Thing {
{
match err
{
- INVALID_ENUM => { ~"Invalid enum" },
- INVALID_VALUE => { ~"Invalid value" },
- _ => { ~"Unknown error" }
+ INVALID_ENUM => { "Invalid enum".to_owned() },
+ INVALID_VALUE => { "Invalid value".to_owned() },
+ _ => { "Unknown error".to_owned() }
}
}
#![allow(dead_assignment)]
pub fn main() {
- let s: ~str = ~"foobar";
+ let s: ~str = "foobar".to_owned();
let mut t: &str = s;
t = t.slice(0, 3); // for master: str::view(t, 0, 3) maybe
}
pub fn main() {
- let snoopy = ~Dog{name: ~"snoopy"};
- let bubbles = ~Dog{name: ~"bubbles"};
+ let snoopy = ~Dog{name: "snoopy".to_owned()};
+ let bubbles = ~Dog{name: "bubbles".to_owned()};
let barker = [snoopy as ~Barks, bubbles as ~Barks];
for pup in barker.iter() {
let slice = x.slice(0,1);
let z = @x;
- assert_repr_eq(abc, ~"[1, 2, 3]");
- assert_repr_eq(tf, ~"[true, false]");
- assert_repr_eq(x, ~"[(), ()]");
- assert_repr_eq(slice, ~"&[()]");
- assert_repr_eq(&x, ~"&[(), ()]");
- assert_repr_eq(z, ~"@[(), ()]");
+ assert_repr_eq(abc, "[1, 2, 3]".to_owned());
+ assert_repr_eq(tf, "[true, false]".to_owned());
+ assert_repr_eq(x, "[(), ()]".to_owned());
+ assert_repr_eq(slice, "&[()]".to_owned());
+ assert_repr_eq(&x, "&[(), ()]".to_owned());
+ assert_repr_eq(z, "@[(), ()]".to_owned());
}
let mut ch_start: uint;
break 'outer;
}
- ~""
+ "".to_owned()
}
pub fn main() {
}
pub fn main() {
- let b = &[~"foo"];
+ let b = &["foo".to_owned()];
let a = A {
- a: &[~"test"],
+ a: &["test".to_owned()],
b: Some(b),
};
assert_eq!(a.b.get_ref()[0].as_slice(), "foo");
fn foo(&self) -> ~str;
fn foo1(&self) -> ~str;
fn foo2(&self) -> ~str{
- ~"base foo2"
+ "base foo2".to_owned()
}
}
impl Base for X {
fn foo(&self) -> ~str{
- ~"base foo"
+ "base foo".to_owned()
}
fn foo1(&self) -> ~str{
- ~"base foo1"
+ "base foo1".to_owned()
}
}
impl Base2 for X {
fn baz(&self) -> ~str{
- ~"base2 baz"
+ "base2 baz".to_owned()
}
}
impl Base3 for X {
fn root(&self) -> ~str{
- ~"base3 root"
+ "base3 root".to_owned()
}
}
impl Super for X {
fn bar(&self) -> ~str{
- ~"super bar"
+ "super bar".to_owned()
}
}
pub fn main() {
let n = X;
let s = &n as &Super;
- assert_eq!(s.bar(),~"super bar");
- assert_eq!(s.foo(),~"base foo");
- assert_eq!(s.foo1(),~"base foo1");
- assert_eq!(s.foo2(),~"base foo2");
- assert_eq!(s.baz(),~"base2 baz");
- assert_eq!(s.root(),~"base3 root");
+ assert_eq!(s.bar(),"super bar".to_owned());
+ assert_eq!(s.foo(),"base foo".to_owned());
+ assert_eq!(s.foo1(),"base foo1".to_owned());
+ assert_eq!(s.foo2(),"base foo2".to_owned());
+ assert_eq!(s.baz(),"base2 baz".to_owned());
+ assert_eq!(s.root(),"base3 root".to_owned());
}
pub fn main() {
{
// This runs without complaint.
- let x = Wrapper::new(~"Bob");
+ let x = Wrapper::new("Bob".to_owned());
x.say_hi();
}
{
// This fails to compile, circa 0.8-89-gc635fba.
// error: internal compiler error: drop_ty_immediate: non-box ty
- Wrapper::new(~"Bob").say_hi();
+ Wrapper::new("Bob".to_owned()).say_hi();
}
}
use std::strbuf::StrBuf;
fn test_stack_assign() {
- let s: ~str = ~"a";
+ let s: ~str = "a".to_owned();
println!("{}", s.clone());
- let t: ~str = ~"a";
+ let t: ~str = "a".to_owned();
assert!(s == t);
- let u: ~str = ~"b";
+ let u: ~str = "b".to_owned();
assert!((s != u));
}
-fn test_heap_lit() { ~"a big string"; }
+fn test_heap_lit() { "a big string".to_owned(); }
fn test_heap_assign() {
- let s: ~str = ~"a big ol' string";
- let t: ~str = ~"a big ol' string";
+ let s: ~str = "a big ol' string".to_owned();
+ let t: ~str = "a big ol' string".to_owned();
assert!(s == t);
- let u: ~str = ~"a bad ol' string";
+ let u: ~str = "a bad ol' string".to_owned();
assert!((s != u));
}
-fn test_heap_log() { let s = ~"a big ol' string"; println!("{}", s); }
+fn test_heap_log() { let s = "a big ol' string".to_owned(); println!("{}", s); }
fn test_stack_add() {
- assert_eq!(~"a" + "b", ~"ab");
- let s: ~str = ~"a";
- assert_eq!(s + s, ~"aa");
- assert_eq!(~"" + "", ~"");
+ assert_eq!("a".to_owned() + "b", "ab".to_owned());
+ let s: ~str = "a".to_owned();
+ assert_eq!(s + s, "aa".to_owned());
+ assert_eq!("".to_owned() + "", "".to_owned());
}
-fn test_stack_heap_add() { assert!((~"a" + "bracadabra" == ~"abracadabra")); }
+fn test_stack_heap_add() { assert!(("a".to_owned() + "bracadabra" == "abracadabra".to_owned())); }
fn test_heap_add() {
- assert_eq!(~"this should" + " totally work", ~"this should totally work");
+ assert_eq!("this should".to_owned() + " totally work", "this should totally work".to_owned());
}
fn test_append() {
// except according to those terms.
fn f() {
- let a = ~"hello";
+ let a = "hello".to_owned();
let b: &str = a;
println!("{}", b);
}
// except according to those terms.
pub fn main() {
- let x = ~"hello";
+ let x = "hello".to_owned();
let ref y = x;
assert_eq!(x.slice(0, x.len()), y.slice(0, y.len()));
}
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
- let s = ~"hello there";
+ let s = "hello there".to_owned();
let mut i: int = 0;
for c in s.bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
-pub fn main() { if false { println!("{}", ~"foo" + "bar"); } }
+pub fn main() { if false { println!("{}", "foo".to_owned() + "bar"); } }
pub fn main() {
let mut x = Some(a(22u));
- let exp = ~"Some(a(22u))";
+ let exp = "Some(a(22u))".to_owned();
let act = format!("{:?}", x);
assert_eq!(act, exp);
check_log(exp, x);
- x = Some(b(~"hi"));
- let exp = ~"Some(b(~\"hi\"))";
+ x = Some(b("hi".to_owned()));
+ let exp = "Some(b(~\"hi\"))".to_owned();
let act = format!("{:?}", x);
assert_eq!(act, exp);
check_log(exp, x);
x = None;
- let exp = ~"None";
+ let exp = "None".to_owned();
let act = format!("{:?}", x);
assert_eq!(act, exp);
check_log(exp, x);
}
pub fn main() {
- assert_eq!(~"a(22u)", format!("{:?}", a(22u)));
- assert_eq!(~"b(~\"hi\")", format!("{:?}", b(~"hi")));
- assert_eq!(~"c", format!("{:?}", c));
- assert_eq!(~"d", format!("{:?}", d));
+ assert_eq!("a(22u)".to_owned(), format!("{:?}", a(22u)));
+ assert_eq!("b(~\"hi\")".to_owned(), format!("{:?}", b("hi".to_owned())));
+ assert_eq!("c".to_owned(), format!("{:?}", c));
+ assert_eq!("d".to_owned(), format!("{:?}", d));
}
fn f1(ref_string: &str) -> ~str {
match ref_string {
- "a" => ~"found a",
- "b" => ~"found b",
- _ => ~"not found"
+ "a" => "found a".to_owned(),
+ "b" => "found b".to_owned(),
+ _ => "not found".to_owned()
}
}
fn f2(ref_string: &str) -> ~str {
match ref_string {
- "a" => ~"found a",
- "b" => ~"found b",
+ "a" => "found a".to_owned(),
+ "b" => "found b".to_owned(),
s => format!("not found ({})", s)
}
}
fn g1(ref_1: &str, ref_2: &str) -> ~str {
match (ref_1, ref_2) {
- ("a", "b") => ~"found a,b",
- ("b", "c") => ~"found b,c",
- _ => ~"not found"
+ ("a", "b") => "found a,b".to_owned(),
+ ("b", "c") => "found b,c".to_owned(),
+ _ => "not found".to_owned()
}
}
fn g2(ref_1: &str, ref_2: &str) -> ~str {
match (ref_1, ref_2) {
- ("a", "b") => ~"found a,b",
- ("b", "c") => ~"found b,c",
+ ("a", "b") => "found a,b".to_owned(),
+ ("b", "c") => "found b,c".to_owned(),
(s1, s2) => format!("not found ({}, {})", s1, s2)
}
}
pub fn main() {
- assert_eq!(f1(~"b"), ~"found b");
- assert_eq!(f1(&"c"), ~"not found");
- assert_eq!(f1("d"), ~"not found");
- assert_eq!(f2(~"b"), ~"found b");
- assert_eq!(f2(&"c"), ~"not found (c)");
- assert_eq!(f2("d"), ~"not found (d)");
- assert_eq!(g1(~"b", ~"c"), ~"found b,c");
- assert_eq!(g1(&"c", &"d"), ~"not found");
- assert_eq!(g1("d", "e"), ~"not found");
- assert_eq!(g2(~"b", ~"c"), ~"found b,c");
- assert_eq!(g2(&"c", &"d"), ~"not found (c, d)");
- assert_eq!(g2("d", "e"), ~"not found (d, e)");
+ assert_eq!(f1("b".to_owned()), "found b".to_owned());
+ assert_eq!(f1(&"c"), "not found".to_owned());
+ assert_eq!(f1("d"), "not found".to_owned());
+ assert_eq!(f2("b".to_owned()), "found b".to_owned());
+ assert_eq!(f2(&"c"), "not found (c)".to_owned());
+ assert_eq!(f2("d"), "not found (d)".to_owned());
+ assert_eq!(g1("b".to_owned(), "c".to_owned()), "found b,c".to_owned());
+ assert_eq!(g1(&"c", &"d"), "not found".to_owned());
+ assert_eq!(g1("d", "e"), "not found".to_owned());
+ assert_eq!(g2("b".to_owned(), "c".to_owned()), "found b,c".to_owned());
+ assert_eq!(g2(&"c", &"d"), "not found (c, d)".to_owned());
+ assert_eq!(g2("d", "e"), "not found (d, e)".to_owned());
}
fn test1() {
// from issue 6338
- match ((1, ~"a"), (2, ~"b")) {
+ match ((1, "a".to_owned()), (2, "b".to_owned())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
- assert_eq!(a, ~"a");
- assert_eq!(b, ~"b");
+ assert_eq!(a, "a".to_owned());
+ assert_eq!(b, "b".to_owned());
},
_ => fail!(),
}
enum t { tag1(~str), tag2, }
- match tag1(~"test") {
+ match tag1("test".to_owned()) {
tag2 => fail!(),
tag1(ref s) if "test" != *s => fail!(),
tag1(ref s) if "test" == *s => (),
}
pub fn main() {
- assert_eq!(transform(Some(10)), Some(~"11"));
+ assert_eq!(transform(Some(10)), Some("11".to_owned()));
assert_eq!(transform(None), None);
- assert!((vec!(~"hi"))
+ assert!((vec!("hi".to_owned()))
.bind(|x| vec!(x.clone(), *x + "!") )
.bind(|x| vec!(x.clone(), *x + "?") ) ==
- vec!(~"hi", ~"hi?", ~"hi!", ~"hi!?"));
+ vec!("hi".to_owned(), "hi?".to_owned(), "hi!".to_owned(), "hi!?".to_owned()));
}
}
pub fn main() {
- let x = S { x: ~"Hello!" };
+ let x = S { x: "Hello!".to_owned() };
x.foo();
}
use std::task;
pub fn main() {
- let x = ~"Hello world!";
+ let x = "Hello world!".to_owned();
task::spawn(proc() {
println!("{}", x);
});
check_type!(&17: &int);
check_type!(~18: ~int);
check_type!(@19: @int);
- check_type!(~"foo": ~str);
+ check_type!("foo".to_owned(): ~str);
check_type!(vec!(20, 22): Vec<int> );
let mint: uint = unsafe { cast::transmute(main) };
check_type!(main: fn(), |pthing| {
// except according to those terms.
pub fn main() {
- let thing = ~"{{ f }}";
+ let thing = "{{ f }}".to_owned();
let f = thing.find_str("{{");
if f.is_none() {
} else if args.len() > 1 && args[1].as_slice() == "loud" {
loud_recurse();
} else {
- let silent = Process::output(args[0], [~"silent"]).unwrap();
+ let silent = Process::output(args[0], ["silent".to_owned()]).unwrap();
assert!(!silent.status.success());
let error = str::from_utf8_lossy(silent.error.as_slice());
assert!(error.as_slice().contains("has overflowed its stack"));
- let loud = Process::output(args[0], [~"loud"]).unwrap();
+ let loud = Process::output(args[0], ["loud".to_owned()]).unwrap();
assert!(!loud.status.success());
let error = str::from_utf8_lossy(silent.error.as_slice());
assert!(error.as_slice().contains("has overflowed its stack"));
}
pub fn main() {
- let foo = ~"foo";
- let bar = ~"bar";
+ let foo = "foo".to_owned();
+ let bar = "bar".to_owned();
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
*i.borrow_mut() = 5;
assert_eq!((i_value, *i.borrow()), (2, 5));
- let s = Rc::new(~"foo");
+ let s = Rc::new("foo".to_owned());
assert!(s.equiv(&("foo")));
assert_eq!(s.as_slice(), "foo");
*(*i).borrow_mut() = 5;
assert_eq!((i_value, *(*i).borrow()), (2, 5));
- let s = Rc::new(~"foo");
- assert_eq!(*s, ~"foo");
+ let s = Rc::new("foo".to_owned());
+ assert_eq!(*s, "foo".to_owned());
assert_eq!((*s).as_slice(), "foo");
let mut_s = Rc::new(RefCell::new(StrBuf::from_str("foo")));
let config = process::ProcessConfig {
program : "/bin/sh",
- args: &[~"-c", ~"read a"],
+ args: &["-c".to_owned(), "read a".to_owned()],
detach: true,
.. process::ProcessConfig::new()
};
// because `inner`s alignment was 4.
assert_eq!(mem::size_of::<Outer>(), m::size());
- assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u32}}");
+ assert_eq!(y, "Outer{c8: 22u8, t: Inner{c64: 44u32}}".to_owned());
}
}
// because `Inner`s alignment was 4.
assert_eq!(mem::size_of::<Outer>(), m::m::size());
- assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}");
+ assert_eq!(y, "Outer{c8: 22u8, t: Inner{c64: 44u64}}".to_owned());
}
}
struct X { foo: ~str, bar: ~str }
pub fn main() {
- let x = X {foo: ~"hello", bar: ~"world"};
+ let x = X {foo: "hello".to_owned(), bar: "world".to_owned()};
println!("{}", x.foo.clone());
println!("{}", x.bar.clone());
}
assert_eq!(42, Foo::foo());
assert_eq!(84, Baz::bar());
assert!(Boz::boz(1));
- assert_eq!(~"bort()", Bort::bort());
+ assert_eq!("bort()".to_owned(), Bort::bort());
}
impl TyVisitor for MyVisitor {
fn visit_bot(&mut self) -> bool {
- self.types.push(~"bot");
+ self.types.push("bot".to_owned());
println!("visited bot type");
true
}
fn visit_nil(&mut self) -> bool {
- self.types.push(~"nil");
+ self.types.push("nil".to_owned());
println!("visited nil type");
true
}
fn visit_bool(&mut self) -> bool {
- self.types.push(~"bool");
+ self.types.push("bool".to_owned());
println!("visited bool type");
true
}
fn visit_int(&mut self) -> bool {
- self.types.push(~"int");
+ self.types.push("int".to_owned());
println!("visited int type");
true
}
fn visit_i8(&mut self) -> bool {
- self.types.push(~"i8");
+ self.types.push("i8".to_owned());
println!("visited i8 type");
true
}
fn visit_i16(&mut self) -> bool {
- self.types.push(~"i16");
+ self.types.push("i16".to_owned());
println!("visited i16 type");
true
}
fn visit_evec_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true }
fn visit_evec_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
- self.types.push(~"[");
+ self.types.push("[".to_owned());
unsafe { visit_tydesc(inner, &mut *self as &mut TyVisitor); }
- self.types.push(~"]");
+ self.types.push("]".to_owned());
true
}
fn visit_evec_slice(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true }
}
let vec_types: Vec<~str> = v.types.clone().move_iter().collect();
- assert_eq!(vec_types, vec!(~"bool", ~"int", ~"i8", ~"i16"));
+ assert_eq!(vec_types, vec!("bool".to_owned(), "int".to_owned(),
+ "i8".to_owned(), "i16".to_owned()));
}
}
pub fn main() {
- let p = ~"hello";
+ let p = "hello".to_owned();
let r = foo(p);
assert_eq!(r, 'h' as u8);
- let p = ~"hello";
+ let p = "hello".to_owned();
let r = foo(p);
assert_eq!(r, 'h' as u8);
}
})
});
assert!((ostream as uint != 0u));
- let s = ~"hello";
+ let s = "hello".to_owned();
"hello".with_c_str(|buf| {
let write_len = libc::fwrite(buf as *libc::c_void,
1u as libc::size_t,
fn my_err(s: ~str) -> ! { println!("{:?}", s); fail!(); }
fn okay(i: uint) -> int {
- if i == 3u { my_err(~"I don't like three"); } else { return 42; }
+ if i == 3u { my_err("I don't like three".to_owned()); } else { return 42; }
}
pub fn main() { okay(4u); }
pub fn main() {
let mut map: HashMap<SendStr, uint> = HashMap::new();
assert!(map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned(~"foo"), 42));
+ assert!(!map.insert(Owned("foo".to_owned()), 42));
assert!(!map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned(~"foo"), 42));
+ assert!(!map.insert(Owned("foo".to_owned()), 42));
assert!(!map.insert(Slice("foo"), 43));
- assert!(!map.insert(Owned(~"foo"), 44));
+ assert!(!map.insert(Owned("foo".to_owned()), 44));
assert!(!map.insert(Slice("foo"), 45));
- assert!(!map.insert(Owned(~"foo"), 46));
+ assert!(!map.insert(Owned("foo".to_owned()), 46));
let v = 46;
- assert_eq!(map.find(&Owned(~"foo")), Some(&v));
+ assert_eq!(map.find(&Owned("foo".to_owned())), Some(&v));
assert_eq!(map.find(&Slice("foo")), Some(&v));
let (a, b, c, d) = (50, 51, 52, 53);
assert!(map.insert(Slice("abc"), a));
- assert!(map.insert(Owned(~"bcd"), b));
+ assert!(map.insert(Owned("bcd".to_owned()), b));
assert!(map.insert(Slice("cde"), c));
- assert!(map.insert(Owned(~"def"), d));
+ assert!(map.insert(Owned("def".to_owned()), d));
assert!(!map.insert(Slice("abc"), a));
- assert!(!map.insert(Owned(~"bcd"), b));
+ assert!(!map.insert(Owned("bcd".to_owned()), b));
assert!(!map.insert(Slice("cde"), c));
- assert!(!map.insert(Owned(~"def"), d));
+ assert!(!map.insert(Owned("def".to_owned()), d));
- assert!(!map.insert(Owned(~"abc"), a));
+ assert!(!map.insert(Owned("abc".to_owned()), a));
assert!(!map.insert(Slice("bcd"), b));
- assert!(!map.insert(Owned(~"cde"), c));
+ assert!(!map.insert(Owned("cde".to_owned()), c));
assert!(!map.insert(Slice("def"), d));
assert_eq!(map.find_equiv(&("abc")), Some(&a));
assert_eq!(map.find_equiv(&("cde")), Some(&c));
assert_eq!(map.find_equiv(&("def")), Some(&d));
- assert_eq!(map.find_equiv(&(~"abc")), Some(&a));
- assert_eq!(map.find_equiv(&(~"bcd")), Some(&b));
- assert_eq!(map.find_equiv(&(~"cde")), Some(&c));
- assert_eq!(map.find_equiv(&(~"def")), Some(&d));
+ assert_eq!(map.find_equiv(&("abc".to_owned())), Some(&a));
+ assert_eq!(map.find_equiv(&("bcd".to_owned())), Some(&b));
+ assert_eq!(map.find_equiv(&("cde".to_owned())), Some(&c));
+ assert_eq!(map.find_equiv(&("def".to_owned())), Some(&d));
assert_eq!(map.find_equiv(&Slice("abc")), Some(&a));
assert_eq!(map.find_equiv(&Slice("bcd")), Some(&b));
assert_eq!(map.find_equiv(&Slice("cde")), Some(&c));
assert_eq!(map.find_equiv(&Slice("def")), Some(&d));
- assert_eq!(map.find_equiv(&Owned(~"abc")), Some(&a));
- assert_eq!(map.find_equiv(&Owned(~"bcd")), Some(&b));
- assert_eq!(map.find_equiv(&Owned(~"cde")), Some(&c));
- assert_eq!(map.find_equiv(&Owned(~"def")), Some(&d));
+ assert_eq!(map.find_equiv(&Owned("abc".to_owned())), Some(&a));
+ assert_eq!(map.find_equiv(&Owned("bcd".to_owned())), Some(&b));
+ assert_eq!(map.find_equiv(&Owned("cde".to_owned())), Some(&c));
+ assert_eq!(map.find_equiv(&Owned("def".to_owned())), Some(&d));
}
pub fn main() {
let mut map: TreeMap<SendStr, uint> = TreeMap::new();
assert!(map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned(~"foo"), 42));
+ assert!(!map.insert(Owned("foo".to_owned()), 42));
assert!(!map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned(~"foo"), 42));
+ assert!(!map.insert(Owned("foo".to_owned()), 42));
assert!(!map.insert(Slice("foo"), 43));
- assert!(!map.insert(Owned(~"foo"), 44));
+ assert!(!map.insert(Owned("foo".to_owned()), 44));
assert!(!map.insert(Slice("foo"), 45));
- assert!(!map.insert(Owned(~"foo"), 46));
+ assert!(!map.insert(Owned("foo".to_owned()), 46));
let v = 46;
- assert_eq!(map.find(&Owned(~"foo")), Some(&v));
+ assert_eq!(map.find(&Owned("foo".to_owned())), Some(&v));
assert_eq!(map.find(&Slice("foo")), Some(&v));
let (a, b, c, d) = (50, 51, 52, 53);
assert!(map.insert(Slice("abc"), a));
- assert!(map.insert(Owned(~"bcd"), b));
+ assert!(map.insert(Owned("bcd".to_owned()), b));
assert!(map.insert(Slice("cde"), c));
- assert!(map.insert(Owned(~"def"), d));
+ assert!(map.insert(Owned("def".to_owned()), d));
assert!(!map.insert(Slice("abc"), a));
- assert!(!map.insert(Owned(~"bcd"), b));
+ assert!(!map.insert(Owned("bcd".to_owned()), b));
assert!(!map.insert(Slice("cde"), c));
- assert!(!map.insert(Owned(~"def"), d));
+ assert!(!map.insert(Owned("def".to_owned()), d));
- assert!(!map.insert(Owned(~"abc"), a));
+ assert!(!map.insert(Owned("abc".to_owned()), a));
assert!(!map.insert(Slice("bcd"), b));
- assert!(!map.insert(Owned(~"cde"), c));
+ assert!(!map.insert(Owned("cde".to_owned()), c));
assert!(!map.insert(Slice("def"), d));
assert_eq!(map.find(&Slice("abc")), Some(&a));
assert_eq!(map.find(&Slice("cde")), Some(&c));
assert_eq!(map.find(&Slice("def")), Some(&d));
- assert_eq!(map.find(&Owned(~"abc")), Some(&a));
- assert_eq!(map.find(&Owned(~"bcd")), Some(&b));
- assert_eq!(map.find(&Owned(~"cde")), Some(&c));
- assert_eq!(map.find(&Owned(~"def")), Some(&d));
+ assert_eq!(map.find(&Owned("abc".to_owned())), Some(&a));
+ assert_eq!(map.find(&Owned("bcd".to_owned())), Some(&b));
+ assert_eq!(map.find(&Owned("cde".to_owned())), Some(&c));
+ assert_eq!(map.find(&Owned("def".to_owned())), Some(&d));
assert!(map.pop(&Slice("foo")).is_some());
assert_eq!(map.move_iter().map(|(k, v)| k.to_str() + v.to_str())
.collect::<~[~str]>()
.concat(),
- ~"abc50bcd51cde52def53");
+ "abc50bcd51cde52def53".to_owned());
}
pub fn main() {
- assert!((~"hello" < ~"hellr"));
- assert!((~"hello " > ~"hello"));
- assert!((~"hello" != ~"there"));
+ assert!(("hello".to_owned() < "hellr".to_owned()));
+ assert!(("hello ".to_owned() > "hello".to_owned()));
+ assert!(("hello".to_owned() != "there".to_owned()));
assert!((vec!(1, 2, 3, 4) > vec!(1, 2, 3)));
assert!((vec!(1, 2, 3) < vec!(1, 2, 3, 4)));
assert!((vec!(1, 2, 4, 4) > vec!(1, 2, 3, 4)));
let t: @ty = @Spanned { data: 3u, span: sp };
let p_: Path_ = Path_ {
global: true,
- idents: vec!(~"hi"),
+ idents: vec!("hi".to_owned()),
types: vec!(t),
};
let p: path = Spanned { data: p_, span: sp };
pub fn main() {
let args = os::args();
- if args.len() >= 2 && args[1] == ~"signal" {
+ if args.len() >= 2 && args[1] == "signal".to_owned() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
- let status = Process::status(args[0], [~"signal"]).unwrap();
+ let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
return test();
}
- let mut p = Process::new(args[0], [~"test"]).unwrap();
+ let mut p = Process::new(args[0], ["test".to_owned()]).unwrap();
assert!(p.wait().success());
}
}
pub fn main() {
- task::spawn(proc() x(~"hello from first spawned fn", 65) );
- task::spawn(proc() x(~"hello from second spawned fn", 66) );
- task::spawn(proc() x(~"hello from third spawned fn", 67) );
+ task::spawn(proc() x("hello from first spawned fn".to_owned(), 65) );
+ task::spawn(proc() x("hello from second spawned fn".to_owned(), 66) );
+ task::spawn(proc() x("hello from third spawned fn".to_owned(), 67) );
let mut i: int = 30;
while i > 0 { i = i - 1; println!("parent sleeping"); task::deschedule(); }
}
type ctx = Sender<int>;
fn iotask(_tx: &ctx, ip: ~str) {
- assert_eq!(ip, ~"localhost");
+ assert_eq!(ip, "localhost".to_owned());
}
pub fn main() {
let (tx, _rx) = channel::<int>();
- task::spawn(proc() iotask(&tx, ~"localhost") );
+ task::spawn(proc() iotask(&tx, "localhost".to_owned()) );
}
pub fn main() {
assert_eq!(10u.plus(), 30);
- assert_eq!((~"hi").plus(), 200);
+ assert_eq!(("hi".to_owned()).plus(), 200);
- assert_eq!((vec!(1)).length_().str(), ~"1");
+ assert_eq!((vec!(1)).length_().str(), "1".to_owned());
let vect = vec!(3, 4).map_(|a| *a + 4);
assert_eq!(*vect.get(0), 7);
let vect = (vec!(3, 4)).map_::<uint>(|a| *a as uint + 4u);
use static_methods_crate::read;
pub fn main() {
- let result: int = read(~"5");
+ let result: int = read("5".to_owned());
assert_eq!(result, 5);
- assert_eq!(read::readMaybe(~"false"), Some(false));
- assert_eq!(read::readMaybe(~"foo"), None::<bool>);
+ assert_eq!(read::readMaybe("false".to_owned()), Some(false));
+ assert_eq!(read::readMaybe("foo".to_owned()), None::<bool>);
}
pub fn main() {
- let a: ~str = ~"hello";
- let b: ~str = ~"world";
+ let a: ~str = "hello".to_owned();
+ let b: ~str = "world".to_owned();
let s: ~str = a + b;
println!("{}", s.clone());
assert_eq!(s[9], 'd' as u8);
pub fn main() {
- let s = ~"hello";
+ let s = "hello".to_owned();
let c: u8 = s[4];
println!("{:?}", c);
assert_eq!(c, 0x6f as u8);
// except according to those terms.
pub fn main() {
- let a: ~str = ~"this \
-is a test";
+ let a: ~str = "this \
+is a test".to_owned();
let b: ~str =
- ~"this \
- is \
- another \
- test";
- assert_eq!(a, ~"this is a test");
- assert_eq!(b, ~"this is another test");
+ "this \
+ is \
+ another \
+ test".to_owned();
+ assert_eq!(a, "this is a test".to_owned());
+ assert_eq!(b, "this is another test".to_owned());
}
pub fn main() {
// Make sure we properly handle repeated self-appends.
- let mut a: ~str = ~"A";
+ let mut a: ~str = "A".to_owned();
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
assert_eq!(foo, foo_);
let foo = Foo {
- bar: ~"one",
- baz: ~"two"
+ bar: "one".to_owned(),
+ baz: "two".to_owned()
};
let foo_ = foo.clone();
}
pub fn main() {
- let _z = foo { x: ~"Hello" };
+ let _z = foo { x: "Hello".to_owned() };
}
struct S { f0: ~str, f1: int }
pub fn main() {
- let s = ~"Hello, world!";
+ let s = "Hello, world!".to_owned();
let _s = S { f0: s.to_owned(), ..S { f0: s, f1: 23 } };
}
struct S { f0: ~str, f1: ~str }
pub fn main() {
- let s = ~"Hello, world!";
+ let s = "Hello, world!".to_owned();
let _s = S { f1: s.to_owned(), f0: s };
}
pub fn main() {
let mut test = TestDescAndFn {
desc: TestDesc {
- name: DynTestName(~"test"),
+ name: DynTestName("test".to_owned()),
should_fail: false
},
testfn: DynTestFn(proc() ()),
//assert!((col!() == 11));
assert_eq!(indirect_line!(), 27);
assert!((file!().to_owned().ends_with("syntax-extension-source-utils.rs")));
- assert_eq!(stringify!((2*3) + 5).to_owned(), ~"( 2 * 3 ) + 5");
+ assert_eq!(stringify!((2*3) + 5).to_owned(), "( 2 * 3 ) + 5".to_owned());
assert!(include!("syntax-extension-source-utils-files/includeme.fragment").to_owned()
- == ~"victory robot 6");
+ == "victory robot 6".to_owned());
assert!(
include_str!("syntax-extension-source-utils-files/includeme.fragment").to_owned()
let x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = format!("{:?}", x);
println!("y = {}", y);
- assert_eq!(y, ~"t_rec{c8: 22u8, t: a_tag(44u64)}");
+ assert_eq!(y, "t_rec{c8: 22u8, t: a_tag(44u64)}".to_owned());
}
pub fn main() {
let act = format!("{:?}", red);
println!("{}", act);
- assert_eq!(~"red", act);
- assert_eq!(~"green", format!("{:?}", green));
- assert_eq!(~"white", format!("{:?}", white));
+ assert_eq!("red".to_owned(), act);
+ assert_eq!("green".to_owned(), format!("{:?}", green));
+ assert_eq!("white".to_owned(), format!("{:?}", white));
}
}
pub fn main() {
- test_color(red, 0xff0000, ~"red");
- test_color(green, 0x00ff00, ~"green");
- test_color(blue, 0x0000ff, ~"blue");
- test_color(black, 0x000000, ~"black");
- test_color(white, 0xFFFFFF, ~"white");
- test_color(imaginary, -1, ~"imaginary");
- test_color(purple, 2, ~"purple");
- test_color(orange, 4, ~"orange");
+ test_color(red, 0xff0000, "red".to_owned());
+ test_color(green, 0x00ff00, "green".to_owned());
+ test_color(blue, 0x0000ff, "blue".to_owned());
+ test_color(black, 0x000000, "black".to_owned());
+ test_color(white, 0xFFFFFF, "white".to_owned());
+ test_color(imaginary, -1, "imaginary".to_owned());
+ test_color(purple, 2, "purple".to_owned());
+ test_color(orange, 4, "orange".to_owned());
}
fn test_color(color: color, val: int, name: ~str) {
fn get_color_alt(color: color) -> ~str {
match color {
- red => {~"red"}
- green => {~"green"}
- blue => {~"blue"}
- black => {~"black"}
- white => {~"white"}
- imaginary => {~"imaginary"}
- purple => {~"purple"}
- orange => {~"orange"}
+ red => {"red".to_owned()}
+ green => {"green".to_owned()}
+ blue => {"blue".to_owned()}
+ black => {"black".to_owned()}
+ white => {"white".to_owned()}
+ imaginary => {"imaginary".to_owned()}
+ purple => {"purple".to_owned()}
+ orange => {"orange".to_owned()}
}
}
fn get_color_if(color: color) -> ~str {
- if color == red {~"red"}
- else if color == green {~"green"}
- else if color == blue {~"blue"}
- else if color == black {~"black"}
- else if color == white {~"white"}
- else if color == imaginary {~"imaginary"}
- else if color == purple {~"purple"}
- else if color == orange {~"orange"}
- else {~"unknown"}
+ if color == red {"red".to_owned()}
+ else if color == green {"green".to_owned()}
+ else if color == blue {"blue".to_owned()}
+ else if color == black {"black".to_owned()}
+ else if color == white {"white".to_owned()}
+ else if color == imaginary {"imaginary".to_owned()}
+ else if color == purple {"purple".to_owned()}
+ else if color == orange {"orange".to_owned()}
+ else {"unknown".to_owned()}
}
// use of tail calls causes arg slot leaks, issue #160.
fn inner(dummy: ~str, b: bool) { if b { return inner(dummy, false); } }
-pub fn main() { inner(~"hi", true); }
+pub fn main() { inner("hi".to_owned(), true); }
let mut a;
let mut b;
a = rx.recv();
- assert!(a == ~"A");
+ assert!(a == "A".to_owned());
println!("{:?}", a);
b = rx.recv();
- assert!(b == ~"B");
+ assert!(b == "B".to_owned());
println!("{:?}", b);
}
let _child = task::spawn(proc() { start(&tx) });
let mut c = rx.recv();
- c.send(~"A");
- c.send(~"B");
+ c.send("A".to_owned());
+ c.send("B".to_owned());
task::deschedule();
}
fn test_str() {
let (tx, rx) = channel();
- let s0 = ~"test";
+ let s0 = "test".to_owned();
tx.send(s0);
let s1 = rx.recv();
assert_eq!(s1[0], 't' as u8);
use std::task;
pub fn main() {
- task::spawn(proc() child(~"Hello") );
+ task::spawn(proc() child("Hello".to_owned()) );
}
fn child(_s: ~str) {
let tests = __test::TESTS;
assert!(
- tests.iter().any(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
+ tests.iter().any(|t| t.desc.name.to_str() == "shouldignore".to_owned() &&
+ t.desc.ignore));
assert!(
- tests.iter().any(|t| t.desc.name.to_str() == ~"shouldnotignore" && !t.desc.ignore));
+ tests.iter().any(|t| t.desc.name.to_str() == "shouldnotignore".to_owned() &&
+ !t.desc.ignore));
}
}
pub fn main() {
- let catte = Catte { num_whiskers: 7, name: ~"alonzo_church" };
- let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: ~"alan_turing" };
- let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: ~"albert_einstein" };
- let fishe = Goldfyshe { swim_speed: 998, name: ~"alec_guinness" };
+ let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_owned() };
+ let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_owned() };
+ let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_owned() };
+ let fishe = Goldfyshe { swim_speed: 998, name: "alec_guinness".to_owned() };
let arc = Arc::new(vec!(~catte as ~Pet:Share+Send,
~dogge1 as ~Pet:Share+Send,
~fishe as ~Pet:Share+Send,
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> ~str {
match *self {
- None => { ~"none" }
- Some(ref t) => { ~"some(" + t.to_str_() + ~")" }
+ None => { "none".to_owned() }
+ Some(ref t) => { "some(".to_owned() + t.to_str_() + ")".to_owned() }
}
}
}
let t2 = Tree(@RefCell::new(TreeR{left: Some(t1),
right: Some(t1),
val: ~2 as ~to_str:Send}));
- let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
+ let expected = "[2, some([1, none, none]), some([1, none, none])]".to_owned();
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
fn to_string(&self) -> ~str { self.clone() }
}
impl to_str for () {
- fn to_string(&self) -> ~str { ~"()" }
+ fn to_string(&self) -> ~str { "()".to_owned() }
}
trait map<T> {
}
fn foo<U, T: map<U>>(x: T) -> Vec<~str> {
- x.map(|_e| ~"hi" )
+ x.map(|_e| "hi".to_owned() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<~str> {
x.map(|_e| _e.to_string() )
}
pub fn main() {
- assert_eq!(foo(vec!(1)), vec!(~"hi"));
- assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!(~"4", ~"5"));
- assert_eq!(bar::<~str, Vec<~str> >(vec!(~"x", ~"y")), vec!(~"x", ~"y"));
- assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!(~"()"));
+ assert_eq!(foo(vec!(1)), vec!("hi".to_owned()));
+ assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_owned(), "5".to_owned()));
+ assert_eq!(bar::<~str, Vec<~str> >(vec!("x".to_owned(), "y".to_owned())),
+ vec!("x".to_owned(), "y".to_owned()));
+ assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_owned()));
}
}
pub fn main() {
- assert!(1.to_string() == ~"1");
- assert!((vec!(2, 3, 4)).to_string() == ~"[2, 3, 4]");
+ assert!(1.to_string() == "1".to_owned());
+ assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_owned());
fn indirect<T:to_str>(x: T) -> ~str {
x.to_string() + "!"
}
- assert!(indirect(vec!(10, 20)) == ~"[10, 20]!");
+ assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_owned());
fn indirect2<T:to_str>(x: T) -> ~str {
indirect(x)
}
- assert!(indirect2(vec!(1)) == ~"[1]!");
+ assert!(indirect2(vec!(1)) == "[1]!".to_owned());
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
- assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi"));
+ assert_eq!(Some("hi".to_owned()).do_get2(), ("hi".to_owned(), "hi".to_owned()));
}
pub fn main() {
let q = Quux;
- assert_eq!(q.bar(), ~"test");
+ assert_eq!(q.bar(), "test".to_owned());
}
fn empty_pointy() -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
- d : make_uniq_closure(~"hi")
+ d : make_uniq_closure("hi".to_owned())
})
}
assert_eq!(pi as int, '\u03a0' as int);
assert_eq!('\x0a' as int, '\n' as int);
- let bhutan: ~str = ~"འབྲུག་ཡུལ།";
- let japan: ~str = ~"日本";
- let uzbekistan: ~str = ~"Ўзбекистон";
- let austria: ~str = ~"Österreich";
+ let bhutan: ~str = "འབྲུག་ཡུལ།".to_owned();
+ let japan: ~str = "日本".to_owned();
+ let uzbekistan: ~str = "Ўзбекистон".to_owned();
+ let austria: ~str = "Österreich".to_owned();
let bhutan_e: ~str =
- ~"\u0f60\u0f56\u0fb2\u0f74\u0f42\u0f0b\u0f61\u0f74\u0f63\u0f0d";
- let japan_e: ~str = ~"\u65e5\u672c";
+ "\u0f60\u0f56\u0fb2\u0f74\u0f42\u0f0b\u0f61\u0f74\u0f63\u0f0d".to_owned();
+ let japan_e: ~str = "\u65e5\u672c".to_owned();
let uzbekistan_e: ~str =
- ~"\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e\u043d";
- let austria_e: ~str = ~"\u00d6sterreich";
+ "\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e\u043d".to_owned();
+ let austria_e: ~str = "\u00d6sterreich".to_owned();
let oo: char = 'Ö';
assert_eq!(oo as int, 0xd6);
fn boldly_go(_crew_member: crew_of_enterprise_d, _where: ~str) { }
-pub fn main() { boldly_go(worf, ~"where no one has gone before"); }
+pub fn main() { boldly_go(worf, "where no one has gone before".to_owned()); }
pub fn main() {
let x = [
- Foo { string: ~"foo" },
- Foo { string: ~"bar" },
- Foo { string: ~"baz" }
+ Foo { string: "foo".to_owned() },
+ Foo { string: "bar".to_owned() },
+ Foo { string: "baz".to_owned() }
];
match x {
[ref first, ..tail] => {
- assert!(first.string == ~"foo");
+ assert!(first.string == "foo".to_owned());
assert_eq!(tail.len(), 2);
- assert!(tail[0].string == ~"bar");
- assert!(tail[1].string == ~"baz");
+ assert!(tail[0].string == "bar".to_owned());
+ assert!(tail[1].string == "baz".to_owned());
match tail {
[Foo { .. }, _, Foo { .. }, .. _tail] => {
// except according to those terms.
pub fn main() {
- assert_eq!((vec!(0, 1)).to_str(), ~"[0, 1]");
- assert_eq!((&[1, 2]).to_str(), ~"[1, 2]");
+ assert_eq!((vec!(0, 1)).to_str(), "[0, 1]".to_owned());
+ assert_eq!((&[1, 2]).to_str(), "[1, 2]".to_owned());
let foo = vec!(3, 4);
let bar = &[4, 5];
- assert_eq!(foo.to_str(), ~"[3, 4]");
- assert_eq!(bar.to_str(), ~"[4, 5]");
+ assert_eq!(foo.to_str(), "[3, 4]".to_owned());
+ assert_eq!(bar.to_str(), "[4, 5]".to_owned());
}