We were still generating compiler docs even with --disable-docs passed.
cc @pnkfelix
CFG_CPUTYPE=arm
;;
+ armv7l)
+ CFG_CPUTYPE=arm
+ CFG_OSTYPE="${CFG_OSTYPE}eabihf"
+ ;;
+
x86_64 | x86-64 | x64 | amd64)
CFG_CPUTYPE=x86_64
;;
opt optimize-cxx 1 "build optimized C++ code"
opt optimize-llvm 1 "build optimized LLVM"
opt optimize-tests 1 "build tests with optimizations"
+opt libcpp 1 "build with clang's libcpp"
opt llvm-assertions 1 "build LLVM with assertions"
opt debug 1 "build with extra debug fun"
opt ratchet-bench 0 "ratchet benchmarks"
if [ -z "$CC" ]
then
CFG_CC="clang"
+ CFG_CXX="clang++"
fi
;;
(*)
case "$CFG_CC" in
("ccache clang")
- LLVM_CXX_32="ccache clang++ -m32 -Qunused-arguments"
- LLVM_CC_32="ccache clang -m32 -Qunused-arguments"
+ LLVM_CXX_32="ccache clang++ -Qunused-arguments"
+ LLVM_CC_32="ccache clang -Qunused-arguments"
LLVM_CXX_64="ccache clang++ -Qunused-arguments"
LLVM_CC_64="ccache clang -Qunused-arguments"
- LLVM_OPTS="$LLVM_OPTS --enable-libcpp"
;;
("clang")
- LLVM_CXX_32="clang++ -m32 -Qunused-arguments"
- LLVM_CC_32="clang -m32 -Qunused-arguments"
+ LLVM_CXX_32="clang++ -Qunused-arguments"
+ LLVM_CC_32="clang -Qunused-arguments"
LLVM_CXX_64="clang++ -Qunused-arguments"
LLVM_CC_64="clang -Qunused-arguments"
- LLVM_OPTS="$LLVM_OPTS --enable-libcpp"
;;
("ccache gcc")
- LLVM_CXX_32="ccache g++ -m32"
- LLVM_CC_32="ccache gcc -m32"
+ LLVM_CXX_32="ccache g++"
+ LLVM_CC_32="ccache gcc"
LLVM_CXX_64="ccache g++"
LLVM_CC_64="ccache gcc"
;;
("gcc")
- LLVM_CXX_32="g++ -m32"
- LLVM_CC_32="gcc -m32"
+ LLVM_CXX_32="g++"
+ LLVM_CC_32="gcc"
LLVM_CXX_64="g++"
LLVM_CC_64="gcc"
(*)
msg "inferring LLVM_CXX/CC from CXX/CC = $CXX/$CC"
- LLVM_CXX_32="$CXX -m32"
- LLVM_CC_32="$CC -m32"
+ LLVM_CXX_32="$CXX"
+ LLVM_CC_32="$CC"
LLVM_CXX_64="$CXX"
LLVM_CC_64="$CC"
;;
esac
- LLVM_CFLAGS_32="-m32"
- LLVM_CXXFLAGS_32="-m32"
- LLVM_LDFLAGS_32="-m32"
+ case "$CFG_CPUTYPE" in
+ (x86*)
+ LLVM_CXX_32="$LLVM_CXX_32 -m32"
+ LLVM_CC_32="$LLVM_CC_32 -m32"
+
+ LLVM_CFLAGS_32="-m32"
+ LLVM_CXXFLAGS_32="-m32"
+ LLVM_LDFLAGS_32="-m32"
+
+ LLVM_CFLAGS_64=""
+ LLVM_CXXFLAGS_64=""
+ LLVM_LDFLAGS_64=""
+
+ LLVM_CXX_32="$LLVM_CXX_32 -m32"
+ LLVM_CC_32="$LLVM_CC_32 -m32"
+ ;;
+
+ (*)
+ LLVM_CFLAGS_32=""
+ LLVM_CXXFLAGS_32=""
+ LLVM_LDFLAGS_32=""
- LLVM_CFLAGS_64=""
- LLVM_CXXFLAGS_64=""
- LLVM_LDFLAGS_64=""
+ LLVM_CFLAGS_64=""
+ LLVM_CXXFLAGS_64=""
+ LLVM_LDFLAGS_64=""
+ ;;
+ esac
if echo $t | grep -q x86_64
then
CXXFLAGS=$LLVM_CXXFLAGS
LDFLAGS=$LLVM_LDFLAGS
+ if [ "$CFG_DISABLE_LIBCPP" != 1 ]; then
+ LLVM_OPTS="$LLVM_OPTS --enable-libcpp"
+ fi
+
LLVM_FLAGS="$LLVM_TARGETS $LLVM_OPTS $LLVM_BUILD \
$LLVM_HOST $LLVM_TARGET --with-python=$CFG_PYTHON"
TARGET_CRATES := libc std green rustuv native flate arena glob term semver \
uuid serialize sync getopts collections num test time rand \
- workcache url log regex graphviz core rlibc alloc
+ workcache url log regex graphviz core rlibc alloc debug
HOST_CRATES := syntax rustc rustdoc fourcc hexfloat regex_macros fmt_macros
CRATES := $(TARGET_CRATES) $(HOST_CRATES)
TOOLS := compiletest rustdoc rustc
DEPS_core :=
DEPS_rlibc :=
DEPS_alloc := core libc native:jemalloc
+DEPS_debug := std
DEPS_std := core libc alloc native:rustrt native:backtrace
DEPS_graphviz := std
DEPS_green := std rand native:context_switch
DEPS_rustuv := std native:uv native:uv_support
DEPS_native := std
-DEPS_syntax := std term serialize collections log fmt_macros
+DEPS_syntax := std term serialize collections log fmt_macros debug
DEPS_rustc := syntax native:rustllvm flate arena serialize sync getopts \
- collections time log graphviz
+ collections time log graphviz debug
DEPS_rustdoc := rustc native:hoedown serialize sync getopts collections \
- test time
+ test time debug
DEPS_flate := std native:miniz
DEPS_arena := std collections
DEPS_graphviz := std
DEPS_uuid := std serialize rand
DEPS_sync := std alloc
DEPS_getopts := std
-DEPS_collections := std rand
+DEPS_collections := std rand debug
DEPS_fourcc := syntax std
DEPS_hexfloat := syntax std
DEPS_num := std rand
pub fn main() {
let args = os::args();
let config = parse_config(args.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect());
log_config(&config);
run_tests(&config);
Config {
compile_lib_path: matches.opt_str("compile-lib-path")
.unwrap()
- .to_strbuf(),
- run_lib_path: matches.opt_str("run-lib-path").unwrap().to_strbuf(),
+ .to_string(),
+ run_lib_path: matches.opt_str("run-lib-path").unwrap().to_string(),
rustc_path: opt_path(matches, "rustc-path"),
clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
- stage_id: matches.opt_str("stage-id").unwrap().to_strbuf(),
+ stage_id: matches.opt_str("stage-id").unwrap().to_string(),
mode: FromStr::from_str(matches.opt_str("mode")
.unwrap()
.as_slice()).expect("invalid mode"),
ratchet_noise_percent:
matches.opt_str("ratchet-noise-percent")
.and_then(|s| from_str::<f64>(s.as_slice())),
- runtool: matches.opt_str("runtool").map(|x| x.to_strbuf()),
+ runtool: matches.opt_str("runtool").map(|x| x.to_string()),
host_rustcflags: matches.opt_str("host-rustcflags")
- .map(|x| x.to_strbuf()),
+ .map(|x| x.to_string()),
target_rustcflags: matches.opt_str("target-rustcflags")
- .map(|x| x.to_strbuf()),
+ .map(|x| x.to_string()),
jit: matches.opt_present("jit"),
- target: opt_str2(matches.opt_str("target").map(|x| x.to_strbuf())),
- host: opt_str2(matches.opt_str("host").map(|x| x.to_strbuf())),
+ target: opt_str2(matches.opt_str("target").map(|x| x.to_string())),
+ host: opt_str2(matches.opt_str("host").map(|x| x.to_string())),
android_cross_path: opt_path(matches, "android-cross-path"),
adb_path: opt_str2(matches.opt_str("adb-path")
- .map(|x| x.to_strbuf())),
+ .map(|x| x.to_string())),
adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")
- .map(|x| x.to_strbuf())),
+ .map(|x| x.to_string())),
adb_device_status:
"arm-linux-androideabi" ==
opt_str2(matches.opt_str("target")
- .map(|x| x.to_strbuf())).as_slice() &&
+ .map(|x| x.to_string())).as_slice() &&
"(none)" !=
opt_str2(matches.opt_str("adb-test-dir")
- .map(|x| x.to_strbuf())).as_slice() &&
+ .map(|x| x.to_string())).as_slice() &&
!opt_str2(matches.opt_str("adb-test-dir")
- .map(|x| x.to_strbuf())).is_empty(),
+ .map(|x| x.to_string())).is_empty(),
lldb_python_dir: matches.opt_str("lldb-python-dir")
- .map(|x| x.to_strbuf()),
+ .map(|x| x.to_string()),
test_shard: test::opt_shard(matches.opt_str("test-shard")
- .map(|x| x.to_strbuf())),
+ .map(|x| x.to_string())),
verbose: matches.opt_present("verbose")
}
}
opt_str(&config.filter
.as_ref()
.map(|re| {
- re.to_str().into_strbuf()
+ re.to_str().into_string()
}))));
logv(c, format_strbuf!("runtool: {}", opt_str(&config.runtool)));
logv(c, format_strbuf!("host-rustcflags: {}",
logv(c, format_strbuf!("adb_device_status: {}",
config.adb_device_status));
match config.test_shard {
- None => logv(c, "test_shard: (all)".to_strbuf()),
+ None => logv(c, "test_shard: (all)".to_string()),
Some((a,b)) => logv(c, format_strbuf!("test_shard: {}.{}", a, b))
}
logv(c, format_strbuf!("verbose: {}", config.verbose));
pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
- None => "(none)".to_strbuf(),
+ None => "(none)".to_string(),
Some(s) => s,
}
}
// Pretty-printer does not work with .rc files yet
let valid_extensions =
match config.mode {
- Pretty => vec!(".rs".to_owned()),
- _ => vec!(".rc".to_owned(), ".rs".to_owned())
+ Pretty => vec!(".rs".to_string()),
+ _ => vec!(".rc".to_string(), ".rs".to_string())
};
- let invalid_prefixes = vec!(".".to_owned(), "#".to_owned(), "~".to_owned());
+ let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
let name = testfile.filename_str().unwrap();
let mut valid = false;
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
- let testfile = testfile.as_str().unwrap().to_strbuf();
+ let testfile = testfile.as_str().unwrap().to_string();
test::DynTestFn(proc() {
runtest::run(config, testfile)
})
pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
- let testfile = testfile.as_str().unwrap().to_strbuf();
+ let testfile = testfile.as_str().unwrap().to_string();
test::DynMetricFn(proc(mm) {
runtest::run_metrics(config, testfile, mm)
})
fn parse_expected(line_num: uint, line: &str, re: &Regex) -> Option<ExpectedError> {
re.captures(line).and_then(|caps| {
let adjusts = caps.name("adjusts").len();
- let kind = caps.name("kind").to_ascii().to_lower().into_str().to_strbuf();
- let msg = caps.name("msg").trim().to_strbuf();
+ let kind = caps.name("kind").to_ascii().to_lower().into_str().to_string();
+ let msg = caps.name("msg").trim().to_string();
debug!("line={} kind={} msg={}", line_num, kind, msg);
Some(ExpectedError {
}
fn parse_error_pattern(line: &str) -> Option<String> {
- parse_name_value_directive(line, "error-pattern".to_strbuf())
+ parse_name_value_directive(line, "error-pattern".to_string())
}
fn parse_aux_build(line: &str) -> Option<String> {
- parse_name_value_directive(line, "aux-build".to_strbuf())
+ parse_name_value_directive(line, "aux-build".to_string())
}
fn parse_compile_flags(line: &str) -> Option<String> {
- parse_name_value_directive(line, "compile-flags".to_strbuf())
+ parse_name_value_directive(line, "compile-flags".to_string())
}
fn parse_run_flags(line: &str) -> Option<String> {
- parse_name_value_directive(line, "run-flags".to_strbuf())
+ parse_name_value_directive(line, "run-flags".to_string())
}
fn parse_check_line(line: &str) -> Option<String> {
- parse_name_value_directive(line, "check".to_strbuf())
+ parse_name_value_directive(line, "check".to_string())
}
fn parse_force_host(line: &str) -> bool {
}
fn parse_exec_env(line: &str) -> Option<(String, String)> {
- parse_name_value_directive(line, "exec-env".to_strbuf()).map(|nv| {
+ parse_name_value_directive(line, "exec-env".to_string()).map(|nv| {
// nv is either FOO or FOO=BAR
let mut strs: Vec<String> = nv.as_slice()
.splitn('=', 1)
- .map(|s| s.to_strbuf())
+ .map(|s| s.to_string())
.collect();
match strs.len() {
- 1u => (strs.pop().unwrap(), "".to_strbuf()),
+ 1u => (strs.pop().unwrap(), "".to_string()),
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".to_strbuf()) {
+ match parse_name_value_directive(line, "pp-exact".to_string()) {
Some(s) => Some(Path::new(s)),
None => {
if parse_name_directive(line, "pp-exact") {
match line.find_str(keycolon.as_slice()) {
Some(colon) => {
let value = line.slice(colon + keycolon.len(),
- line.len()).to_strbuf();
+ line.len()).to_string();
debug!("{}: {}", directive, value);
Some(value)
}
fn target_env(lib_path: &str, prog: &str) -> Vec<(String, String)> {
let prog = if cfg!(windows) {prog.slice_to(prog.len() - 4)} else {prog};
- let mut aux_path = prog.to_strbuf();
+ let mut aux_path = prog.to_string();
aux_path.push_str(".libaux");
// Need to be sure to put both the lib_path and the aux path in the dylib
// Remove the previous dylib search path var
let var = DynamicLibrary::envvar();
let mut env: Vec<(String,String)> =
- os::env().move_iter().map(|(a,b)|(a.to_strbuf(), b.to_strbuf())).collect();
+ os::env().move_iter().map(|(a,b)|(a.to_string(), b.to_string())).collect();
match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
Some(i) => { env.remove(i); }
None => {}
// Add the new dylib search path var
let newpath = DynamicLibrary::create_path(path.as_slice());
- env.push((var.to_strbuf(),
- str::from_utf8(newpath.as_slice()).unwrap().to_strbuf()));
+ env.push((var.to_string(),
+ str::from_utf8(newpath.as_slice()).unwrap().to_string()));
return env;
}
Some(Result {
status: status,
- out: str::from_utf8(output.as_slice()).unwrap().to_strbuf(),
- err: str::from_utf8(error.as_slice()).unwrap().to_strbuf()
+ out: str::from_utf8(output.as_slice()).unwrap().to_string(),
+ err: str::from_utf8(error.as_slice()).unwrap().to_string()
})
},
Err(..) => None
let proc_res = compile_test(config, props, testfile);
if proc_res.status.success() {
- fatal_ProcRes("compile-fail test compiled successfully!".to_strbuf(),
+ fatal_ProcRes("compile-fail test compiled successfully!".to_string(),
&proc_res);
}
if !expected_errors.is_empty() {
if !props.error_patterns.is_empty() {
fatal("both error pattern and expected errors \
- specified".to_strbuf());
+ specified".to_string());
}
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!".to_strbuf(), &proc_res);
+ fatal_ProcRes("compilation failed!".to_string(), &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!".to_strbuf(),
+ fatal_ProcRes("run-fail test isn't valgrind-clean!".to_string(),
&proc_res);
}
let mut proc_res = compile_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes("compilation failed!".to_strbuf(), &proc_res);
+ fatal_ProcRes("compilation failed!".to_string(), &proc_res);
}
proc_res = exec_compiled_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes("test run failed!".to_strbuf(), &proc_res);
+ fatal_ProcRes("test run failed!".to_string(), &proc_res);
}
} else {
let proc_res = jit_test(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes("jit failed!".to_strbuf(), &proc_res);
+ fatal_ProcRes("jit failed!".to_string(), &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".to_strbuf());
+ logv(config, "testing for exact pretty-printing".to_string());
} else {
- logv(config, "testing for converging pretty-printing".to_strbuf());
+ logv(config, "testing for converging pretty-printing".to_string());
}
let rounds =
match props.pp_exact { Some(_) => 1, None => 2 };
let src = File::open(testfile).read_to_end().unwrap();
- let src = str::from_utf8(src.as_slice()).unwrap().to_strbuf();
+ let src = str::from_utf8(src.as_slice()).unwrap().to_string();
let mut srcs = vec!(src);
let mut round = 0;
let proc_res = print_source(config,
props,
testfile,
- (*srcs.get(round)).to_strbuf(),
+ (*srcs.get(round)).to_string(),
"normal");
if !proc_res.status.success() {
Some(ref file) => {
let filepath = testfile.dir_path().join(file);
let s = File::open(&filepath).read_to_end().unwrap();
- str::from_utf8(s.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(s.as_slice()).unwrap().to_string()
}
None => { (*srcs.get(srcs.len() - 2u)).clone() }
};
if props.pp_exact.is_some() {
// Now we have to care about line endings
- let cr = "\r".to_strbuf();
- actual = actual.replace(cr.as_slice(), "").to_strbuf();
- expected = expected.replace(cr.as_slice(), "").to_strbuf();
+ let cr = "\r".to_string();
+ actual = actual.replace(cr.as_slice(), "").to_string();
+ expected = expected.replace(cr.as_slice(), "").to_string();
}
compare_source(expected.as_slice(), actual.as_slice());
let proc_res = typecheck_source(config, props, testfile, actual);
if !proc_res.status.success() {
- fatal_ProcRes("pretty-printed source does not typecheck".to_strbuf(),
+ fatal_ProcRes("pretty-printed source does not typecheck".to_string(),
&proc_res);
}
if props.no_pretty_expanded { return }
make_pp_args(config,
props,
testfile,
- pretty_type.to_strbuf()),
+ pretty_type.to_string()),
props.exec_env.clone(),
config.compile_lib_path.as_slice(),
Some(src))
pretty_type: String) -> ProcArgs {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let mut args = vec!("-".to_strbuf(),
- "--pretty".to_strbuf(),
+ let mut args = vec!("-".to_string(),
+ "--pretty".to_string(),
pretty_type,
format_strbuf!("--target={}", config.target),
- "-L".to_strbuf(),
- aux_dir.as_str().unwrap().to_strbuf());
+ "-L".to_string(),
+ aux_dir.as_str().unwrap().to_string());
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.push_all_move(split_maybe_args(&props.compile_flags));
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_strbuf(),
+ prog: config.rustc_path.as_str().unwrap().to_string(),
args: args,
};
}
fn compare_source(expected: &str, actual: &str) {
if expected != actual {
error("pretty-printed source does not match expected \
- source".to_strbuf());
+ source".to_string());
println!("\n\
expected:\n\
------------------------------------------\n\
config.target.as_slice()
};
// FIXME (#9639): This needs to handle non-utf8 paths
- let mut args = vec!("-".to_strbuf(),
- "--no-trans".to_strbuf(),
- "--crate-type=lib".to_strbuf(),
+ let mut args = vec!("-".to_string(),
+ "--no-trans".to_string(),
+ "--crate-type=lib".to_string(),
format_strbuf!("--target={}", target),
- "-L".to_strbuf(),
- config.build_base.as_str().unwrap().to_strbuf(),
- "-L".to_strbuf(),
- aux_dir.as_str().unwrap().to_strbuf());
+ "-L".to_string(),
+ config.build_base.as_str().unwrap().to_string(),
+ "-L".to_string(),
+ aux_dir.as_str().unwrap().to_string());
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.push_all_move(split_maybe_args(&props.compile_flags));
// FIXME (#9639): This needs to handle non-utf8 paths
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_strbuf(),
+ prog: config.rustc_path.as_str().unwrap().to_string(),
args: args,
};
}
let config = &mut config;
let DebuggerCommands { commands, check_lines, .. } = parse_debugger_commands(testfile, "gdb");
- let mut cmds = commands.connect("\n").to_strbuf();
+ let mut cmds = commands.connect("\n").to_string();
// compile test file (it shoud have 'compile-flags:-g' in the header)
let compiler_run_result = compile_test(config, props, testfile);
if !compiler_run_result.status.success() {
- fatal_ProcRes("compilation failed!".to_strbuf(), &compiler_run_result);
+ fatal_ProcRes("compilation failed!".to_string(), &compiler_run_result);
}
let exe_file = make_exe_name(config, testfile);
match config.target.as_slice() {
"arm-linux-androideabi" => {
- cmds = cmds.replace("run", "continue").to_strbuf();
+ cmds = cmds.replace("run", "continue").to_string();
// write debugger script
- let script_str = ["set charset UTF-8".to_strbuf(),
+ let script_str = ["set charset UTF-8".to_string(),
format_strbuf!("file {}",
exe_file.as_str()
.unwrap()
- .to_strbuf()),
- "target remote :5039".to_strbuf(),
+ .to_string()),
+ "target remote :5039".to_string(),
cmds,
- "quit".to_strbuf()].connect("\n");
+ "quit".to_string()].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config,
testfile,
procsrv::run("",
config.adb_path.as_slice(),
[
- "push".to_strbuf(),
- exe_file.as_str().unwrap().to_strbuf(),
+ "push".to_string(),
+ exe_file.as_str().unwrap().to_string(),
config.adb_test_dir.clone()
],
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`",
config.adb_path));
procsrv::run("",
config.adb_path.as_slice(),
[
- "forward".to_strbuf(),
- "tcp:5039".to_strbuf(),
- "tcp:5039".to_strbuf()
+ "forward".to_string(),
+ "tcp:5039".to_string(),
+ "tcp:5039".to_string()
],
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
let adb_arg = format_strbuf!("export LD_LIBRARY_PATH={}; \
config.adb_path
.as_slice(),
[
- "shell".to_strbuf(),
+ "shell".to_string(),
adb_arg.clone()
],
- vec!(("".to_strbuf(),
- "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(),
+ "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`",
config.adb_path));
loop {
}
let tool_path = match config.android_cross_path.as_str() {
- Some(x) => x.to_strbuf(),
- None => fatal("cannot find android cross path".to_strbuf())
+ Some(x) => x.to_string(),
+ None => fatal("cannot find android cross path".to_string())
};
let debugger_script = make_out_name(config, testfile, "debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
let debugger_opts =
- vec!("-quiet".to_strbuf(),
- "-batch".to_strbuf(),
- "-nx".to_strbuf(),
+ vec!("-quiet".to_string(),
+ "-batch".to_string(),
+ "-nx".to_string(),
format_strbuf!("-command={}",
debugger_script.as_str().unwrap()));
} = procsrv::run("",
gdb_path.as_slice(),
debugger_opts.as_slice(),
- vec!(("".to_strbuf(), "".to_strbuf())),
+ vec!(("".to_string(), "".to_string())),
None)
.expect(format_strbuf!("failed to exec `{}`", gdb_path));
let cmdline = {
_=> {
// write debugger script
let script_str = [
- "set charset UTF-8".to_strbuf(),
+ "set charset UTF-8".to_string(),
cmds,
- "quit\n".to_strbuf()
+ "quit\n".to_string()
].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config,
// run debugger script with gdb
#[cfg(windows)]
fn debugger() -> String {
- "gdb.exe".to_strbuf()
+ "gdb.exe".to_string()
}
#[cfg(unix)]
fn debugger() -> String {
- "gdb".to_strbuf()
+ "gdb".to_string()
}
let debugger_script = make_out_name(config, testfile, "debugger.script");
// FIXME (#9639): This needs to handle non-utf8 paths
let debugger_opts =
- vec!("-quiet".to_strbuf(),
- "-batch".to_strbuf(),
- "-nx".to_strbuf(),
+ vec!("-quiet".to_string(),
+ "-batch".to_string(),
+ "-nx".to_string(),
format_strbuf!("-command={}",
debugger_script.as_str().unwrap()),
- exe_file.as_str().unwrap().to_strbuf());
+ exe_file.as_str().unwrap().to_string());
proc_args = ProcArgs {
prog: debugger(),
args: debugger_opts,
}
if !debugger_run_result.status.success() {
- fatal("gdb failed to execute".to_strbuf());
+ fatal("gdb failed to execute".to_string());
}
check_debugger_output(&debugger_run_result, check_lines.as_slice());
if config.lldb_python_dir.is_none() {
fatal("Can't run LLDB test because LLDB's python path is not \
- set.".to_strbuf());
+ set.".to_string());
}
let mut config = Config {
// compile test file (it shoud have 'compile-flags:-g' in the header)
let compile_result = compile_test(config, props, testfile);
if !compile_result.status.success() {
- fatal_ProcRes("compilation failed!".to_strbuf(), &compile_result);
+ fatal_ProcRes("compilation failed!".to_string(), &compile_result);
}
let exe_file = make_exe_name(config, testfile);
let debugger_run_result = run_lldb(config, &exe_file, &debugger_script);
if !debugger_run_result.status.success() {
- fatal_ProcRes("Error while running LLDB".to_strbuf(),
+ fatal_ProcRes("Error while running LLDB".to_string(),
&debugger_run_result);
}
process.wait_with_output().unwrap();
(status,
- str::from_utf8(output.as_slice()).unwrap().to_strbuf(),
- str::from_utf8(error.as_slice()).unwrap().to_strbuf())
+ str::from_utf8(output.as_slice()).unwrap().to_string(),
+ str::from_utf8(error.as_slice()).unwrap().to_string())
},
Err(e) => {
fatal(format_strbuf!("Failed to setup Python process for \
header::parse_name_value_directive(
line.as_slice(),
- command_directive.to_strbuf()).map(|cmd| {
+ command_directive.to_string()).map(|cmd| {
commands.push(cmd)
});
header::parse_name_value_directive(
line.as_slice(),
- check_directive.to_strbuf()).map(|cmd| {
+ check_directive.to_string()).map(|cmd| {
check_lines.push(cmd)
});
}
// Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
let options_to_remove = [
- "-O".to_strbuf(),
- "-g".to_strbuf(),
- "--debuginfo".to_strbuf()
+ "-O".to_string(),
+ "-g".to_string(),
+ "--debuginfo".to_string()
];
let new_options =
split_maybe_args(options).move_iter()
.filter(|x| !options_to_remove.contains(x))
.collect::<Vec<String>>()
.connect(" ")
- .to_strbuf();
+ .to_string();
Some(new_options)
}
s.as_slice()
.trim()
.split_str("[...]")
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect()
}).collect();
// check if each line in props.check_lines appears in the
}
if proc_res.status.success() {
- fatal("process did not return an error status".to_strbuf());
+ fatal("process did not return an error status".to_string());
}
let mut next_err_idx = 0u;
for pattern in missing_patterns.iter() {
error(format_strbuf!("error pattern '{}' not found!", *pattern));
}
- fatal_ProcRes("multiple error patterns not found".to_strbuf(),
+ fatal_ProcRes("multiple error patterns not found".to_string(),
proc_res);
}
}
fn check_no_compiler_crash(proc_res: &ProcRes) {
for line in proc_res.stderr.as_slice().lines() {
if line.starts_with("error: internal compiler error:") {
- fatal_ProcRes("compiler encountered internal error".to_strbuf(),
+ fatal_ProcRes("compiler encountered internal error".to_string(),
proc_res);
}
}
expected_errors.len(), false);
if proc_res.status.success() {
- fatal("process did not return an error status".to_strbuf());
+ fatal("process did not return an error status".to_string());
}
let prefixes = expected_errors.iter().map(|ee| {
c
}
} ).collect();
- str::from_chars(c.as_slice()).to_strbuf()
+ str::from_chars(c.as_slice()).to_string()
}
#[cfg(target_os = "win32")]
}
fn jit_test(config: &Config, props: &TestProps, testfile: &Path) -> ProcRes {
- compile_test_(config, props, testfile, ["--jit".to_strbuf()])
+ compile_test_(config, props, testfile, ["--jit".to_string()])
}
fn compile_test_(config: &Config, props: &TestProps,
testfile: &Path, extra_args: &[String]) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let link_args = vec!("-L".to_strbuf(),
- aux_dir.as_str().unwrap().to_strbuf());
+ let link_args = vec!("-L".to_string(),
+ aux_dir.as_str().unwrap().to_string());
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".to_owned(), aux_dir.as_str().unwrap().to_owned());
+ let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
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".to_strbuf())
+ vec!("--crate-type=dylib".to_string())
};
let aux_args =
make_compile_args(config,
&aux_props,
crate_type.append(
extra_link_args.iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice()),
|a,b| {
config.target.as_slice()
};
// FIXME (#9639): This needs to handle non-utf8 paths
- let mut args = vec!(testfile.as_str().unwrap().to_strbuf(),
- "-L".to_strbuf(),
- config.build_base.as_str().unwrap().to_strbuf(),
+ let mut args = vec!(testfile.as_str().unwrap().to_string(),
+ "-L".to_string(),
+ config.build_base.as_str().unwrap().to_string(),
format_strbuf!("--target={}", target));
args.push_all(extras.as_slice());
if !props.no_prefer_dynamic {
- args.push("-C".to_strbuf());
- args.push("prefer-dynamic".to_strbuf());
+ args.push("-C".to_string());
+ args.push("prefer-dynamic".to_string());
}
let path = match xform_file {
ThisFile(path) => {
- args.push("-o".to_strbuf());
+ args.push("-o".to_string());
path
}
ThisDirectory(path) => {
- args.push("--out-dir".to_strbuf());
+ args.push("--out-dir".to_string());
path
}
};
- args.push(path.as_str().unwrap().to_strbuf());
+ args.push(path.as_str().unwrap().to_string());
if props.force_host {
args.push_all_move(split_maybe_args(&config.host_rustcflags));
} else {
}
args.push_all_move(split_maybe_args(&props.compile_flags));
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_strbuf(),
+ prog: config.rustc_path.as_str().unwrap().to_string(),
args: args,
};
}
let exe_file = make_exe_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- args.push(exe_file.as_str().unwrap().to_strbuf());
+ args.push(exe_file.as_str().unwrap().to_string());
// Add the arguments in the run_flags directive
args.push_all_move(split_maybe_args(&props.run_flags));
if s.is_whitespace() {
None
} else {
- Some(s.to_strbuf())
+ Some(s.to_string())
}
}).collect()
}
let mut tvec: Vec<String> = args.prog
.as_slice()
.split('/')
- .map(|ts| ts.to_strbuf())
+ .map(|ts| ts.to_string())
.collect();
let prog_short = tvec.pop().unwrap();
let copy_result = procsrv::run("",
config.adb_path.as_slice(),
[
- "push".to_strbuf(),
+ "push".to_string(),
args.prog.clone(),
config.adb_test_dir.clone()
],
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
if config.verbose {
let mut runargs = Vec::new();
// run test via adb_run_wrapper
- runargs.push("shell".to_strbuf());
+ runargs.push("shell".to_string());
for (key, val) in env.move_iter() {
runargs.push(format_strbuf!("{}={}", key, val));
}
runargs.push(format_strbuf!("{}", prog_short));
for tv in args.args.iter() {
- runargs.push(tv.to_strbuf());
+ runargs.push(tv.to_string());
}
procsrv::run("",
config.adb_path.as_slice(),
runargs.as_slice(),
- vec!(("".to_strbuf(), "".to_strbuf())), Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())), Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
// get exitcode of result
runargs = Vec::new();
- runargs.push("shell".to_strbuf());
- runargs.push("cat".to_strbuf());
+ runargs.push("shell".to_string());
+ runargs.push("cat".to_string());
runargs.push(format_strbuf!("{}/{}.exitcode",
config.adb_test_dir,
prog_short));
procsrv::run("",
config.adb_path.as_slice(),
runargs.as_slice(),
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
let mut exitcode: int = 0;
// get stdout of result
runargs = Vec::new();
- runargs.push("shell".to_strbuf());
- runargs.push("cat".to_strbuf());
+ runargs.push("shell".to_string());
+ runargs.push("cat".to_string());
runargs.push(format_strbuf!("{}/{}.stdout",
config.adb_test_dir,
prog_short));
procsrv::run("",
config.adb_path.as_slice(),
runargs.as_slice(),
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
// get stderr of result
runargs = Vec::new();
- runargs.push("shell".to_strbuf());
- runargs.push("cat".to_strbuf());
+ runargs.push("shell".to_string());
+ runargs.push("cat".to_string());
runargs.push(format_strbuf!("{}/{}.stderr",
config.adb_test_dir,
prog_short));
procsrv::run("",
config.adb_path.as_slice(),
runargs.as_slice(),
- vec!(("".to_strbuf(), "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(), "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`", config.adb_path));
dump_output(config,
let copy_result = procsrv::run("",
config.adb_path.as_slice(),
[
- "push".to_strbuf(),
+ "push".to_string(),
file.as_str()
.unwrap()
- .to_strbuf(),
- config.adb_test_dir.to_strbuf()
+ .to_string(),
+ config.adb_test_dir.to_string()
],
- vec!(("".to_strbuf(),
- "".to_strbuf())),
- Some("".to_strbuf()))
+ vec!(("".to_string(),
+ "".to_string())),
+ Some("".to_string()))
.expect(format_strbuf!("failed to exec `{}`",
config.adb_path));
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".to_strbuf(),
- aux_dir.as_str().unwrap().to_strbuf());
- let llvm_args = vec!("--emit=obj".to_strbuf(),
- "--crate-type=lib".to_strbuf(),
- "-C".to_strbuf(),
- "save-temps".to_strbuf());
+ let link_args = vec!("-L".to_string(),
+ aux_dir.as_str().unwrap().to_string());
+ let llvm_args = vec!("--emit=obj".to_string(),
+ "--crate-type=lib".to_string(),
+ "-C".to_string(),
+ "save-temps".to_string());
let args = make_compile_args(config,
props,
link_args.append(llvm_args.as_slice()),
let testcc = testfile.with_extension("cc");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: config.clang_path.get_ref().as_str().unwrap().to_strbuf(),
- args: vec!("-c".to_strbuf(),
- "-emit-llvm".to_strbuf(),
- "-o".to_strbuf(),
- bitcodefile.as_str().unwrap().to_strbuf(),
- testcc.as_str().unwrap().to_strbuf())
+ prog: config.clang_path.get_ref().as_str().unwrap().to_string(),
+ args: vec!("-c".to_string(),
+ "-emit-llvm".to_string(),
+ "-o".to_string(),
+ bitcodefile.as_str().unwrap().to_string(),
+ testcc.as_str().unwrap().to_string())
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None)
}
let prog = config.llvm_bin_path.get_ref().join("llvm-extract");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: prog.as_str().unwrap().to_strbuf(),
+ prog: prog.as_str().unwrap().to_string(),
args: vec!(format_strbuf!("-func={}", fname),
format_strbuf!("-o={}", extracted_bc.as_str().unwrap()),
- bitcodefile.as_str().unwrap().to_strbuf())
+ bitcodefile.as_str().unwrap().to_string())
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None)
}
let prog = config.llvm_bin_path.get_ref().join("llvm-dis");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: prog.as_str().unwrap().to_strbuf(),
+ prog: prog.as_str().unwrap().to_string(),
args: vec!(format_strbuf!("-o={}", extracted_ll.as_str().unwrap()),
- extracted_bc.as_str().unwrap().to_strbuf())
+ extracted_bc.as_str().unwrap().to_string())
};
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".to_strbuf());
+ fatal("missing --llvm-bin-path".to_string());
}
if config.clang_path.is_none() {
- fatal("missing --clang-path".to_strbuf());
+ fatal("missing --clang-path".to_string());
}
let mut proc_res = compile_test_and_save_bitcode(config, props, testfile);
if !proc_res.status.success() {
- fatal_ProcRes("compilation failed!".to_strbuf(), &proc_res);
+ fatal_ProcRes("compilation failed!".to_string(), &proc_res);
}
proc_res = extract_function_from_bitcode(config, props, "test", testfile, "");
if !proc_res.status.success() {
- fatal_ProcRes("extracting 'test' function failed".to_strbuf(),
+ fatal_ProcRes("extracting 'test' function failed".to_string(),
&proc_res);
}
proc_res = disassemble_extract(config, props, testfile, "");
if !proc_res.status.success() {
- fatal_ProcRes("disassembling extract failed".to_strbuf(), &proc_res);
+ fatal_ProcRes("disassembling extract failed".to_string(), &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!".to_strbuf(), &proc_res);
+ fatal_ProcRes("compilation failed!".to_string(), &proc_res);
}
proc_res = extract_function_from_bitcode(config, props, "test", testfile, "clang");
if !proc_res.status.success() {
- fatal_ProcRes("extracting 'test' function failed".to_strbuf(),
+ fatal_ProcRes("extracting 'test' function failed".to_string(),
&proc_res);
}
proc_res = disassemble_extract(config, props, testfile, "clang");
if !proc_res.status.success() {
- fatal_ProcRes("disassembling extract failed".to_strbuf(), &proc_res);
+ fatal_ProcRes("disassembling extract failed".to_string(), &proc_res);
}
let base = output_base_name(config, testfile);
Some(curr) => {
format_strbuf!("{}{}{}", path, path_div(), curr)
}
- None => path.to_str().to_strbuf()
+ None => path.to_str().to_string()
}
}
#[cfg(target_os = "win32")]
-pub fn lib_path_env_var() -> String { "PATH".to_strbuf() }
+pub fn lib_path_env_var() -> String { "PATH".to_string() }
#[cfg(target_os = "win32")]
-pub fn path_div() -> String { ";".to_strbuf() }
+pub fn path_div() -> String { ";".to_string() }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
~~~
let x: int = 42;
-let y: String = x.to_str().to_strbuf();
+let y: String = x.to_str().to_string();
~~~
**String to int**
use std::str;
let x: Option<String> =
- str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_strbuf());
+ str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_string());
let y: String = x.unwrap();
~~~
Door::<Open>(name)
}
-let _ = close(Door::<Open>("front".to_strbuf()));
+let _ = close(Door::<Open>("front".to_string()));
~~~
Attempting to close a closed door is prevented statically:
~~~ {.ignore}
-let _ = close(Door::<Closed>("front".to_strbuf())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
+let _ = close(Door::<Closed>("front".to_string())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
~~~
# FFI (Foreign Function Interface)
}
// yield and print the last pair from the iterator
-println!("last: {:?}", it.next());
+println!("last: {}", it.next());
// the iterator is now fully consumed
assert!(it.next().is_none());
~~~
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter();
-println!("{:?}", it.next()); // prints `Some(&1)`
-println!("{:?}", it.next()); // prints `Some(&2)`
-println!("{:?}", it.next_back()); // prints `Some(&6)`
+println!("{}", it.next()); // prints `Some(1)`
+println!("{}", it.next()); // prints `Some(2)`
+println!("{}", it.next_back()); // prints `Some(6)`
// prints `5`, `4` and `3`
for &x in it.rev() {
let ys = [5, 6, 7, 8];
let mut it = xs.iter().chain(ys.iter()).map(|&x| x * 2);
-println!("{:?}", it.next()); // prints `Some(2)`
+println!("{}", it.next()); // prints `Some(2)`
// prints `16`, `14`, `12`, `10`, `8`, `6`, `4`
for x in it.rev() {
let xs = [1, 2, 3, 4, 5];
let ys = ~[7, 9, 11];
let mut it = xs.iter().chain(ys.iter());
-println!("{:?}", it.idx(0)); // prints `Some(&1)`
-println!("{:?}", it.idx(5)); // prints `Some(&7)`
-println!("{:?}", it.idx(7)); // prints `Some(&11)`
-println!("{:?}", it.idx(8)); // prints `None`
+println!("{}", it.idx(0)); // prints `Some(1)`
+println!("{}", it.idx(5)); // prints `Some(7)`
+println!("{}", it.idx(7)); // prints `Some(11)`
+println!("{}", it.idx(8)); // prints `None`
// yield two elements from the beginning, and one from the end
it.next();
it.next();
it.next_back();
-println!("{:?}", it.idx(0)); // prints `Some(&3)`
-println!("{:?}", it.idx(4)); // prints `Some(&9)`
-println!("{:?}", it.idx(6)); // prints `None`
+println!("{}", it.idx(0)); // prints `Some(3)`
+println!("{}", it.idx(4)); // prints `Some(9)`
+println!("{}", it.idx(6)); // prints `None`
~~~
# Introduction
References are one of the more flexible and powerful tools available in
-Rust. A reference can point anywhere: into the managed or exchange
-heap, into the stack, and even into the interior of another data structure. A
-reference is as flexible as a C pointer or C++ reference. However,
-unlike C and C++ compilers, the Rust compiler includes special static checks
-that ensure that programs use references safely. Another advantage of
-references is that they are invisible to the garbage collector, so
-working with references helps reduce the overhead of automatic memory
-management.
+Rust. They can point anywhere: into the heap, stack, and even into the
+interior of another data structure. A reference is as flexible as a C pointer
+or C++ reference.
+
+Unlike C and C++ compilers, the Rust compiler includes special static
+checks that ensure that programs use references safely.
Despite their complete safety, a reference's representation at runtime
is the same as that of an ordinary pointer in a C program. They introduce zero
overhead. The compiler does all safety checks at compile time.
-Although references have rather elaborate theoretical
-underpinnings (region pointers), the core concepts will be familiar to
-anyone who has worked with C or C++. Therefore, the best way to explain
-how they are used—and their limitations—is probably just to work
-through several examples.
+Although references have rather elaborate theoretical underpinnings usually
+introduced as (e.g. region pointers), the core concepts will be familiar to
+anyone who has worked with C or C++. The best way to explain how they are
+used—and their limitations—is probably just to work through several examples.
# By example
References, sometimes known as *borrowed pointers*, are only valid for
a limited duration. References never claim any kind of ownership
-over the data that they point to: instead, they are used for cases
+over the data that they point to. Instead, they are used for cases
where you would like to use data for a short time.
-As an example, consider a simple struct type `Point`:
+Consider a simple struct type `Point`:
~~~
struct Point {x: f64, y: f64}
~~~
We can use this simple definition to allocate points in many different ways. For
-example, in this code, each of these three local variables contains a
-point, but allocated in a different place:
+example, in this code, each of these local variables contains a point,
+but allocated in a different place:
~~~
# struct Point {x: f64, y: f64}
-let on_the_stack : Point = Point {x: 3.0, y: 4.0};
-let managed_box : @Point = @Point {x: 5.0, y: 1.0};
-let owned_box : Box<Point> = box Point {x: 7.0, y: 9.0};
+let on_the_stack : Point = Point {x: 3.0, y: 4.0};
+let on_the_heap : Box<Point> = box Point {x: 7.0, y: 9.0};
~~~
Suppose we wanted to write a procedure that computed the distance between any
-two points, no matter where they were stored. For example, we might like to
-compute the distance between `on_the_stack` and `managed_box`, or between
-`managed_box` and `owned_box`. One option is to define a function that takes
-two arguments of type `Point`—that is, it takes the points by value. But if we
-define it this way, calling the function will cause the points to be
+two points, no matter where they were stored. One option is to define a function
+that takes two arguments of type `Point`—that is, it takes the points by value.
+But if we define it this way, calling the function will cause the points to be
copied. For points, this is probably not so bad, but often copies are
-expensive. Worse, if the data type contains mutable fields, copying can change
-the semantics of your program in unexpected ways. So we'd like to define a
-function that takes the points by pointer. We can use references to do
-this:
+expensive. So we'd like to define a function that takes the points just as
+a reference.
~~~
# struct Point {x: f64, y: f64}
}
~~~
-Now we can call `compute_distance()` in various ways:
+Now we can call `compute_distance()`:
~~~
# struct Point {x: f64, y: f64}
# let on_the_stack : Point = Point{x: 3.0, y: 4.0};
-# let managed_box : @Point = @Point{x: 5.0, y: 1.0};
-# let owned_box : Box<Point> = box Point{x: 7.0, y: 9.0};
+# let on_the_heap : Box<Point> = box Point{x: 7.0, y: 9.0};
# fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
-compute_distance(&on_the_stack, managed_box);
-compute_distance(managed_box, owned_box);
+compute_distance(&on_the_stack, &*on_the_heap);
~~~
Here, the `&` operator takes the address of the variable
`on_the_stack`, because we have created an alias: that is, another
name for the same data.
-In contrast, we can pass the boxes `managed_box` and `owned_box` to
-`compute_distance` directly. The compiler automatically converts a box like
-`@Point` or `~Point` to a reference like `&Point`. This is another form
-of borrowing: in this case, the caller lends the contents of the managed or
-owned box to the callee.
+For the second argument, we need to extract the contents of `on_the_heap`
+by derefercing with the `*` symbol. Now that we have the data, we need
+to create a reference with the `&` symbol.
Whenever a caller lends data to a callee, there are some limitations on what
the caller can do with the original. For example, if the contents of a
# Taking the address of fields
-As in C, the `&` operator is not limited to taking the address of
+The `&` operator is not limited to taking the address of
local variables. It can also take the address of fields or
individual array elements. For example, consider this type definition
-for `rectangle`:
+for `Rectangle`:
~~~
struct Point {x: f64, y: f64} // as before
# struct Rectangle {origin: Point, size: Size}
let rect_stack = &Rectangle {origin: Point {x: 1.0, y: 2.0},
size: Size {w: 3.0, h: 4.0}};
-let rect_managed = @Rectangle {origin: Point {x: 3.0, y: 4.0},
- size: Size {w: 3.0, h: 4.0}};
-let rect_owned = box Rectangle {origin: Point {x: 5.0, y: 6.0},
+let rect_heap = box Rectangle {origin: Point {x: 5.0, y: 6.0},
size: Size {w: 3.0, h: 4.0}};
~~~
# struct Size {w: f64, h: f64} // as before
# struct Rectangle {origin: Point, size: Size}
# let rect_stack = &Rectangle {origin: Point {x: 1.0, y: 2.0}, size: Size {w: 3.0, h: 4.0}};
-# let rect_managed = @Rectangle {origin: Point {x: 3.0, y: 4.0}, size: Size {w: 3.0, h: 4.0}};
-# let rect_owned = box Rectangle {origin: Point {x: 5.0, y: 6.0}, size: Size {w: 3.0, h: 4.0}};
+# let rect_heap = box Rectangle {origin: Point {x: 5.0, y: 6.0}, size: Size {w: 3.0, h: 4.0}};
# fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
-compute_distance(&rect_stack.origin, &rect_managed.origin);
+compute_distance(&rect_stack.origin, &rect_heap.origin);
~~~
which would borrow the field `origin` from the rectangle on the stack
-as well as from the managed box, and then compute the distance between them.
+as well as from the owned box, and then compute the distance between them.
-# Borrowing managed boxes and rooting
+# Lifetimes
-We’ve seen a few examples so far of borrowing heap boxes, both managed
-and owned. Up till this point, we’ve glossed over issues of
-safety. As stated in the introduction, at runtime a reference
-is simply a pointer, nothing more. Therefore, avoiding C's problems
-with dangling pointers requires a compile-time safety check.
+We’ve seen a few examples of borrowing data. To this point, we’ve glossed
+over issues of safety. As stated in the introduction, at runtime a reference
+is simply a pointer, nothing more. Therefore, avoiding C's problems with
+dangling pointers requires a compile-time safety check.
The basis for the check is the notion of _lifetimes_. A lifetime is a
static approximation of the span of execution during which the pointer
is valid: it always corresponds to some expression or block within the
-program. Code inside that expression can use the pointer without
-restrictions. But if the pointer escapes from that expression (for
-example, if the expression contains an assignment expression that
-assigns the pointer to a mutable field of a data structure with a
-broader scope than the pointer itself), the compiler reports an
-error. We'll be discussing lifetimes more in the examples to come, and
-a more thorough introduction is also available.
-
-When the `&` operator creates a reference, the compiler must
-ensure that the pointer remains valid for its entire
-lifetime. Sometimes this is relatively easy, such as when taking the
-address of a local variable or a field that is stored on the stack:
-
-~~~
-struct X { f: int }
-fn example1() {
- let mut x = X { f: 3 };
- let y = &mut x.f; // -+ L
- // ... // |
-} // -+
-~~~
-
-Here, the lifetime of the reference `y` is simply L, the
-remainder of the function body. The compiler need not do any other
-work to prove that code will not free `x.f`. This is true even if the
-code mutates `x`.
-
-The situation gets more complex when borrowing data inside heap boxes:
-
-~~~
-# struct X { f: int }
-fn example2() {
- let mut x = @X { f: 3 };
- let y = &x.f; // -+ L
- // ... // |
-} // -+
-~~~
-
-In this example, the value `x` is a heap box, and `y` is therefore a
-pointer into that heap box. Again the lifetime of `y` is L, the
-remainder of the function body. But there is a crucial difference:
-suppose `x` were to be reassigned during the lifetime L? If the
-compiler isn't careful, the managed box could become *unrooted*, and
-would therefore be subject to garbage collection. A heap box that is
-unrooted is one such that no pointer values in the heap point to
-it. It would violate memory safety for the box that was originally
-assigned to `x` to be garbage-collected, since a non-heap
-pointer *`y`* still points into it.
-
-> *Note:* Our current implementation implements the garbage collector
-> using reference counting and cycle detection.
-
-For this reason, whenever an `&` expression borrows the interior of a
-managed box stored in a mutable location, the compiler inserts a
-temporary that ensures that the managed box remains live for the
-entire lifetime. So, the above example would be compiled as if it were
-written
-
-~~~
-# struct X { f: int }
-fn example2() {
- let mut x = @X {f: 3};
- let x1 = x;
- let y = &x1.f; // -+ L
- // ... // |
-} // -+
-~~~
-
-Now if `x` is reassigned, the pointer `y` will still remain valid. This
-process is called *rooting*.
-
-# Borrowing owned boxes
-
-The previous example demonstrated *rooting*, the process by which the
-compiler ensures that managed boxes remain live for the duration of a
-borrow. Unfortunately, rooting does not work for borrows of owned
-boxes, because it is not possible to have two references to an owned
-box.
-
-For owned boxes, therefore, the compiler will only allow a borrow *if
-the compiler can guarantee that the owned box will not be reassigned
-or moved for the lifetime of the pointer*. This does not necessarily
-mean that the owned box is stored in immutable memory. For example,
+program.
+
+The compiler will only allow a borrow *if it can guarantee that the data will
+not be reassigned or moved for the lifetime of the pointer*. This does not
+necessarily mean that the data is stored in immutable memory. For example,
the following function is legal:
~~~
}
~~~
-Here, as before, the interior of the variable `x` is being borrowed
+Here, the interior of the variable `x` is being borrowed
and `x` is declared as mutable. However, the compiler can prove that
`x` is not assigned anywhere in the lifetime L of the variable
`y`. Therefore, it accepts the function, even though `x` is mutable
and in fact is mutated later in the function.
It may not be clear why we are so concerned about mutating a borrowed
-variable. The reason is that the runtime system frees any owned box
+variable. The reason is that the runtime system frees any box
_as soon as its owning reference changes or goes out of
scope_. Therefore, a program like this is illegal (and would be
rejected by the compiler):
+---------+
~~~
-Here you can see that the variable `y` still points at the old box,
-which has been freed.
+Here you can see that the variable `y` still points at the old `f`
+property of Foo, which has been freed.
In fact, the compiler can apply the same kind of reasoning to any
-memory that is _(uniquely) owned by the stack frame_. So we could
+memory that is (uniquely) owned by the stack frame. So we could
modify the previous example to introduce additional owned pointers
and structs, and the compiler will still be able to detect possible
-mutations:
+mutations. This time, we'll use an analogy to illustrate the concept.
~~~ {.ignore}
fn example3() -> int {
- struct R { g: int }
- struct S { f: Box<R> }
+ struct House { owner: Box<Person> }
+ struct Person { age: int }
- let mut x = box S {f: box R {g: 3}};
- let y = &x.f.g;
- x = box S {f: box R {g: 4}}; // Error reported here.
- x.f = box R {g: 5}; // Error reported here.
- *y
+ let mut house = box House {
+ owner: box Person {age: 30}
+ };
+
+ let owner_age = &house.owner.age;
+ house = box House {owner: box Person {age: 40}}; // Error reported here.
+ house.owner = box Person {age: 50}; // Error reported here.
+ *owner_age
}
~~~
-In this case, two errors are reported, one when the variable `x` is
-modified and another when `x.f` is modified. Either modification would
-invalidate the pointer `y`.
+In this case, two errors are reported, one when the variable `house` is
+modified and another when `house.owner` is modified. Either modification would
+invalidate the pointer `owner_age`.
# Borrowing and enums
case where the compiler must be very careful to ensure that pointers
remain valid: pointers into the interior of an `enum`.
-As an example, let’s look at the following `shape` type that can
-represent both rectangles and circles:
+Let’s look at the following `shape` type that can represent both rectangles
+and circles:
~~~
struct Point {x: f64, y: f64}; // as before
possible to return references as the result of a function, but
as we'll see, doing so requires some explicit annotation.
-For example, we could write a subroutine like this:
+We could write a subroutine like this:
~~~
struct Point {x: f64, y: f64}
parameters; named lifetimes indicate which parameter that
is.
-In the previous examples, function parameter types did not include a
-lifetime name. In those examples, the compiler simply creates a fresh
-name for the lifetime automatically: that is, the lifetime name is
-guaranteed to refer to a distinct lifetime from the lifetimes of all
-other parameters.
+In the previous code samples, function parameter types did not include a
+lifetime name. The compiler simply creates a fresh name for the lifetime
+automatically: that is, the lifetime name is guaranteed to refer to a distinct
+lifetime from the lifetimes of all other parameters.
Named lifetimes that appear in function signatures are conceptually
the same as the other lifetimes we have seen before, but they are a bit
~~~ {.ignore}
struct Point {x: f64, y: f64}
-fn get_x_sh(p: @Point) -> &f64 {
+fn get_x_sh(p: &Point) -> &f64 {
&p.x // Error reported here
}
~~~
-Here, the function `get_x_sh()` takes a managed box as input and
+Here, the function `get_x_sh()` takes a reference as input and
returns a reference. As before, the lifetime of the reference
that will be returned is a parameter (specified by the
caller). That means that `get_x_sh()` promises to return a reference
pointer that was valid for as long as its pointer argument was valid.
Within `get_x_sh()`, we see the expression `&p.x` which takes the
-address of a field of a managed box. The presence of this expression
-implies that the compiler must guarantee that, so long as the
-resulting pointer is valid, the managed box will not be reclaimed by
-the garbage collector. But recall that `get_x_sh()` also promised to
+address of a field of a Point. The presence of this expression
+implies that the compiler must guarantee that , so long as the
+resulting pointer is valid, the original Point won't be moved or changed.
+
+But recall that `get_x_sh()` also promised to
return a pointer that was valid for as long as the caller wanted it to
be. Clearly, `get_x_sh()` is not in a position to make both of these
guarantees; in fact, it cannot guarantee that the pointer will remain
valid at all once it returns, as the parameter `p` may or may not be
live in the caller. Therefore, the compiler will report an error here.
-In general, if you borrow a managed (or owned) box to create a
+In general, if you borrow a struct or box to create a
reference, it will only be valid within the function
and cannot be returned. This is why the typical way to return references
is to take references as input (the only other case in
be confusing for people coming from other languages that support pointers, such
as C++. This guide will help you understand this important topic.
-# You don't actually need pointers
+# You don't actually need pointers, use references
I have good news for you: you probably don't need to care about pointers,
especially as you're getting started. Think of it this way: Rust is a language
1. Owned: `Box<Trait>` must be a pointer, because you don't know the size of the
object, so indirection is mandatory.
+
2. Owned: You need a recursive data structure. These can be infinite sized, so
indirection is mandatory.
+
3. Owned: A very, very, very rare situation in which you have a *huge* chunk of
data that you wish to pass to many methods. Passing a pointer will make this
more efficient. If you're coming from another language where this technique is
common, such as C++, please read "A note..." below.
-4. Managed: Having only a single owner to a piece of data would be inconvenient
-or impossible. This is only often useful when a program is very large or very
-complicated. Using a managed pointer will activate Rust's garbage collection
-mechanism.
-5. Reference: You're writing a function, and you need a pointer, but you don't
+
+4. Reference: You're writing a function, and you need a pointer, but you don't
care about its ownership. If you make the argument a reference, callers
can send in whatever kind they want.
+5. Shared: You need to share data among tasks. You can achieve that via the
+`Rc` and `Arc` types.
+
Five exceptions. That's it. Otherwise, you shouldn't need them. Be sceptical
of pointers in Rust: use them for a deliberate purpose, not just to make the
compiler happy.
~~~rust
# fn transform(p: Point) -> Point { p }
+#[deriving(Show)]
struct Point {
x: int,
y: int,
fn main() {
let p0 = Point { x: 5, y: 10};
let p1 = transform(p0);
- println!("{:?}", p1);
+ println!("{}", p1);
}
~~~
This does work, but you don't need to create those references! The better way to write this is simply:
~~~rust
+#[deriving(Show)]
struct Point {
x: int,
y: int,
fn main() {
let p0 = Point { x: 5, y: 10};
let p1 = transform(p0);
- println!("{:?}", p1);
+ println!("{}", p1);
}
~~~
1. Only one owned pointer may exist to a particular place in memory. It may be
borrowed from that owner, however.
+
2. The Rust compiler uses static analysis to determine where the pointer is in
scope, and handles allocating and de-allocating that memory. Owned pointers are
not garbage collected.
Sometimes, you need a recursive data structure. The simplest is known as a 'cons list':
~~~rust
-
+#[deriving(Show)]
enum List<T> {
Nil,
Cons(T, Box<List<T>>),
fn main() {
let list: List<int> = Cons(1, box Cons(2, box Cons(3, box Nil)));
- println!("{:?}", list);
+ println!("{}", list);
}
~~~
Now it'll be copying a pointer-sized chunk of memory rather than the whole
struct.
-# Managed Pointers
-
-> **Note**: the `@` form of managed pointers is deprecated and behind a
-> feature gate (it requires a `#![feature(managed_pointers)]` attribute on
-> the crate root). There are replacements, currently
-> there is `std::rc::Rc` and `std::gc::Gc` for shared ownership via reference
-> counting and garbage collection respectively.
-
-Managed pointers, notated by an `@`, are used when having a single owner for
-some data isn't convenient or possible. This generally happens when your
-program is very large and complicated.
-
-For example, let's say you're using an owned pointer, and you want to do this:
-
-~~~rust{.ignore}
-struct Point {
- x: int,
- y: int,
-}
-
-fn main() {
- let a = box Point { x: 10, y: 20 };
- let b = a;
- println!("{}", b.x);
- println!("{}", a.x);
-}
-~~~
-
-You'll get this error:
-
-~~~ {.notrust}
-test.rs:10:20: 10:21 error: use of moved value: `a`
-test.rs:10 println!("{}", a.x);
- ^
-note: in expansion of format_args!
-<std-macros>:158:27: 158:81 note: expansion site
-<std-macros>:157:5: 159:6 note: in expansion of println!
-test.rs:10:5: 10:25 note: expansion site
-test.rs:8:9: 8:10 note: `a` moved here because it has type `Box<Point>`, which is moved by default (use `ref` to override)
-test.rs:8 let b = a;
- ^
-~~~
-
-As the message says, owned pointers only allow for one owner at a time. When you assign `a` to `b`, `a` becomes invalid. Change your code to this, however:
-
-~~~rust
-struct Point {
- x: int,
- y: int,
-}
-
-fn main() {
- let a = @Point { x: 10, y: 20 };
- let b = a;
- println!("{}", b.x);
- println!("{}", a.x);
-}
-~~~
-
-And it works:
-
-~~~ {.notrust}
-10
-10
-~~~
-
-So why not just use managed pointers everywhere? There are two big drawbacks to
-managed pointers:
-
-1. They activate Rust's garbage collector. Other pointer types don't share this
-drawback.
-2. You cannot pass this data to another task. Shared ownership across
-concurrency boundaries is the source of endless pain in other languages, so
-Rust does not let you do this.
-
# References
References are the third major kind of pointer Rust supports. They are
}
fn main() {
- let origin = @Point { x: 0.0, y: 0.0 };
+ let origin = &Point { x: 0.0, y: 0.0 };
let p1 = box Point { x: 5.0, y: 3.0 };
- println!("{:?}", compute_distance(origin, p1));
+ println!("{}", compute_distance(origin, p1));
}
~~~
This prints `5.83095189`. You can see that the `compute_distance` function
-takes in two references, but we give it a managed and unique pointer. Of
-course, if this were a real program, we wouldn't have any of these pointers,
+takes in two references, a reference to a value on the stack, and a reference
+to a value in a box.
+Of course, if this were a real program, we wouldn't have any of these pointers,
they're just there to demonstrate the concepts.
So how is this hard? Well, because we're ignoring ownership, the compiler needs
an ordinary pointer in a C program. They introduce zero overhead. The compiler
does all safety checks at compile time.
-This theory is called 'region pointers,' and involve a concept called
-'lifetimes'. Here's the simple explanation: would you expect this code to
-compile?
+This theory is called 'region pointers' and you can read more about it
+[here](http://www.cs.umd.edu/projects/cyclone/papers/cyclone-regions.pdf).
+Region pointers evolved into what we know today as 'lifetimes'.
+
+Here's the simple explanation: would you expect this code to compile?
~~~rust{.ignore}
fn main() {
let mut x = box 5;
if *x < 10 {
let y = &x;
- println!("Oh no: {:?}", y);
+ println!("Oh no: {}", y);
return;
}
*x -= 1;
- println!("Oh no: {:?}", x);
+ println!("Oh no: {}", x);
}
~~~
let y = &x;
*x -= 1;
- println!("Oh no: {:?}", y);
+ println!("Oh no: {}", y);
return;
}
*x -= 1;
- println!("Oh no: {:?}", x);
+ println!("Oh no: {}", x);
}
~~~
}
~~~
-This gives you flexibility, without sacrificing performance. For example, this will
-also work:
-
-~~~rust
-fn foo(x: Box<int>) -> int {
- return *x;
-}
-
-fn main() {
- let x = box 5;
- let y = @foo(x);
-}
-~~~
+This gives you flexibility, without sacrificing performance.
You may think that this gives us terrible performance: return a value and then
-immediately box it up?!?! Isn't that the worst of both worlds? Rust is smarter
+immediately box it up ?! Isn't that the worst of both worlds? Rust is smarter
than that. There is no copy in this code. `main` allocates enough room for the
-`@int`, passes a pointer to that memory into `foo` as `x`, and then `foo` writes
+`box int`, passes a pointer to that memory into `foo` as `x`, and then `foo` writes
the value straight into that pointer. This writes the return value directly into
the allocated box.
returning values from your code. Allow the caller to choose how they want to
use your output.
-
# Related Resources
* [Lifetimes guide](guide-lifetimes.html)
let mut delayed_fib = sync::Future::spawn(proc() fib(50));
make_a_sandwich();
-println!("fib(50) = {:?}", delayed_fib.get())
+println!("fib(50) = {}", delayed_fib.get())
# }
~~~
let mut value: uint;
loop {
value = channel.recv();
- channel.send(value.to_str().to_strbuf());
+ channel.send(value.to_str().to_string());
if value == 0 { break; }
}
}
# let mut value: uint;
# loop {
# value = channel.recv();
-# channel.send(value.to_str().to_strbuf());
+# channel.send(value.to_str().to_string());
# if value == 0u { break; }
# }
# }
Cat { name: String, weight: f64 }
}
-let mut a: Animal = Dog("Cocoa".to_strbuf(), 37.2);
-a = Cat { name: "Spotty".to_strbuf(), weight: 2.7 };
+let mut a: Animal = Dog("Cocoa".to_string(), 37.2);
+a = Cat { name: "Spotty".to_string(), weight: 2.7 };
~~~~
In this example, `Cat` is a _struct-like enum variant_,
~~~~
the syntax `Circle : Shape` means that types that implement `Circle` must also have an implementation for `Shape`.
-Multiple supertraits are separated by spaces, `trait Circle : Shape Eq { }`.
+Multiple supertraits are separated by `+`, `trait Circle : Shape + Eq { }`.
In an implementation of `Circle` for a given type `T`, methods can refer to `Shape` methods,
since the typechecker checks that any type with an implementation of `Circle` also has an implementation of `Shape`.
procedure:
```rust
-let string = "Hello".to_owned();
+let string = "Hello".to_string();
// Creates a new procedure, passing it to the `spawn` function.
spawn(proc() {
}
impl Printable for int {
- fn to_string(&self) -> String { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str().to_string() }
}
fn print(a: Box<Printable>) {
that [printf][pf] has. Unlike printf, `format!` will give you a compile-time
error when the types of the directives don't match the types of the arguments.
-~~~~
-# let mystery_object = ();
-
+~~~
// `{}` will print the "default format" of a type
println!("{} is {}", "the answer", 43);
+~~~
-// `{:?}` will conveniently print any type
+~~~~
+extern crate debug;
+
+# fn main() {
+# let mystery_object = ();
+// `{:?}` will conveniently print any type,
+// but requires the `debug` crate to be linked in
println!("what is this thing: {:?}", mystery_object);
+# }
~~~~
[pf]: http://en.cppreference.com/w/cpp/io/c/fprintf
operator to convert a variant to its discriminator value as an `int`:
~~~~
-# enum Direction { North }
-println!( "{:?} => {}", North, North as int );
+# #[deriving(Show)] enum Direction { North }
+println!( "{} => {}", North, North as int );
~~~~
It is possible to set the discriminator values to chosen constant values:
~~~~
# trait Printable { fn print(&self); }
impl Printable for int {
- fn print(&self) { println!("{:?}", *self) }
+ fn print(&self) { println!("{}", *self) }
}
impl Printable for String {
}
# 1.print();
-# ("foo".to_strbuf()).print();
+# ("foo".to_string()).print();
~~~~
Methods defined in an impl for a trait may be called just like
~~~~
# trait Printable { fn print(&self); }
impl Printable for f32 {
- fn print(&self) { println!("{:?}", *self) }
+ fn print(&self) { println!("{}", *self) }
}
impl Printable for bool {
- fn print(&self) { println!("{:?}", *self) }
+ fn print(&self) { println!("{}", *self) }
}
# true.print();
giving its signature. That is, we can write the following:
~~~~
+extern crate debug;
+
+# fn main() {
trait Printable {
- // Default method implementation
+ // Default method implementation
fn print(&self) { println!("{:?}", *self) }
}
impl Printable for f32 {}
# 1.print();
-# ("foo".to_strbuf()).print();
+# ("foo".to_string()).print();
# true.print();
# 3.14159.print();
+# }
~~~~
Here, the impls of `Printable` for `int`, `bool`, and `f32` don't
extern crate core;
extern crate libc;
+
// Allow testing this library
+#[cfg(test)] extern crate debug;
#[cfg(test)] extern crate sync;
#[cfg(test)] extern crate native;
#[cfg(test)] #[phase(syntax, link)] extern crate std;
let arena = TypedArena::new();
for _ in range(0, 100000) {
arena.alloc(Noncopy {
- string: "hello world".to_strbuf(),
+ string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
});
}
let arena = TypedArena::new();
b.iter(|| {
arena.alloc(Noncopy {
- string: "hello world".to_strbuf(),
+ string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
pub fn bench_noncopy_nonarena(b: &mut Bencher) {
b.iter(|| {
box Noncopy {
- string: "hello world".to_strbuf(),
+ string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
}
})
let arena = Arena::new();
b.iter(|| {
arena.alloc(|| Noncopy {
- string: "hello world".to_strbuf(),
+ string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
#[test]
fn test_to_str() {
let zerolen = Bitv::new(0u, false);
- assert_eq!(zerolen.to_str(), "".to_owned());
+ assert_eq!(zerolen.to_str(), "".to_string());
let eightbits = Bitv::new(8u, false);
- assert_eq!(eightbits.to_str(), "00000000".to_owned());
+ assert_eq!(eightbits.to_str(), "00000000".to_string());
}
#[test]
let mut b = bitv::Bitv::new(2, false);
b.set(0, true);
b.set(1, false);
- assert_eq!(b.to_str(), "10".to_owned());
+ assert_eq!(b.to_str(), "10".to_string());
}
#[test]
#[test]
fn test_from_bools() {
assert!(from_bools([true, false, true, true]).to_str() ==
- "1011".to_owned());
+ "1011".to_string());
}
#[test]
//Tests the functionality of the insert methods (which are unfinished).
#[test]
fn insert_test_one() {
- let b = BTree::new(1, "abc".to_owned(), 2);
- let is_insert = b.insert(2, "xyz".to_owned());
+ let b = BTree::new(1, "abc".to_string(), 2);
+ let is_insert = b.insert(2, "xyz".to_string());
//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".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_1 = LeafElt::new(1, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
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_owned()).to_str());
- assert!(b.insert(4, "ddd".to_owned()).root.is_leaf());
+ //println!("{}", b.clone().insert(4, "ddd".to_string()).to_str());
+ assert!(b.insert(4, "ddd".to_string()).root.is_leaf());
}
#[test]
fn insert_test_three() {
- 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 leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
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_owned()).to_str());
- assert!(!b.insert(5, "eee".to_owned()).root.is_leaf());
+ //println!("{}", b.clone().insert(5, "eee".to_string()).to_str());
+ assert!(!b.insert(5, "eee".to_string()).root.is_leaf());
}
#[test]
fn insert_test_four() {
- 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 leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
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".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());
+ b = b.clone().insert(5, "eee".to_string());
+ b = b.clone().insert(6, "fff".to_string());
+ b = b.clone().insert(7, "ggg".to_string());
+ b = b.clone().insert(8, "hhh".to_string());
+ b = b.clone().insert(0, "omg".to_string());
//println!("{}", b.clone().to_str());
assert!(!b.root.is_leaf());
}
#[test]
fn bsearch_test_one() {
- let b = BTree::new(1, "abc".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
assert_eq!(Some(1), b.root.bsearch_node(2));
}
#[test]
fn bsearch_test_two() {
- let b = BTree::new(1, "abc".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
assert_eq!(Some(0), b.root.bsearch_node(0));
}
#[test]
fn bsearch_test_three() {
- 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 leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
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".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 leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
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".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
let val = b.get(1);
- assert_eq!(val, Some("abc".to_owned()));
+ assert_eq!(val, Some("abc".to_string()));
}
//Tests the BTree's clone() method.
#[test]
fn btree_clone_test() {
- let b = BTree::new(1, "abc".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 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".to_owned(), 2);
- let b2 = BTree::new(2, "bcd".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
+ let b2 = BTree::new(2, "bcd".to_string(), 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".to_owned(), 2);
- let b2 = BTree::new(1, "bcd".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
+ let b2 = BTree::new(1, "bcd".to_string(), 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".to_owned(), 2);
- let b2 = BTree::new(2, "bcd".to_owned(), 2);
+ let b = BTree::new(1, "abc".to_string(), 2);
+ let b2 = BTree::new(2, "bcd".to_string(), 2);
assert!(&b2.cmp(&b) == &Greater)
}
//Tests the BTree's to_str() method.
#[test]
fn btree_tostr_test() {
- let b = BTree::new(1, "abc".to_owned(), 2);
- assert_eq!(b.to_str(), "Key: 1, value: abc;".to_owned())
+ let b = BTree::new(1, "abc".to_string(), 2);
+ assert_eq!(b.to_str(), "Key: 1, value: abc;".to_string())
}
}
assert_eq!(m1, m2);
}
+ #[test]
+ fn test_show() {
+ let mut map: HashMap<int, int> = HashMap::new();
+ let empty: HashMap<int, int> = HashMap::new();
+
+ map.insert(1, 2);
+ map.insert(3, 4);
+
+ let map_str = format!("{}", map);
+
+ assert!(map_str == "{1: 2, 3: 4}".to_owned() || map_str == "{3: 4, 1: 2}".to_owned());
+ assert_eq!(format!("{}", empty), "{}".to_owned());
+ }
+
#[test]
fn test_expand() {
let mut m = HashMap::new();
let mut m = HashMap::new();
let (foo, bar, baz) = (1,2,3);
- m.insert("foo".to_owned(), foo);
- m.insert("bar".to_owned(), bar);
- m.insert("baz".to_owned(), baz);
+ m.insert("foo".to_string(), foo);
+ m.insert("bar".to_string(), bar);
+ m.insert("baz".to_string(), baz);
assert_eq!(m.find_equiv(&("foo")), Some(&foo));
let set_str = format!("{}", set);
- assert!(set_str == "{1, 2}".to_owned() || set_str == "{2, 1}".to_owned());
- assert_eq!(format!("{}", empty), "{}".to_owned());
+ assert!(set_str == "{1, 2}".to_string() || set_str == "{2, 1}".to_string());
+ assert_eq!(format!("{}", empty), "{}".to_string());
}
}
#![deny(deprecated_owned_vector)]
extern crate rand;
+extern crate debug;
#[cfg(test)] extern crate test;
#[cfg(test)] #[phase(syntax, link)] extern crate log;
#[test]
fn test_put_update() {
let mut cache: LruCache<String, Vec<u8>> = LruCache::new(1);
- cache.put("1".to_strbuf(), vec![10, 10]);
- cache.put("1".to_strbuf(), vec![10, 19]);
- assert_opt_eq(cache.get(&"1".to_strbuf()), vec![10, 19]);
+ cache.put("1".to_string(), vec![10, 10]);
+ cache.put("1".to_string(), vec![10, 19]);
+ assert_opt_eq(cache.get(&"1".to_string()), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<String, String> = LruCache::new(2);
- cache.put("foo1".to_strbuf(), "bar1".to_strbuf());
- cache.put("foo2".to_strbuf(), "bar2".to_strbuf());
- cache.put("foo3".to_strbuf(), "bar3".to_strbuf());
- assert!(cache.get(&"foo1".to_strbuf()).is_none());
- cache.put("foo2".to_strbuf(), "bar2update".to_strbuf());
- cache.put("foo4".to_strbuf(), "bar4".to_strbuf());
- assert!(cache.get(&"foo3".to_strbuf()).is_none());
+ cache.put("foo1".to_string(), "bar1".to_string());
+ cache.put("foo2".to_string(), "bar2".to_string());
+ cache.put("foo3".to_string(), "bar3".to_string());
+ assert!(cache.get(&"foo1".to_string()).is_none());
+ cache.put("foo2".to_string(), "bar2update".to_string());
+ cache.put("foo4".to_string(), "bar4".to_string());
+ assert!(cache.get(&"foo3".to_string()).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}".to_owned());
+ assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_string());
cache.put(2, 22);
- assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned());
+ assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_string());
cache.put(6, 60);
- assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned());
+ assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_string());
cache.get(&3);
- assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned());
+ assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_string());
cache.change_capacity(2);
- assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned());
+ assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_string());
}
#[test]
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
- assert_eq!(cache.to_str(), "{}".to_owned());
+ assert_eq!(cache.to_str(), "{}".to_string());
}
}
//! trees. The only requirement for the types is that the key implements
//! `TotalOrd`.
-use std::iter;
-use std::iter::{Peekable};
use std::cmp::Ordering;
+use std::fmt::Show;
+use std::fmt;
+use std::iter::Peekable;
+use std::iter;
use std::mem::{replace, swap};
use std::ptr;
fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) }
}
+impl<K: TotalOrd + Show, V: Show> Show for TreeMap<K, V> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ try!(write!(f, r"\{"));
+
+ for (i, (k, v)) in self.iter().enumerate() {
+ if i != 0 { try!(write!(f, ", ")); }
+ try!(write!(f, "{}: {}", *k, *v));
+ }
+
+ write!(f, r"\}")
+ }
+}
+
impl<K: TotalOrd, V> Container for TreeMap<K, V> {
fn len(&self) -> uint { self.length }
}
fn lt(&self, other: &TreeSet<T>) -> bool { self.map < other.map }
}
+impl<T: TotalOrd + Show> Show for TreeSet<T> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ try!(write!(f, r"\{"));
+
+ for (i, x) in self.iter().enumerate() {
+ if i != 0 { try!(write!(f, ", ")); }
+ try!(write!(f, "{}", *x));
+ }
+
+ write!(f, r"\}")
+ }
+}
+
impl<T: TotalOrd> Container for TreeSet<T> {
#[inline]
fn len(&self) -> uint { self.map.len() }
assert!(a < b && a <= b);
}
+ #[test]
+ fn test_show() {
+ let mut map: TreeMap<int, int> = TreeMap::new();
+ let empty: TreeMap<int, int> = TreeMap::new();
+
+ map.insert(1, 2);
+ map.insert(3, 4);
+
+ let map_str = format!("{}", map);
+
+ assert!(map_str == "{1: 2, 3: 4}".to_owned());
+ assert_eq!(format!("{}", empty), "{}".to_owned());
+ }
+
#[test]
fn test_lazy_iterator() {
let mut m = TreeMap::new();
assert!(set.contains(x));
}
}
+
+ #[test]
+ fn test_show() {
+ let mut set: TreeSet<int> = TreeSet::new();
+ let empty: TreeSet<int> = TreeSet::new();
+
+ set.insert(1);
+ set.insert(2);
+
+ let set_str = format!("{}", set);
+
+ assert!(set_str == "{1, 2}".to_owned());
+ assert_eq!(format!("{}", empty), "{}".to_owned());
+ }
}
//! Operations on boolean values (`bool` type)
//!
-//! A quick summary:
-//!
-//! Implementations of the following traits:
-//!
-//! * `Not`
-//! * `BitAnd`
-//! * `BitOr`
-//! * `BitXor`
-//! * `Ord`
-//! * `TotalOrd`
-//! * `Eq`
-//! * `TotalEq`
-//! * `Default`
-//!
//! A `to_bit` conversion function.
use num::{Int, one, zero};
-#[cfg(not(test))] use cmp::{Eq, Ord, TotalOrd, Ordering, TotalEq};
-#[cfg(not(test))] use ops::{Not, BitAnd, BitOr, BitXor};
-#[cfg(not(test))] use default::Default;
-
/////////////////////////////////////////////////////////////////////////////
// Freestanding functions
/////////////////////////////////////////////////////////////////////////////
if p { one() } else { zero() }
}
-/////////////////////////////////////////////////////////////////////////////
-// Trait impls on `bool`
-/////////////////////////////////////////////////////////////////////////////
-
-#[cfg(not(test))]
-impl Not<bool> for bool {
- /// The logical complement of a boolean value.
- ///
- /// # Examples
- ///
- /// ```rust
- /// assert_eq!(!true, false);
- /// assert_eq!(!false, true);
- /// ```
- #[inline]
- fn not(&self) -> bool { !*self }
-}
-
-#[cfg(not(test))]
-impl BitAnd<bool, bool> for bool {
- /// Conjunction of two boolean values.
- ///
- /// # Examples
- ///
- /// ```rust
- /// assert_eq!(false.bitand(&false), false);
- /// assert_eq!(true.bitand(&false), false);
- /// assert_eq!(false.bitand(&true), false);
- /// assert_eq!(true.bitand(&true), true);
- ///
- /// assert_eq!(false & false, false);
- /// assert_eq!(true & false, false);
- /// assert_eq!(false & true, false);
- /// assert_eq!(true & true, true);
- /// ```
- #[inline]
- fn bitand(&self, b: &bool) -> bool { *self & *b }
-}
-
-#[cfg(not(test))]
-impl BitOr<bool, bool> for bool {
- /// Disjunction of two boolean values.
- ///
- /// # Examples
- ///
- /// ```rust
- /// assert_eq!(false.bitor(&false), false);
- /// assert_eq!(true.bitor(&false), true);
- /// assert_eq!(false.bitor(&true), true);
- /// assert_eq!(true.bitor(&true), true);
- ///
- /// assert_eq!(false | false, false);
- /// assert_eq!(true | false, true);
- /// assert_eq!(false | true, true);
- /// assert_eq!(true | true, true);
- /// ```
- #[inline]
- fn bitor(&self, b: &bool) -> bool { *self | *b }
-}
-
-#[cfg(not(test))]
-impl BitXor<bool, bool> for bool {
- /// An 'exclusive or' of two boolean values.
- ///
- /// 'exclusive or' is identical to `or(and(a, not(b)), and(not(a), b))`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// assert_eq!(false.bitxor(&false), false);
- /// assert_eq!(true.bitxor(&false), true);
- /// assert_eq!(false.bitxor(&true), true);
- /// assert_eq!(true.bitxor(&true), false);
- ///
- /// assert_eq!(false ^ false, false);
- /// assert_eq!(true ^ false, true);
- /// assert_eq!(false ^ true, true);
- /// assert_eq!(true ^ true, false);
- /// ```
- #[inline]
- fn bitxor(&self, b: &bool) -> bool { *self ^ *b }
-}
-
-#[cfg(not(test))]
-impl Ord for bool {
- #[inline]
- fn lt(&self, other: &bool) -> bool {
- to_bit::<u8>(*self) < to_bit(*other)
- }
-}
-
-#[cfg(not(test))]
-impl TotalOrd for bool {
- #[inline]
- fn cmp(&self, other: &bool) -> Ordering {
- to_bit::<u8>(*self).cmp(&to_bit(*other))
- }
-}
-
-/// Equality between two boolean values.
-///
-/// Two booleans are equal if they have the same value.
-///
-/// # Examples
-///
-/// ```rust
-/// assert_eq!(false.eq(&true), false);
-/// assert_eq!(false == false, true);
-/// assert_eq!(false != true, true);
-/// assert_eq!(false.ne(&false), false);
-/// ```
-#[cfg(not(test))]
-impl Eq for bool {
- #[inline]
- fn eq(&self, other: &bool) -> bool { (*self) == (*other) }
-}
-
-#[cfg(not(test))]
-impl TotalEq for bool {}
-
-#[cfg(not(test))]
-impl Default for bool {
- fn default() -> bool { false }
-}
-
#[cfg(test)]
mod tests {
use realstd::prelude::*;
}
#[test]
+ #[allow(experimental)]
fn clone_ref_updates_flag() {
let x = RefCell::new(0);
{
/// Returns the compatibility decomposition of a character.
pub use unicode::normalization::decompose_compatible;
-#[cfg(not(test))] use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering};
-#[cfg(not(test))] use default::Default;
-
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
}
}
-#[cfg(not(test))]
-impl Eq for char {
- #[inline]
- fn eq(&self, other: &char) -> bool { (*self) == (*other) }
-}
-
-#[cfg(not(test))]
-impl TotalEq for char {}
-
-#[cfg(not(test))]
-impl Ord for char {
- #[inline]
- fn lt(&self, other: &char) -> bool { *self < *other }
-}
-
-#[cfg(not(test))]
-impl TotalOrd for char {
- fn cmp(&self, other: &char) -> Ordering {
- (*self as u32).cmp(&(*other as u32))
- }
-}
-
-#[cfg(not(test))]
-impl Default for char {
- #[inline]
- fn default() -> char { '\x00' }
-}
#[cfg(test)]
mod test {
if v1 > v2 { v1 } else { v2 }
}
-// Implementation of Eq/TotalEq for some primitive types
+// Implementation of Eq, TotalEq, Ord and TotalOrd for primitive types
#[cfg(not(test))]
mod impls {
- use cmp::{Ord, TotalOrd, Eq, TotalEq, Ordering, Equal};
+ use cmp::{Ord, TotalOrd, Eq, TotalEq, Ordering, Less, Greater, Equal};
+
+ macro_rules! eq_impl(
+ ($($t:ty)*) => ($(
+ impl Eq for $t {
+ #[inline]
+ fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
+ #[inline]
+ fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
+ }
+ )*)
+ )
impl Eq for () {
#[inline]
#[inline]
fn ne(&self, _other: &()) -> bool { false }
}
- impl TotalEq for () {}
+
+ eq_impl!(bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
+ macro_rules! totaleq_impl(
+ ($($t:ty)*) => ($(
+ impl TotalEq for $t {}
+ )*)
+ )
+
+ totaleq_impl!(() bool char uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
+ macro_rules! ord_impl(
+ ($($t:ty)*) => ($(
+ impl Ord for $t {
+ #[inline]
+ fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
+ #[inline]
+ fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
+ #[inline]
+ fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
+ #[inline]
+ fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
+ }
+ )*)
+ )
+
impl Ord for () {
#[inline]
fn lt(&self, _other: &()) -> bool { false }
}
+
+ impl Ord for bool {
+ #[inline]
+ fn lt(&self, other: &bool) -> bool {
+ (*self as u8) < (*other as u8)
+ }
+ }
+
+ ord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
+ macro_rules! totalord_impl(
+ ($($t:ty)*) => ($(
+ impl TotalOrd for $t {
+ #[inline]
+ fn cmp(&self, other: &$t) -> Ordering {
+ if *self < *other { Less }
+ else if *self > *other { Greater }
+ else { Equal }
+ }
+ }
+ )*)
+ )
+
impl TotalOrd for () {
#[inline]
fn cmp(&self, _other: &()) -> Ordering { Equal }
}
+ impl TotalOrd for bool {
+ #[inline]
+ fn cmp(&self, other: &bool) -> Ordering {
+ (*self as u8).cmp(&(*other as u8))
+ }
+ }
+
+ totalord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
// & pointers
impl<'a, T: Eq> Eq for &'a T {
#[inline]
fn default() -> Self;
}
-impl Default for () {
- #[inline]
- fn default() -> () { () }
-}
+macro_rules! default_impl(
+ ($t:ty, $v:expr) => {
+ impl Default for $t {
+ #[inline]
+ fn default() -> $t { $v }
+ }
+ }
+)
+
+default_impl!((), ())
+default_impl!(bool, false)
+default_impl!(char, '\x00')
+
+default_impl!(uint, 0u)
+default_impl!(u8, 0u8)
+default_impl!(u16, 0u16)
+default_impl!(u32, 0u32)
+default_impl!(u64, 0u64)
+
+default_impl!(int, 0i)
+default_impl!(i8, 0i8)
+default_impl!(i16, 0i16)
+default_impl!(i32, 0i32)
+default_impl!(i64, 0i64)
+
+default_impl!(f32, 0.0f32)
+default_impl!(f64, 0.0f64)
impl<T: Default + 'static> Default for @T {
fn default() -> @T { @Default::default() }
///
/// ~~~
/// use std::fmt::radix;
-/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_owned());
+/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// ~~~
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
intrinsics::move_val_init(&mut *dst, src)
}
-/// Deprecated, use move_val_init() instead
+/// Deprecated, use `overwrite` instead
#[inline]
-#[deprecated = "this function has been renamed to move_val_init()"]
+#[deprecated = "this function has been renamed to `overwrite`"]
pub unsafe fn move_val_init<T>(dst: &mut T, src: T) {
overwrite(dst, src)
}
#[test]
fn test_replace() {
- let mut x = Some("test".to_owned());
+ let mut x = Some("test".to_string());
let y = replace(&mut x, None);
assert!(x.is_none());
assert!(y.is_some());
}
unsafe {
- assert!(Vec::from_slice([76u8]) == transmute("L".to_owned()));
+ assert!(Vec::from_slice([76u8]) == transmute("L".to_string()));
}
}
}
//! Operations and constants for 32-bits floats (`f32` type)
-use default::Default;
use intrinsics;
use mem;
use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN};
-use num::{Zero, One, Bounded, Signed, Num, Primitive, Float};
+use num::Float;
use option::Option;
-#[cfg(not(test))] use cmp::{Eq, Ord};
-#[cfg(not(test))] use ops::{Add, Sub, Mul, Div, Rem, Neg};
-
pub static RADIX: uint = 2u;
pub static MANTISSA_DIGITS: uint = 24u;
pub static LN_10: f32 = 2.30258509299404568401799145468436421_f32;
}
-#[cfg(not(test))]
-impl Ord for f32 {
- #[inline]
- fn lt(&self, other: &f32) -> bool { (*self) < (*other) }
- #[inline]
- fn le(&self, other: &f32) -> bool { (*self) <= (*other) }
- #[inline]
- fn ge(&self, other: &f32) -> bool { (*self) >= (*other) }
- #[inline]
- fn gt(&self, other: &f32) -> bool { (*self) > (*other) }
-}
-#[cfg(not(test))]
-impl Eq for f32 {
- #[inline]
- fn eq(&self, other: &f32) -> bool { (*self) == (*other) }
-}
-
-impl Num for f32 {}
-
-impl Default for f32 {
- #[inline]
- fn default() -> f32 { 0.0 }
-}
-
-impl Primitive for f32 {}
-
-impl Zero for f32 {
- #[inline]
- fn zero() -> f32 { 0.0 }
-
- /// Returns true if the number is equal to either `0.0` or `-0.0`
- #[inline]
- fn is_zero(&self) -> bool { *self == 0.0 || *self == -0.0 }
-}
-
-impl One for f32 {
- #[inline]
- fn one() -> f32 { 1.0 }
-}
-
-#[cfg(not(test))]
-impl Add<f32,f32> for f32 {
- #[inline]
- fn add(&self, other: &f32) -> f32 { *self + *other }
-}
-
-#[cfg(not(test))]
-impl Sub<f32,f32> for f32 {
- #[inline]
- fn sub(&self, other: &f32) -> f32 { *self - *other }
-}
-
-#[cfg(not(test))]
-impl Mul<f32,f32> for f32 {
- #[inline]
- fn mul(&self, other: &f32) -> f32 { *self * *other }
-}
-
-#[cfg(not(test))]
-impl Div<f32,f32> for f32 {
- #[inline]
- fn div(&self, other: &f32) -> f32 { *self / *other }
-}
-
-#[cfg(not(test))]
-impl Rem<f32,f32> for f32 {
- #[inline]
- fn rem(&self, other: &f32) -> f32 {
- extern { fn fmodf(a: f32, b: f32) -> f32; }
- unsafe { fmodf(*self, *other) }
- }
-}
-
-#[cfg(not(test))]
-impl Neg<f32> for f32 {
- #[inline]
- fn neg(&self) -> f32 { -*self }
-}
-
-impl Signed for f32 {
- /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
- #[inline]
- fn abs(&self) -> f32 {
- unsafe { intrinsics::fabsf32(*self) }
- }
-
- /// The positive difference of two numbers. Returns `0.0` if the number is
- /// less than or equal to `other`, otherwise the difference between`self`
- /// and `other` is returned.
- #[inline]
- fn abs_sub(&self, other: &f32) -> f32 {
- extern { fn fdimf(a: f32, b: f32) -> f32; }
- unsafe { fdimf(*self, *other) }
- }
-
- /// # Returns
- ///
- /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
- /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
- /// - `NAN` if the number is NaN
- #[inline]
- fn signum(&self) -> f32 {
- if self != self { NAN } else {
- unsafe { intrinsics::copysignf32(1.0, *self) }
- }
- }
-
- /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
- #[inline]
- fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == INFINITY }
-
- /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
- #[inline]
- fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == NEG_INFINITY }
-}
-
-impl Bounded for f32 {
- // NOTE: this is the smallest non-infinite f32 value, *not* MIN_VALUE
- #[inline]
- fn min_value() -> f32 { -MAX_VALUE }
-
- #[inline]
- fn max_value() -> f32 { MAX_VALUE }
-}
-
impl Float for f32 {
#[inline]
fn nan() -> f32 { NAN }
//! Operations and constants for 64-bits floats (`f64` type)
-use default::Default;
use intrinsics;
use mem;
use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN};
-use num::{Zero, One, Bounded, Signed, Num, Primitive, Float};
+use num::Float;
use option::Option;
-#[cfg(not(test))] use cmp::{Eq, Ord};
-#[cfg(not(test))] use ops::{Add, Sub, Mul, Div, Rem, Neg};
-
// FIXME(#5527): These constants should be deprecated once associated
// constants are implemented in favour of referencing the respective
// members of `Bounded` and `Float`.
pub static LN_10: f64 = 2.30258509299404568401799145468436421_f64;
}
-#[cfg(not(test))]
-impl Ord for f64 {
- #[inline]
- fn lt(&self, other: &f64) -> bool { (*self) < (*other) }
- #[inline]
- fn le(&self, other: &f64) -> bool { (*self) <= (*other) }
- #[inline]
- fn ge(&self, other: &f64) -> bool { (*self) >= (*other) }
- #[inline]
- fn gt(&self, other: &f64) -> bool { (*self) > (*other) }
-}
-#[cfg(not(test))]
-impl Eq for f64 {
- #[inline]
- fn eq(&self, other: &f64) -> bool { (*self) == (*other) }
-}
-
-impl Default for f64 {
- #[inline]
- fn default() -> f64 { 0.0 }
-}
-
-impl Primitive for f64 {}
-
-impl Num for f64 {}
-
-impl Zero for f64 {
- #[inline]
- fn zero() -> f64 { 0.0 }
-
- /// Returns true if the number is equal to either `0.0` or `-0.0`
- #[inline]
- fn is_zero(&self) -> bool { *self == 0.0 || *self == -0.0 }
-}
-
-impl One for f64 {
- #[inline]
- fn one() -> f64 { 1.0 }
-}
-
-#[cfg(not(test))]
-impl Add<f64,f64> for f64 {
- #[inline]
- fn add(&self, other: &f64) -> f64 { *self + *other }
-}
-#[cfg(not(test))]
-impl Sub<f64,f64> for f64 {
- #[inline]
- fn sub(&self, other: &f64) -> f64 { *self - *other }
-}
-#[cfg(not(test))]
-impl Mul<f64,f64> for f64 {
- #[inline]
- fn mul(&self, other: &f64) -> f64 { *self * *other }
-}
-#[cfg(not(test))]
-impl Div<f64,f64> for f64 {
- #[inline]
- fn div(&self, other: &f64) -> f64 { *self / *other }
-}
-#[cfg(not(test))]
-impl Rem<f64,f64> for f64 {
- #[inline]
- fn rem(&self, other: &f64) -> f64 {
- extern { fn fmod(a: f64, b: f64) -> f64; }
- unsafe { fmod(*self, *other) }
- }
-}
-#[cfg(not(test))]
-impl Neg<f64> for f64 {
- #[inline]
- fn neg(&self) -> f64 { -*self }
-}
-
-impl Signed for f64 {
- /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
- #[inline]
- fn abs(&self) -> f64 {
- unsafe { intrinsics::fabsf64(*self) }
- }
-
- /// The positive difference of two numbers. Returns `0.0` if the number is less than or
- /// equal to `other`, otherwise the difference between`self` and `other` is returned.
- #[inline]
- fn abs_sub(&self, other: &f64) -> f64 {
- extern { fn fdim(a: f64, b: f64) -> f64; }
- unsafe { fdim(*self, *other) }
- }
-
- /// # Returns
- ///
- /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
- /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
- /// - `NAN` if the number is NaN
- #[inline]
- fn signum(&self) -> f64 {
- if self != self { NAN } else {
- unsafe { intrinsics::copysignf64(1.0, *self) }
- }
- }
-
- /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
- #[inline]
- fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == INFINITY }
-
- /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
- #[inline]
- fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == NEG_INFINITY }
-}
-
-impl Bounded for f64 {
- // NOTE: this is the smallest non-infinite f32 value, *not* MIN_VALUE
- #[inline]
- fn min_value() -> f64 { -MAX_VALUE }
-
- #[inline]
- fn max_value() -> f64 { MAX_VALUE }
-}
-
impl Float for f64 {
#[inline]
fn nan() -> f64 { NAN }
//! Operations and constants for signed 16-bits integers (`i16` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Signed, Num, Primitive, Int};
-use num::{CheckedDiv, CheckedAdd, CheckedSub, CheckedMul};
-use option::{Option, Some, None};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitOr, BitAnd, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
int_module!(i16, 16)
-impl Bitwise for i16 {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> i16 { unsafe { intrinsics::ctpop16(*self as u16) as i16 } }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self as u16) as i16 } }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self as u16) as i16 } }
-}
-
-impl CheckedAdd for i16 {
- #[inline]
- fn checked_add(&self, v: &i16) -> Option<i16> {
- unsafe {
- let (x, y) = intrinsics::i16_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for i16 {
- #[inline]
- fn checked_sub(&self, v: &i16) -> Option<i16> {
- unsafe {
- let (x, y) = intrinsics::i16_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for i16 {
- #[inline]
- fn checked_mul(&self, v: &i16) -> Option<i16> {
- unsafe {
- let (x, y) = intrinsics::i16_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for signed 32-bits integers (`i32` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Signed, Num, Primitive, Int};
-use num::{CheckedDiv, CheckedAdd, CheckedSub, CheckedMul};
-use option::{Option, Some, None};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitOr, BitAnd, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
int_module!(i32, 32)
-impl Bitwise for i32 {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> i32 { unsafe { intrinsics::ctpop32(*self as u32) as i32 } }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self as u32) as i32 } }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> i32 { unsafe { intrinsics::cttz32(*self as u32) as i32 } }
-}
-
-impl CheckedAdd for i32 {
- #[inline]
- fn checked_add(&self, v: &i32) -> Option<i32> {
- unsafe {
- let (x, y) = intrinsics::i32_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for i32 {
- #[inline]
- fn checked_sub(&self, v: &i32) -> Option<i32> {
- unsafe {
- let (x, y) = intrinsics::i32_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for i32 {
- #[inline]
- fn checked_mul(&self, v: &i32) -> Option<i32> {
- unsafe {
- let (x, y) = intrinsics::i32_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for signed 64-bits integers (`i64` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Signed, Num, Primitive, Int};
-use num::{CheckedDiv, CheckedAdd, CheckedSub, CheckedMul};
-use option::{Option, Some, None};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitOr, BitAnd, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
int_module!(i64, 64)
-impl Bitwise for i64 {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> i64 { unsafe { intrinsics::ctpop64(*self as u64) as i64 } }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> i64 { unsafe { intrinsics::ctlz64(*self as u64) as i64 } }
-
- /// Counts the number of trailing zeros.
- #[inline]
- fn trailing_zeros(&self) -> i64 { unsafe { intrinsics::cttz64(*self as u64) as i64 } }
-}
-
-impl CheckedAdd for i64 {
- #[inline]
- fn checked_add(&self, v: &i64) -> Option<i64> {
- unsafe {
- let (x, y) = intrinsics::i64_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for i64 {
- #[inline]
- fn checked_sub(&self, v: &i64) -> Option<i64> {
- unsafe {
- let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for i64 {
- #[inline]
- fn checked_mul(&self, v: &i64) -> Option<i64> {
- unsafe {
- let (x, y) = intrinsics::i64_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for signed 8-bits integers (`i8` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Signed, Num, Primitive, Int};
-use num::{CheckedDiv, CheckedAdd, CheckedSub, CheckedMul};
-use option::{Option, Some, None};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitOr, BitAnd, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
int_module!(i8, 8)
-impl Bitwise for i8 {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> i8 { unsafe { intrinsics::ctpop8(*self as u8) as i8 } }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> i8 { unsafe { intrinsics::ctlz8(*self as u8) as i8 } }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> i8 { unsafe { intrinsics::cttz8(*self as u8) as i8 } }
-}
-
-impl CheckedAdd for i8 {
- #[inline]
- fn checked_add(&self, v: &i8) -> Option<i8> {
- unsafe {
- let (x, y) = intrinsics::i8_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for i8 {
- #[inline]
- fn checked_sub(&self, v: &i8) -> Option<i8> {
- unsafe {
- let (x, y) = intrinsics::i8_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for i8 {
- #[inline]
- fn checked_mul(&self, v: &i8) -> Option<i8> {
- unsafe {
- let (x, y) = intrinsics::i8_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for architecture-sized signed integers (`int` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Signed, Num, Primitive, Int};
-use num::{CheckedDiv, CheckedAdd, CheckedSub, CheckedMul};
-use option::{Option, Some, None};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitOr, BitAnd, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
#[cfg(target_word_size = "32")] int_module!(int, 32)
#[cfg(target_word_size = "64")] int_module!(int, 64)
-#[cfg(target_word_size = "32")]
-impl Bitwise for int {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> int { (*self as i32).count_ones() as int }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int }
-}
-
-#[cfg(target_word_size = "64")]
-impl Bitwise for int {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> int { (*self as i64).count_ones() as int }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int }
-}
-
-#[cfg(target_word_size = "32")]
-impl CheckedAdd for int {
- #[inline]
- fn checked_add(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i32_add_with_overflow(*self as i32, *v as i32);
- if y { None } else { Some(x as int) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedAdd for int {
- #[inline]
- fn checked_add(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i64_add_with_overflow(*self as i64, *v as i64);
- if y { None } else { Some(x as int) }
- }
- }
-}
-
-#[cfg(target_word_size = "32")]
-impl CheckedSub for int {
- #[inline]
- fn checked_sub(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i32_sub_with_overflow(*self as i32, *v as i32);
- if y { None } else { Some(x as int) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedSub for int {
- #[inline]
- fn checked_sub(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i64_sub_with_overflow(*self as i64, *v as i64);
- if y { None } else { Some(x as int) }
- }
- }
-}
-
-#[cfg(target_word_size = "32")]
-impl CheckedMul for int {
- #[inline]
- fn checked_mul(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i32_mul_with_overflow(*self as i32, *v as i32);
- if y { None } else { Some(x as int) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedMul for int {
- #[inline]
- fn checked_mul(&self, v: &int) -> Option<int> {
- unsafe {
- let (x, y) = intrinsics::i64_mul_with_overflow(*self as i64, *v as i64);
- if y { None } else { Some(x as int) }
- }
- }
-}
// calling the `Bounded::max_value` function.
pub static MAX: $T = !MIN;
-#[cfg(not(test))]
-impl Ord for $T {
- #[inline]
- fn lt(&self, other: &$T) -> bool { *self < *other }
-}
-#[cfg(not(test))]
-impl TotalEq for $T {}
-#[cfg(not(test))]
-impl Eq for $T {
- #[inline]
- fn eq(&self, other: &$T) -> bool { *self == *other }
-}
-#[cfg(not(test))]
-impl TotalOrd for $T {
- #[inline]
- fn cmp(&self, other: &$T) -> Ordering {
- if *self < *other { Less }
- else if *self > *other { Greater }
- else { Equal }
- }
-}
-
-impl Num for $T {}
-
-impl Zero for $T {
- #[inline]
- fn zero() -> $T { 0 }
-
- #[inline]
- fn is_zero(&self) -> bool { *self == 0 }
-}
-
-impl One for $T {
- #[inline]
- fn one() -> $T { 1 }
-}
-
-#[cfg(not(test))]
-impl Add<$T,$T> for $T {
- #[inline]
- fn add(&self, other: &$T) -> $T { *self + *other }
-}
-
-#[cfg(not(test))]
-impl Sub<$T,$T> for $T {
- #[inline]
- fn sub(&self, other: &$T) -> $T { *self - *other }
-}
-
-#[cfg(not(test))]
-impl Mul<$T,$T> for $T {
- #[inline]
- fn mul(&self, other: &$T) -> $T { *self * *other }
-}
-
-#[cfg(not(test))]
-impl Div<$T,$T> for $T {
- /// Integer division, truncated towards 0.
- ///
- /// # Examples
- ///
- /// ~~~
- /// assert!( 8 / 3 == 2);
- /// assert!( 8 / -3 == -2);
- /// assert!(-8 / 3 == -2);
- /// assert!(-8 / -3 == 2);
- ///
- /// assert!( 1 / 2 == 0);
- /// assert!( 1 / -2 == 0);
- /// assert!(-1 / 2 == 0);
- /// assert!(-1 / -2 == 0);
- /// ~~~
- #[inline]
- fn div(&self, other: &$T) -> $T { *self / *other }
-}
-
-#[cfg(not(test))]
-impl Rem<$T,$T> for $T {
- /// Returns the integer remainder after division, satisfying:
- ///
- /// ~~~
- /// # let n = 1;
- /// # let d = 2;
- /// assert!((n / d) * d + (n % d) == n)
- /// ~~~
- ///
- /// # Examples
- ///
- /// ~~~
- /// assert!( 8 % 3 == 2);
- /// assert!( 8 % -3 == 2);
- /// assert!(-8 % 3 == -2);
- /// assert!(-8 % -3 == -2);
- ///
- /// assert!( 1 % 2 == 1);
- /// assert!( 1 % -2 == 1);
- /// assert!(-1 % 2 == -1);
- /// assert!(-1 % -2 == -1);
- /// ~~~
- #[inline]
- fn rem(&self, other: &$T) -> $T { *self % *other }
-}
-
-#[cfg(not(test))]
-impl Neg<$T> for $T {
- #[inline]
- fn neg(&self) -> $T { -*self }
-}
-
-impl Signed for $T {
- /// Computes the absolute value
- #[inline]
- fn abs(&self) -> $T {
- if self.is_negative() { -*self } else { *self }
- }
-
- ///
- /// The positive difference of two numbers. Returns `0` if the number is less than or
- /// equal to `other`, otherwise the difference between`self` and `other` is returned.
- ///
- #[inline]
- fn abs_sub(&self, other: &$T) -> $T {
- if *self <= *other { 0 } else { *self - *other }
- }
-
- ///
- /// # Returns
- ///
- /// - `0` if the number is zero
- /// - `1` if the number is positive
- /// - `-1` if the number is negative
- ///
- #[inline]
- fn signum(&self) -> $T {
- match *self {
- n if n > 0 => 1,
- 0 => 0,
- _ => -1,
- }
- }
-
- /// Returns true if the number is positive
- #[inline]
- fn is_positive(&self) -> bool { *self > 0 }
-
- /// Returns true if the number is negative
- #[inline]
- fn is_negative(&self) -> bool { *self < 0 }
-}
-
-#[cfg(not(test))]
-impl BitOr<$T,$T> for $T {
- #[inline]
- fn bitor(&self, other: &$T) -> $T { *self | *other }
-}
-
-#[cfg(not(test))]
-impl BitAnd<$T,$T> for $T {
- #[inline]
- fn bitand(&self, other: &$T) -> $T { *self & *other }
-}
-
-#[cfg(not(test))]
-impl BitXor<$T,$T> for $T {
- #[inline]
- fn bitxor(&self, other: &$T) -> $T { *self ^ *other }
-}
-
-#[cfg(not(test))]
-impl Shl<$T,$T> for $T {
- #[inline]
- fn shl(&self, other: &$T) -> $T { *self << *other }
-}
-
-#[cfg(not(test))]
-impl Shr<$T,$T> for $T {
- #[inline]
- fn shr(&self, other: &$T) -> $T { *self >> *other }
-}
-
-#[cfg(not(test))]
-impl Not<$T> for $T {
- #[inline]
- fn not(&self) -> $T { !*self }
-}
-
-impl Bounded for $T {
- #[inline]
- fn min_value() -> $T { MIN }
-
- #[inline]
- fn max_value() -> $T { MAX }
-}
-
-impl CheckedDiv for $T {
- #[inline]
- fn checked_div(&self, v: &$T) -> Option<$T> {
- if *v == 0 || (*self == MIN && *v == -1) {
- None
- } else {
- Some(self / *v)
- }
- }
-}
-
-impl Default for $T {
- #[inline]
- fn default() -> $T { 0 }
-}
-
-impl Int for $T {}
-
-impl Primitive for $T {}
-
#[cfg(test)]
mod tests {
use prelude::*;
// except according to those terms.
//! Numeric traits and functions for generic mathematics
-//!
-//! These are implemented for the primitive numeric types in `std::{u8, u16,
-//! u32, u64, uint, i8, i16, i32, i64, int, f32, f64}`.
#![allow(missing_doc)]
+use intrinsics;
+use {int, i8, i16, i32, i64};
+use {uint, u8, u16, u32, u64};
+use {f32, f64};
use clone::Clone;
use cmp::{Eq, Ord};
use kinds::Copy;
+ Div<Self,Self>
+ Rem<Self,Self> {}
+macro_rules! trait_impl(
+ ($name:ident for $($t:ty)*) => ($(
+ impl $name for $t {}
+ )*)
+)
+
+trait_impl!(Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/// Simultaneous division and remainder
#[inline]
pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
fn is_zero(&self) -> bool;
}
+macro_rules! zero_impl(
+ ($t:ty, $v:expr) => {
+ impl Zero for $t {
+ #[inline]
+ fn zero() -> $t { $v }
+ #[inline]
+ fn is_zero(&self) -> bool { *self == $v }
+ }
+ }
+)
+
+macro_rules! zero_float_impl(
+ ($t:ty, $v:expr) => {
+ impl Zero for $t {
+ #[inline]
+ fn zero() -> $t { $v }
+
+ #[inline]
+ fn is_zero(&self) -> bool { *self == $v || *self == -$v }
+ }
+ }
+)
+
+zero_impl!(uint, 0u)
+zero_impl!(u8, 0u8)
+zero_impl!(u16, 0u16)
+zero_impl!(u32, 0u32)
+zero_impl!(u64, 0u64)
+
+zero_impl!(int, 0i)
+zero_impl!(i8, 0i8)
+zero_impl!(i16, 0i16)
+zero_impl!(i32, 0i32)
+zero_impl!(i64, 0i64)
+
+zero_float_impl!(f32, 0.0f32)
+zero_float_impl!(f64, 0.0f64)
+
/// Returns the additive identity, `0`.
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
fn one() -> Self;
}
+macro_rules! one_impl(
+ ($t:ty, $v:expr) => {
+ impl One for $t {
+ #[inline]
+ fn one() -> $t { $v }
+ }
+ }
+)
+
+one_impl!(uint, 1u)
+one_impl!(u8, 1u8)
+one_impl!(u16, 1u16)
+one_impl!(u32, 1u32)
+one_impl!(u64, 1u64)
+
+one_impl!(int, 1i)
+one_impl!(i8, 1i8)
+one_impl!(i16, 1i16)
+one_impl!(i32, 1i32)
+one_impl!(i64, 1i64)
+
+one_impl!(f32, 1.0f32)
+one_impl!(f64, 1.0f64)
+
/// Returns the multiplicative identity, `1`.
#[inline(always)] pub fn one<T: One>() -> T { One::one() }
fn is_negative(&self) -> bool;
}
+macro_rules! signed_impl(
+ ($($t:ty)*) => ($(
+ impl Signed for $t {
+ #[inline]
+ fn abs(&self) -> $t {
+ if self.is_negative() { -*self } else { *self }
+ }
+
+ #[inline]
+ fn abs_sub(&self, other: &$t) -> $t {
+ if *self <= *other { 0 } else { *self - *other }
+ }
+
+ #[inline]
+ fn signum(&self) -> $t {
+ match *self {
+ n if n > 0 => 1,
+ 0 => 0,
+ _ => -1,
+ }
+ }
+
+ #[inline]
+ fn is_positive(&self) -> bool { *self > 0 }
+
+ #[inline]
+ fn is_negative(&self) -> bool { *self < 0 }
+ }
+ )*)
+)
+
+signed_impl!(int i8 i16 i32 i64)
+
+macro_rules! signed_float_impl(
+ ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr, $fabs:path, $fcopysign:path, $fdim:ident) => {
+ impl Signed for $t {
+ /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
+ #[inline]
+ fn abs(&self) -> $t {
+ unsafe { $fabs(*self) }
+ }
+
+ /// The positive difference of two numbers. Returns `0.0` if the number is
+ /// less than or equal to `other`, otherwise the difference between`self`
+ /// and `other` is returned.
+ #[inline]
+ fn abs_sub(&self, other: &$t) -> $t {
+ extern { fn $fdim(a: $t, b: $t) -> $t; }
+ unsafe { $fdim(*self, *other) }
+ }
+
+ /// # Returns
+ ///
+ /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
+ /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
+ /// - `NAN` if the number is NaN
+ #[inline]
+ fn signum(&self) -> $t {
+ if self != self { $nan } else {
+ unsafe { $fcopysign(1.0, *self) }
+ }
+ }
+
+ /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
+ #[inline]
+ fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf }
+
+ /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
+ #[inline]
+ fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf }
+ }
+ }
+)
+
+signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY,
+ intrinsics::fabsf32, intrinsics::copysignf32, fdimf)
+signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY,
+ intrinsics::fabsf64, intrinsics::copysignf64, fdim)
+
/// Computes the absolute value.
///
/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
/// A trait for values which cannot be negative
pub trait Unsigned: Num {}
+trait_impl!(Unsigned for uint u8 u16 u32 u64)
+
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
fn max_value() -> Self;
}
+macro_rules! bounded_impl(
+ ($t:ty, $min:expr, $max:expr) => {
+ impl Bounded for $t {
+ #[inline]
+ fn min_value() -> $t { $min }
+
+ #[inline]
+ fn max_value() -> $t { $max }
+ }
+ }
+)
+
+bounded_impl!(uint, uint::MIN, uint::MAX)
+bounded_impl!(u8, u8::MIN, u8::MAX)
+bounded_impl!(u16, u16::MIN, u16::MAX)
+bounded_impl!(u32, u32::MIN, u32::MAX)
+bounded_impl!(u64, u64::MIN, u64::MAX)
+
+bounded_impl!(int, int::MIN, int::MAX)
+bounded_impl!(i8, i8::MIN, i8::MAX)
+bounded_impl!(i16, i16::MIN, i16::MAX)
+bounded_impl!(i32, i32::MIN, i32::MAX)
+bounded_impl!(i64, i64::MIN, i64::MAX)
+
+bounded_impl!(f32, f32::MIN_VALUE, f32::MAX_VALUE)
+bounded_impl!(f64, f64::MIN_VALUE, f64::MAX_VALUE)
+
/// Numbers with a fixed binary representation.
pub trait Bitwise: Bounded
+ Not<Self>
fn trailing_zeros(&self) -> Self;
}
+macro_rules! bitwise_impl(
+ ($t:ty, $co:path, $lz:path, $tz:path) => {
+ impl Bitwise for $t {
+ #[inline]
+ fn count_ones(&self) -> $t { unsafe { $co(*self) } }
+
+ #[inline]
+ fn leading_zeros(&self) -> $t { unsafe { $lz(*self) } }
+
+ #[inline]
+ fn trailing_zeros(&self) -> $t { unsafe { $tz(*self) } }
+ }
+ }
+)
+
+macro_rules! bitwise_cast_impl(
+ ($t:ty, $t_cast:ty, $co:path, $lz:path, $tz:path) => {
+ impl Bitwise for $t {
+ #[inline]
+ fn count_ones(&self) -> $t { unsafe { $co(*self as $t_cast) as $t } }
+
+ #[inline]
+ fn leading_zeros(&self) -> $t { unsafe { $lz(*self as $t_cast) as $t } }
+
+ #[inline]
+ fn trailing_zeros(&self) -> $t { unsafe { $tz(*self as $t_cast) as $t } }
+ }
+ }
+)
+
+#[cfg(target_word_size = "32")]
+bitwise_cast_impl!(uint, u32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
+#[cfg(target_word_size = "64")]
+bitwise_cast_impl!(uint, u64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
+
+bitwise_impl!(u8, intrinsics::ctpop8, intrinsics::ctlz8, intrinsics::cttz8)
+bitwise_impl!(u16, intrinsics::ctpop16, intrinsics::ctlz16, intrinsics::cttz16)
+bitwise_impl!(u32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
+bitwise_impl!(u64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
+
+#[cfg(target_word_size = "32")]
+bitwise_cast_impl!(int, u32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
+#[cfg(target_word_size = "64")]
+bitwise_cast_impl!(int, u64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
+
+bitwise_cast_impl!(i8, u8, intrinsics::ctpop8, intrinsics::ctlz8, intrinsics::cttz8)
+bitwise_cast_impl!(i16, u16, intrinsics::ctpop16, intrinsics::ctlz16, intrinsics::cttz16)
+bitwise_cast_impl!(i32, u32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
+bitwise_cast_impl!(i64, u64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
+
/// Specifies the available operations common to all of Rust's core numeric primitives.
/// These may not always make sense from a purely mathematical point of view, but
/// may be useful for systems programming.
+ Ord
+ Bounded {}
+trait_impl!(Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/// A collection of traits relevant to primitive signed and unsigned integers
pub trait Int: Primitive
+ Bitwise
+ CheckedMul
+ CheckedDiv {}
+trait_impl!(Int for uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/// Returns the smallest power of 2 greater than or equal to `n`.
#[inline]
pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
fn checked_add(&self, v: &Self) -> Option<Self>;
}
+macro_rules! checked_impl(
+ ($trait_name:ident, $method:ident, $t:ty, $op:path) => {
+ impl $trait_name for $t {
+ #[inline]
+ fn $method(&self, v: &$t) -> Option<$t> {
+ unsafe {
+ let (x, y) = $op(*self, *v);
+ if y { None } else { Some(x) }
+ }
+ }
+ }
+ }
+)
+macro_rules! checked_cast_impl(
+ ($trait_name:ident, $method:ident, $t:ty, $cast:ty, $op:path) => {
+ impl $trait_name for $t {
+ #[inline]
+ fn $method(&self, v: &$t) -> Option<$t> {
+ unsafe {
+ let (x, y) = $op(*self as $cast, *v as $cast);
+ if y { None } else { Some(x as $t) }
+ }
+ }
+ }
+ }
+)
+
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedAdd, checked_add, uint, u32, intrinsics::u32_add_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedAdd, checked_add, uint, u64, intrinsics::u64_add_with_overflow)
+
+checked_impl!(CheckedAdd, checked_add, u8, intrinsics::u8_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, u16, intrinsics::u16_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, u32, intrinsics::u32_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, u64, intrinsics::u64_add_with_overflow)
+
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedAdd, checked_add, int, i32, intrinsics::i32_add_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedAdd, checked_add, int, i64, intrinsics::i64_add_with_overflow)
+
+checked_impl!(CheckedAdd, checked_add, i8, intrinsics::i8_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, i16, intrinsics::i16_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, i32, intrinsics::i32_add_with_overflow)
+checked_impl!(CheckedAdd, checked_add, i64, intrinsics::i64_add_with_overflow)
+
/// Performs subtraction that returns `None` instead of wrapping around on underflow.
pub trait CheckedSub: Sub<Self, Self> {
/// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
fn checked_sub(&self, v: &Self) -> Option<Self>;
}
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedSub, checked_sub, uint, u32, intrinsics::u32_sub_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedSub, checked_sub, uint, u64, intrinsics::u64_sub_with_overflow)
+
+checked_impl!(CheckedSub, checked_sub, u8, intrinsics::u8_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, u16, intrinsics::u16_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, u32, intrinsics::u32_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, u64, intrinsics::u64_sub_with_overflow)
+
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedSub, checked_sub, int, i32, intrinsics::i32_sub_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedSub, checked_sub, int, i64, intrinsics::i64_sub_with_overflow)
+
+checked_impl!(CheckedSub, checked_sub, i8, intrinsics::i8_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, i16, intrinsics::i16_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, i32, intrinsics::i32_sub_with_overflow)
+checked_impl!(CheckedSub, checked_sub, i64, intrinsics::i64_sub_with_overflow)
+
/// Performs multiplication that returns `None` instead of wrapping around on underflow or
/// overflow.
pub trait CheckedMul: Mul<Self, Self> {
fn checked_mul(&self, v: &Self) -> Option<Self>;
}
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedMul, checked_mul, uint, u32, intrinsics::u32_mul_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedMul, checked_mul, uint, u64, intrinsics::u64_mul_with_overflow)
+
+checked_impl!(CheckedMul, checked_mul, u8, intrinsics::u8_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, u16, intrinsics::u16_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, u32, intrinsics::u32_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, u64, intrinsics::u64_mul_with_overflow)
+
+#[cfg(target_word_size = "32")]
+checked_cast_impl!(CheckedMul, checked_mul, int, i32, intrinsics::i32_mul_with_overflow)
+#[cfg(target_word_size = "64")]
+checked_cast_impl!(CheckedMul, checked_mul, int, i64, intrinsics::i64_mul_with_overflow)
+
+checked_impl!(CheckedMul, checked_mul, i8, intrinsics::i8_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, i16, intrinsics::i16_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow)
+checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow)
+
/// Performs division that returns `None` instead of wrapping around on underflow or overflow.
pub trait CheckedDiv: Div<Self, Self> {
/// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
fn checked_div(&self, v: &Self) -> Option<Self>;
}
+macro_rules! checkeddiv_int_impl(
+ ($t:ty, $min:expr) => {
+ impl CheckedDiv for $t {
+ #[inline]
+ fn checked_div(&self, v: &$t) -> Option<$t> {
+ if *v == 0 || (*self == $min && *v == -1) {
+ None
+ } else {
+ Some(self / *v)
+ }
+ }
+ }
+ }
+)
+
+checkeddiv_int_impl!(int, int::MIN)
+checkeddiv_int_impl!(i8, i8::MIN)
+checkeddiv_int_impl!(i16, i16::MIN)
+checkeddiv_int_impl!(i32, i32::MIN)
+checkeddiv_int_impl!(i64, i64::MIN)
+
+macro_rules! checkeddiv_uint_impl(
+ ($($t:ty)*) => ($(
+ impl CheckedDiv for $t {
+ #[inline]
+ fn checked_div(&self, v: &$t) -> Option<$t> {
+ if *v == 0 {
+ None
+ } else {
+ Some(self / *v)
+ }
+ }
+ }
+ )*)
+)
+
+checkeddiv_uint_impl!(uint u8 u16 u32 u64)
+
/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
//! Operations and constants for unsigned 16-bits integers (`u16` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Unsigned, Num, Int, Primitive};
-use num::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
-use option::{Some, None, Option};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitAnd, BitOr, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
uint_module!(u16, i16, 16)
-
-impl CheckedAdd for u16 {
- #[inline]
- fn checked_add(&self, v: &u16) -> Option<u16> {
- unsafe {
- let (x, y) = intrinsics::u16_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for u16 {
- #[inline]
- fn checked_sub(&self, v: &u16) -> Option<u16> {
- unsafe {
- let (x, y) = intrinsics::u16_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for u16 {
- #[inline]
- fn checked_mul(&self, v: &u16) -> Option<u16> {
- unsafe {
- let (x, y) = intrinsics::u16_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for unsigned 32-bits integers (`u32` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Unsigned, Num, Int, Primitive};
-use num::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
-use option::{Some, None, Option};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitAnd, BitOr, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
uint_module!(u32, i32, 32)
-impl CheckedAdd for u32 {
- #[inline]
- fn checked_add(&self, v: &u32) -> Option<u32> {
- unsafe {
- let (x, y) = intrinsics::u32_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for u32 {
- #[inline]
- fn checked_sub(&self, v: &u32) -> Option<u32> {
- unsafe {
- let (x, y) = intrinsics::u32_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for u32 {
- #[inline]
- fn checked_mul(&self, v: &u32) -> Option<u32> {
- unsafe {
- let (x, y) = intrinsics::u32_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for unsigned 64-bits integer (`u64` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Unsigned, Num, Int, Primitive};
-use num::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
-use option::{Some, None, Option};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitAnd, BitOr, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
uint_module!(u64, i64, 64)
-impl CheckedAdd for u64 {
- #[inline]
- fn checked_add(&self, v: &u64) -> Option<u64> {
- unsafe {
- let (x, y) = intrinsics::u64_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for u64 {
- #[inline]
- fn checked_sub(&self, v: &u64) -> Option<u64> {
- unsafe {
- let (x, y) = intrinsics::u64_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for u64 {
- #[inline]
- fn checked_mul(&self, v: &u64) -> Option<u64> {
- unsafe {
- let (x, y) = intrinsics::u64_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for unsigned 8-bits integers (`u8` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Unsigned, Num, Int, Primitive};
-use num::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
-use option::{Some, None, Option};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitAnd, BitOr, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
uint_module!(u8, i8, 8)
-impl CheckedAdd for u8 {
- #[inline]
- fn checked_add(&self, v: &u8) -> Option<u8> {
- unsafe {
- let (x, y) = intrinsics::u8_add_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedSub for u8 {
- #[inline]
- fn checked_sub(&self, v: &u8) -> Option<u8> {
- unsafe {
- let (x, y) = intrinsics::u8_sub_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
-
-impl CheckedMul for u8 {
- #[inline]
- fn checked_mul(&self, v: &u8) -> Option<u8> {
- unsafe {
- let (x, y) = intrinsics::u8_mul_with_overflow(*self, *v);
- if y { None } else { Some(x) }
- }
- }
-}
//! Operations and constants for architecture-sized unsigned integers (`uint` type)
-use default::Default;
-use intrinsics;
-use num::{Bitwise, Bounded, Zero, One, Unsigned, Num, Int, Primitive};
-use num::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
-use option::{Some, None, Option};
-
-#[cfg(not(test))]
-use cmp::{Eq, Ord, TotalEq, TotalOrd, Less, Greater, Equal, Ordering};
-#[cfg(not(test))]
-use ops::{Add, Sub, Mul, Div, Rem, Neg, BitAnd, BitOr, BitXor};
-#[cfg(not(test))]
-use ops::{Shl, Shr, Not};
-
uint_module!(uint, int, ::int::BITS)
-#[cfg(target_word_size = "32")]
-impl CheckedAdd for uint {
- #[inline]
- fn checked_add(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u32_add_with_overflow(*self as u32, *v as u32);
- if y { None } else { Some(x as uint) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedAdd for uint {
- #[inline]
- fn checked_add(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u64_add_with_overflow(*self as u64, *v as u64);
- if y { None } else { Some(x as uint) }
- }
- }
-}
-
-#[cfg(target_word_size = "32")]
-impl CheckedSub for uint {
- #[inline]
- fn checked_sub(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u32_sub_with_overflow(*self as u32, *v as u32);
- if y { None } else { Some(x as uint) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedSub for uint {
- #[inline]
- fn checked_sub(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u64_sub_with_overflow(*self as u64, *v as u64);
- if y { None } else { Some(x as uint) }
- }
- }
-}
-
-#[cfg(target_word_size = "32")]
-impl CheckedMul for uint {
- #[inline]
- fn checked_mul(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u32_mul_with_overflow(*self as u32, *v as u32);
- if y { None } else { Some(x as uint) }
- }
- }
-}
-
-#[cfg(target_word_size = "64")]
-impl CheckedMul for uint {
- #[inline]
- fn checked_mul(&self, v: &uint) -> Option<uint> {
- unsafe {
- let (x, y) = intrinsics::u64_mul_with_overflow(*self as u64, *v as u64);
- if y { None } else { Some(x as uint) }
- }
- }
-}
pub static MIN: $T = 0 as $T;
pub static MAX: $T = 0 as $T - 1 as $T;
-#[cfg(not(test))]
-impl Ord for $T {
- #[inline]
- fn lt(&self, other: &$T) -> bool { *self < *other }
-}
-#[cfg(not(test))]
-impl TotalEq for $T {}
-#[cfg(not(test))]
-impl Eq for $T {
- #[inline]
- fn eq(&self, other: &$T) -> bool { *self == *other }
-}
-#[cfg(not(test))]
-impl TotalOrd for $T {
- #[inline]
- fn cmp(&self, other: &$T) -> Ordering {
- if *self < *other { Less }
- else if *self > *other { Greater }
- else { Equal }
- }
-}
-
-impl Num for $T {}
-
-impl Zero for $T {
- #[inline]
- fn zero() -> $T { 0 }
-
- #[inline]
- fn is_zero(&self) -> bool { *self == 0 }
-}
-
-impl One for $T {
- #[inline]
- fn one() -> $T { 1 }
-}
-
-#[cfg(not(test))]
-impl Add<$T,$T> for $T {
- #[inline]
- fn add(&self, other: &$T) -> $T { *self + *other }
-}
-
-#[cfg(not(test))]
-impl Sub<$T,$T> for $T {
- #[inline]
- fn sub(&self, other: &$T) -> $T { *self - *other }
-}
-
-#[cfg(not(test))]
-impl Mul<$T,$T> for $T {
- #[inline]
- fn mul(&self, other: &$T) -> $T { *self * *other }
-}
-
-#[cfg(not(test))]
-impl Div<$T,$T> for $T {
- #[inline]
- fn div(&self, other: &$T) -> $T { *self / *other }
-}
-
-#[cfg(not(test))]
-impl Rem<$T,$T> for $T {
- #[inline]
- fn rem(&self, other: &$T) -> $T { *self % *other }
-}
-
-#[cfg(not(test))]
-impl Neg<$T> for $T {
- #[inline]
- fn neg(&self) -> $T { -(*self as $T_SIGNED) as $T }
-}
-
-impl Unsigned for $T {}
-
-#[cfg(not(test))]
-impl BitOr<$T,$T> for $T {
- #[inline]
- fn bitor(&self, other: &$T) -> $T { *self | *other }
-}
-
-#[cfg(not(test))]
-impl BitAnd<$T,$T> for $T {
- #[inline]
- fn bitand(&self, other: &$T) -> $T { *self & *other }
-}
-
-#[cfg(not(test))]
-impl BitXor<$T,$T> for $T {
- #[inline]
- fn bitxor(&self, other: &$T) -> $T { *self ^ *other }
-}
-
-#[cfg(not(test))]
-impl Shl<$T,$T> for $T {
- #[inline]
- fn shl(&self, other: &$T) -> $T { *self << *other }
-}
-
-#[cfg(not(test))]
-impl Shr<$T,$T> for $T {
- #[inline]
- fn shr(&self, other: &$T) -> $T { *self >> *other }
-}
-
-#[cfg(not(test))]
-impl Not<$T> for $T {
- #[inline]
- fn not(&self) -> $T { !*self }
-}
-
-impl Bounded for $T {
- #[inline]
- fn min_value() -> $T { MIN }
-
- #[inline]
- fn max_value() -> $T { MAX }
-}
-
-impl Bitwise for $T {
- /// Returns the number of ones in the binary representation of the number.
- #[inline]
- fn count_ones(&self) -> $T {
- (*self as $T_SIGNED).count_ones() as $T
- }
-
- /// Returns the number of leading zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn leading_zeros(&self) -> $T {
- (*self as $T_SIGNED).leading_zeros() as $T
- }
-
- /// Returns the number of trailing zeros in the in the binary representation
- /// of the number.
- #[inline]
- fn trailing_zeros(&self) -> $T {
- (*self as $T_SIGNED).trailing_zeros() as $T
- }
-}
-
-impl CheckedDiv for $T {
- #[inline]
- fn checked_div(&self, v: &$T) -> Option<$T> {
- if *v == 0 {
- None
- } else {
- Some(self / *v)
- }
- }
-}
-
-impl Int for $T {}
-
-impl Primitive for $T {}
-
-impl Default for $T {
- #[inline]
- fn default() -> $T { 0 }
-}
-
#[cfg(test)]
mod tests {
use prelude::*;
* demonstrates adding and subtracting two `Point`s.
*
* ```rust
+ * #[deriving(Show)]
* struct Point {
* x: int,
* y: int
* }
* }
* fn main() {
- * println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
- * println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
+ * println!("{}", Point {x: 1, y: 0} + Point {x: 2, y: 3});
+ * println!("{}", Point {x: 1, y: 0} - Point {x: 2, y: 3});
* }
* ```
*
fn add(&self, rhs: &RHS) -> Result;
}
+macro_rules! add_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Add<$t, $t> for $t {
+ #[inline]
+ fn add(&self, other: &$t) -> $t { (*self) + (*other) }
+ }
+ )*)
+)
+
+add_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/**
*
* The `Sub` trait is used to specify the functionality of `-`.
fn sub(&self, rhs: &RHS) -> Result;
}
+macro_rules! sub_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Sub<$t, $t> for $t {
+ #[inline]
+ fn sub(&self, other: &$t) -> $t { (*self) - (*other) }
+ }
+ )*)
+)
+
+sub_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/**
*
* The `Mul` trait is used to specify the functionality of `*`.
fn mul(&self, rhs: &RHS) -> Result;
}
+macro_rules! mul_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Mul<$t, $t> for $t {
+ #[inline]
+ fn mul(&self, other: &$t) -> $t { (*self) * (*other) }
+ }
+ )*)
+)
+
+mul_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/**
*
* The `Div` trait is used to specify the functionality of `/`.
fn div(&self, rhs: &RHS) -> Result;
}
+macro_rules! div_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Div<$t, $t> for $t {
+ #[inline]
+ fn div(&self, other: &$t) -> $t { (*self) / (*other) }
+ }
+ )*)
+)
+
+div_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
+
/**
*
* The `Rem` trait is used to specify the functionality of `%`.
fn rem(&self, rhs: &RHS) -> Result;
}
+macro_rules! rem_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Rem<$t, $t> for $t {
+ #[inline]
+ fn rem(&self, other: &$t) -> $t { (*self) % (*other) }
+ }
+ )*)
+)
+
+macro_rules! rem_float_impl(
+ ($t:ty, $fmod:ident) => {
+ #[cfg(not(test))]
+ impl Rem<$t, $t> for $t {
+ #[inline]
+ fn rem(&self, other: &$t) -> $t {
+ extern { fn $fmod(a: $t, b: $t) -> $t; }
+ unsafe { $fmod(*self, *other) }
+ }
+ }
+ }
+)
+
+rem_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64)
+rem_float_impl!(f32, fmodf)
+rem_float_impl!(f64, fmod)
+
/**
*
* The `Neg` trait is used to specify the functionality of unary `-`.
fn neg(&self) -> Result;
}
+macro_rules! neg_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Neg<$t> for $t {
+ #[inline]
+ fn neg(&self) -> $t { -*self }
+ }
+ )*)
+)
+
+macro_rules! neg_uint_impl(
+ ($t:ty, $t_signed:ty) => {
+ #[cfg(not(test))]
+ impl Neg<$t> for $t {
+ #[inline]
+ fn neg(&self) -> $t { -(*self as $t_signed) as $t }
+ }
+ }
+)
+
+neg_impl!(int i8 i16 i32 i64 f32 f64)
+
+neg_uint_impl!(uint, int)
+neg_uint_impl!(u8, i8)
+neg_uint_impl!(u16, i16)
+neg_uint_impl!(u32, i32)
+neg_uint_impl!(u64, i64)
+
+
/**
*
* The `Not` trait is used to specify the functionality of unary `!`.
fn not(&self) -> Result;
}
+
+macro_rules! not_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Not<$t> for $t {
+ #[inline]
+ fn not(&self) -> $t { !*self }
+ }
+ )*)
+)
+
+not_impl!(bool uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `BitAnd` trait is used to specify the functionality of `&`.
fn bitand(&self, rhs: &RHS) -> Result;
}
+macro_rules! bitand_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl BitAnd<$t, $t> for $t {
+ #[inline]
+ fn bitand(&self, rhs: &$t) -> $t { (*self) & (*rhs) }
+ }
+ )*)
+)
+
+bitand_impl!(bool uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `BitOr` trait is used to specify the functionality of `|`.
fn bitor(&self, rhs: &RHS) -> Result;
}
+macro_rules! bitor_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl BitOr<$t,$t> for $t {
+ #[inline]
+ fn bitor(&self, rhs: &$t) -> $t { (*self) | (*rhs) }
+ }
+ )*)
+)
+
+bitor_impl!(bool uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `BitXor` trait is used to specify the functionality of `^`.
fn bitxor(&self, rhs: &RHS) -> Result;
}
+macro_rules! bitxor_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl BitXor<$t, $t> for $t {
+ #[inline]
+ fn bitxor(&self, other: &$t) -> $t { (*self) ^ (*other) }
+ }
+ )*)
+)
+
+bitxor_impl!(bool uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `Shl` trait is used to specify the functionality of `<<`.
fn shl(&self, rhs: &RHS) -> Result;
}
+macro_rules! shl_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Shl<$t, $t> for $t {
+ #[inline]
+ fn shl(&self, other: &$t) -> $t { (*self) << (*other) }
+ }
+ )*)
+)
+
+shl_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `Shr` trait is used to specify the functionality of `>>`.
fn shr(&self, rhs: &RHS) -> Result;
}
+macro_rules! shr_impl(
+ ($($t:ty)*) => ($(
+ #[cfg(not(test))]
+ impl Shr<$t, $t> for $t {
+ #[inline]
+ fn shr(&self, other: &$t) -> $t { (*self) >> (*other) }
+ }
+ )*)
+)
+
+shr_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64)
+
/**
*
* The `Index` trait is used to specify the functionality of indexing operations
/// to the value inside the original.
///
/// ```
- /// let num_as_str: Option<String> = Some("10".to_strbuf());
+ /// let num_as_str: Option<String> = Some("10".to_string());
/// // First, cast `Option<String>` to `Option<&String>` 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<String>` into an `Option<uint>`, consuming the original:
///
/// ```
- /// let num_as_str: Option<String> = Some("10".to_strbuf());
+ /// let num_as_str: Option<String> = Some("10".to_string());
/// // `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".to_strbuf();
+ let x = "test".to_string();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
- let s = Some("hello".to_strbuf()).unwrap();
+ let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
* ```rust
* let v = &[1,2,3,4];
* for win in v.windows(2) {
- * println!("{:?}", win);
+ * println!("{}", win);
* }
* ```
*
* ```rust
* let v = &[1,2,3,4,5];
* for win in v.chunks(2) {
- * println!("{:?}", win);
+ * println!("{}", win);
* }
* ```
*
/// # Example
///
/// ```rust
- /// let mut v = ~["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
+ /// let mut v = ~["foo".to_string(), "bar".to_string(), "baz".to_string()];
///
/// unsafe {
- /// // `"baz".to_owned()` is deallocated.
- /// v.unsafe_set(2, "qux".to_owned());
+ /// // `"baz".to_string()` is deallocated.
+ /// v.unsafe_set(2, "qux".to_string());
///
/// // Out of bounds: could cause a crash, or overwriting
/// // other data, or something else.
- /// // v.unsafe_set(10, "oops".to_owned());
+ /// // v.unsafe_set(10, "oops".to_string());
/// }
/// ```
unsafe fn unsafe_set(self, index: uint, val: T);
/// # Example
///
/// ```rust
- /// let mut v = ["foo".to_owned(), "bar".to_owned()];
+ /// let mut v = ["foo".to_string(), "bar".to_string()];
///
- /// // memory leak! `"bar".to_owned()` is not deallocated.
- /// unsafe { v.init_elem(1, "baz".to_owned()); }
+ /// // memory leak! `"bar".to_string()` is not deallocated.
+ /// unsafe { v.init_elem(1, "baz".to_string()); }
/// ```
unsafe fn init_elem(self, i: uint, val: T);
/// An iterator that decodes UTF-16 encoded codepoints from a vector
/// of `u16`s.
#[deriving(Clone)]
-pub struct UTF16Items<'a> {
+pub struct Utf16Items<'a> {
iter: slice::Items<'a, u16>
}
/// The possibilities for values decoded from a `u16` stream.
#[deriving(Eq, TotalEq, Clone, Show)]
-pub enum UTF16Item {
+pub enum Utf16Item {
/// A valid codepoint.
ScalarValue(char),
/// An invalid surrogate without its pair.
LoneSurrogate(u16)
}
-impl UTF16Item {
+impl Utf16Item {
/// Convert `self` to a `char`, taking `LoneSurrogate`s to the
/// replacement character (U+FFFD).
#[inline]
}
}
-impl<'a> Iterator<UTF16Item> for UTF16Items<'a> {
- fn next(&mut self) -> Option<UTF16Item> {
+impl<'a> Iterator<Utf16Item> for Utf16Items<'a> {
+ fn next(&mut self) -> Option<Utf16Item> {
let u = match self.iter.next() {
Some(u) => *u,
None => return None
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// ```
-pub fn utf16_items<'a>(v: &'a [u16]) -> UTF16Items<'a> {
- UTF16Items { iter : v.iter() }
+pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
+ Utf16Items { iter : v.iter() }
}
/// Return a slice of `v` ending at (and not including) the first NUL
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Implementation of the `{:?}` format qualifier
+//!
+//! This module contains the `Poly` trait which is used to implement the `{:?}`
+//! format expression in formatting macros. This trait is defined for all types
+//! automatically, so it is likely not necessary to use this module manually
+
+use std::fmt;
+
+use repr;
+
+/// Format trait for the `?` character
+pub trait Poly {
+ /// Formats the value using the given formatter.
+ #[experimental]
+ fn fmt(&self, &mut fmt::Formatter) -> fmt::Result;
+}
+
+#[doc(hidden)]
+pub fn secret_poly<T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result {
+ // FIXME #11938 - UFCS would make us able call the this method
+ // directly Poly::fmt(x, fmt).
+ x.fmt(fmt)
+}
+
+impl<T> Poly for T {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match (f.width, f.precision) {
+ (None, None) => {
+ match repr::write_repr(f, self) {
+ Ok(()) => Ok(()),
+ Err(..) => Err(fmt::WriteError),
+ }
+ }
+
+ // If we have a specified width for formatting, then we have to make
+ // this allocation of a new string
+ _ => {
+ let s = repr::repr_to_str(self);
+ f.pad(s.as_slice())
+ }
+ }
+ }
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Debugging utilities for Rust programs
+//!
+//! This crate is intended to provide useful functionality when debugging
+//! programs, such as reflection for printing values. This crate is currently
+//! entirely experimental as its makeup will likely change over time.
+//! Additionally, it is not guaranteed that functionality such as reflection
+//! will persist into the future.
+
+#![crate_id = "debug#0.11.0-pre"]
+#![license = "MIT/ASL2"]
+#![crate_type = "rlib"]
+#![crate_type = "dylib"]
+#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
+ html_favicon_url = "http://www.rust-lang.org/favicon.ico",
+ html_root_url = "http://doc.rust-lang.org/")]
+#![experimental]
+#![feature(managed_boxes, macro_rules, quad_precision_float)]
+#![allow(experimental)]
+
+pub mod fmt;
+pub mod reflect;
+pub mod repr;
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+/*!
+
+Runtime type reflection
+
+*/
+
+#![allow(missing_doc)]
+
+use std::intrinsics::{Disr, Opaque, TyDesc, TyVisitor};
+use std::mem;
+
+/**
+ * Trait for visitor that wishes to reflect on data.
+ *
+ * To use this, create a struct that encapsulates the set of pointers you wish
+ * to walk through a data structure, and implement both `MovePtr` for it as well
+ * as `TyVisitor`; then build a MovePtrAdaptor wrapped around your struct.
+ */
+pub trait MovePtr {
+ fn move_ptr(&mut self, adjustment: |*u8| -> *u8);
+ fn push_ptr(&mut self);
+ fn pop_ptr(&mut self);
+}
+
+/// Helper function for alignment calculation.
+#[inline]
+pub fn align(size: uint, align: uint) -> uint {
+ ((size + align) - 1u) & !(align - 1u)
+}
+
+/// Adaptor to wrap around visitors implementing MovePtr.
+pub struct MovePtrAdaptor<V> {
+ inner: V
+}
+pub fn MovePtrAdaptor<V:TyVisitor + MovePtr>(v: V) -> MovePtrAdaptor<V> {
+ MovePtrAdaptor { inner: v }
+}
+
+impl<V:TyVisitor + MovePtr> MovePtrAdaptor<V> {
+ #[inline]
+ pub fn bump(&mut self, sz: uint) {
+ self.inner.move_ptr(|p| ((p as uint) + sz) as *u8)
+ }
+
+ #[inline]
+ pub fn align(&mut self, a: uint) {
+ self.inner.move_ptr(|p| align(p as uint, a) as *u8)
+ }
+
+ #[inline]
+ pub fn align_to<T>(&mut self) {
+ self.align(mem::min_align_of::<T>());
+ }
+
+ #[inline]
+ pub fn bump_past<T>(&mut self) {
+ self.bump(mem::size_of::<T>());
+ }
+
+ pub fn unwrap(self) -> V { self.inner }
+}
+
+/// Abstract type-directed pointer-movement using the MovePtr trait
+impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> {
+ fn visit_bot(&mut self) -> bool {
+ self.align_to::<()>();
+ if ! self.inner.visit_bot() { return false; }
+ self.bump_past::<()>();
+ true
+ }
+
+ fn visit_nil(&mut self) -> bool {
+ self.align_to::<()>();
+ if ! self.inner.visit_nil() { return false; }
+ self.bump_past::<()>();
+ true
+ }
+
+ fn visit_bool(&mut self) -> bool {
+ self.align_to::<bool>();
+ if ! self.inner.visit_bool() { return false; }
+ self.bump_past::<bool>();
+ true
+ }
+
+ fn visit_int(&mut self) -> bool {
+ self.align_to::<int>();
+ if ! self.inner.visit_int() { return false; }
+ self.bump_past::<int>();
+ true
+ }
+
+ fn visit_i8(&mut self) -> bool {
+ self.align_to::<i8>();
+ if ! self.inner.visit_i8() { return false; }
+ self.bump_past::<i8>();
+ true
+ }
+
+ fn visit_i16(&mut self) -> bool {
+ self.align_to::<i16>();
+ if ! self.inner.visit_i16() { return false; }
+ self.bump_past::<i16>();
+ true
+ }
+
+ fn visit_i32(&mut self) -> bool {
+ self.align_to::<i32>();
+ if ! self.inner.visit_i32() { return false; }
+ self.bump_past::<i32>();
+ true
+ }
+
+ fn visit_i64(&mut self) -> bool {
+ self.align_to::<i64>();
+ if ! self.inner.visit_i64() { return false; }
+ self.bump_past::<i64>();
+ true
+ }
+
+ fn visit_uint(&mut self) -> bool {
+ self.align_to::<uint>();
+ if ! self.inner.visit_uint() { return false; }
+ self.bump_past::<uint>();
+ true
+ }
+
+ fn visit_u8(&mut self) -> bool {
+ self.align_to::<u8>();
+ if ! self.inner.visit_u8() { return false; }
+ self.bump_past::<u8>();
+ true
+ }
+
+ fn visit_u16(&mut self) -> bool {
+ self.align_to::<u16>();
+ if ! self.inner.visit_u16() { return false; }
+ self.bump_past::<u16>();
+ true
+ }
+
+ fn visit_u32(&mut self) -> bool {
+ self.align_to::<u32>();
+ if ! self.inner.visit_u32() { return false; }
+ self.bump_past::<u32>();
+ true
+ }
+
+ fn visit_u64(&mut self) -> bool {
+ self.align_to::<u64>();
+ if ! self.inner.visit_u64() { return false; }
+ self.bump_past::<u64>();
+ true
+ }
+
+ fn visit_f32(&mut self) -> bool {
+ self.align_to::<f32>();
+ if ! self.inner.visit_f32() { return false; }
+ self.bump_past::<f32>();
+ true
+ }
+
+ fn visit_f64(&mut self) -> bool {
+ self.align_to::<f64>();
+ if ! self.inner.visit_f64() { return false; }
+ self.bump_past::<f64>();
+ true
+ }
+
+ fn visit_f128(&mut self) -> bool {
+ self.align_to::<f128>();
+ if ! self.inner.visit_f128() { return false; }
+ self.bump_past::<f128>();
+ true
+ }
+
+ fn visit_char(&mut self) -> bool {
+ self.align_to::<char>();
+ if ! self.inner.visit_char() { return false; }
+ self.bump_past::<char>();
+ true
+ }
+
+ fn visit_estr_box(&mut self) -> bool {
+ true
+ }
+
+ fn visit_estr_uniq(&mut self) -> bool {
+ self.align_to::<~str>();
+ if ! self.inner.visit_estr_uniq() { return false; }
+ self.bump_past::<~str>();
+ true
+ }
+
+ fn visit_estr_slice(&mut self) -> bool {
+ self.align_to::<&'static str>();
+ if ! self.inner.visit_estr_slice() { return false; }
+ self.bump_past::<&'static str>();
+ true
+ }
+
+ fn visit_estr_fixed(&mut self, n: uint,
+ sz: uint,
+ align: uint) -> bool {
+ self.align(align);
+ if ! self.inner.visit_estr_fixed(n, sz, align) { return false; }
+ self.bump(sz);
+ true
+ }
+
+ fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.align_to::<@u8>();
+ if ! self.inner.visit_box(mtbl, inner) { return false; }
+ self.bump_past::<@u8>();
+ true
+ }
+
+ fn visit_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.align_to::<Box<u8>>();
+ if ! self.inner.visit_uniq(mtbl, inner) { return false; }
+ self.bump_past::<Box<u8>>();
+ true
+ }
+
+ fn visit_ptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.align_to::<*u8>();
+ if ! self.inner.visit_ptr(mtbl, inner) { return false; }
+ self.bump_past::<*u8>();
+ true
+ }
+
+ fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.align_to::<&'static u8>();
+ if ! self.inner.visit_rptr(mtbl, inner) { return false; }
+ self.bump_past::<&'static u8>();
+ 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.align_to::<~[u8]>();
+ if ! self.inner.visit_evec_uniq(mtbl, inner) { return false; }
+ self.bump_past::<~[u8]>();
+ true
+ }
+
+ fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.align_to::<&'static [u8]>();
+ if ! self.inner.visit_evec_slice(mtbl, inner) { return false; }
+ self.bump_past::<&'static [u8]>();
+ true
+ }
+
+ fn visit_evec_fixed(&mut self, n: uint, sz: uint, align: uint,
+ mtbl: uint, inner: *TyDesc) -> bool {
+ self.align(align);
+ if ! self.inner.visit_evec_fixed(n, sz, align, mtbl, inner) {
+ return false;
+ }
+ self.bump(sz);
+ true
+ }
+
+ fn visit_enter_rec(&mut self, n_fields: uint, sz: uint, align: uint) -> bool {
+ self.align(align);
+ if ! self.inner.visit_enter_rec(n_fields, sz, align) { return false; }
+ true
+ }
+
+ fn visit_rec_field(&mut self, i: uint, name: &str,
+ mtbl: uint, inner: *TyDesc) -> bool {
+ unsafe { self.align((*inner).align); }
+ if ! self.inner.visit_rec_field(i, name, mtbl, inner) {
+ return false;
+ }
+ unsafe { self.bump((*inner).size); }
+ true
+ }
+
+ fn visit_leave_rec(&mut self, n_fields: uint, sz: uint, align: uint) -> bool {
+ if ! self.inner.visit_leave_rec(n_fields, sz, align) { return false; }
+ true
+ }
+
+ fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint, sz: uint,
+ align: uint) -> bool {
+ self.align(align);
+ if ! self.inner.visit_enter_class(name, named_fields, n_fields, sz, align) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_class_field(&mut self, i: uint, name: &str, named: bool, mtbl: uint,
+ inner: *TyDesc) -> bool {
+ unsafe { self.align((*inner).align); }
+ if ! self.inner.visit_class_field(i, name, named, mtbl, inner) {
+ return false;
+ }
+ unsafe { self.bump((*inner).size); }
+ true
+ }
+
+ fn visit_leave_class(&mut self, name: &str, named_fields: bool, n_fields: uint, sz: uint,
+ align: uint) -> bool {
+ if ! self.inner.visit_leave_class(name, named_fields, n_fields, sz, align) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_enter_tup(&mut self, n_fields: uint, sz: uint, align: uint) -> bool {
+ self.align(align);
+ if ! self.inner.visit_enter_tup(n_fields, sz, align) { return false; }
+ true
+ }
+
+ fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool {
+ unsafe { self.align((*inner).align); }
+ if ! self.inner.visit_tup_field(i, inner) { return false; }
+ unsafe { self.bump((*inner).size); }
+ true
+ }
+
+ fn visit_leave_tup(&mut self, n_fields: uint, sz: uint, align: uint) -> bool {
+ if ! self.inner.visit_leave_tup(n_fields, sz, align) { return false; }
+ true
+ }
+
+ fn visit_enter_fn(&mut self, purity: uint, proto: uint,
+ n_inputs: uint, retstyle: uint) -> bool {
+ if ! self.inner.visit_enter_fn(purity, proto, n_inputs, retstyle) {
+ return false
+ }
+ true
+ }
+
+ fn visit_fn_input(&mut self, i: uint, mode: uint, inner: *TyDesc) -> bool {
+ if ! self.inner.visit_fn_input(i, mode, inner) { return false; }
+ true
+ }
+
+ fn visit_fn_output(&mut self, retstyle: uint, variadic: bool, inner: *TyDesc) -> bool {
+ if ! self.inner.visit_fn_output(retstyle, variadic, inner) { return false; }
+ true
+ }
+
+ fn visit_leave_fn(&mut self, purity: uint, proto: uint,
+ n_inputs: uint, retstyle: uint) -> bool {
+ if ! self.inner.visit_leave_fn(purity, proto, n_inputs, retstyle) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_enter_enum(&mut self, n_variants: uint,
+ get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
+ sz: uint, align: uint)
+ -> bool {
+ self.align(align);
+ if ! self.inner.visit_enter_enum(n_variants, get_disr, sz, align) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_enter_enum_variant(&mut self, variant: uint,
+ disr_val: Disr,
+ n_fields: uint,
+ name: &str) -> bool {
+ if ! self.inner.visit_enter_enum_variant(variant, disr_val,
+ n_fields, name) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_enum_variant_field(&mut self, i: uint, offset: uint, inner: *TyDesc) -> bool {
+ self.inner.push_ptr();
+ self.bump(offset);
+ if ! self.inner.visit_enum_variant_field(i, offset, inner) { return false; }
+ self.inner.pop_ptr();
+ true
+ }
+
+ fn visit_leave_enum_variant(&mut self, variant: uint,
+ disr_val: Disr,
+ n_fields: uint,
+ name: &str) -> bool {
+ if ! self.inner.visit_leave_enum_variant(variant, disr_val,
+ n_fields, name) {
+ return false;
+ }
+ true
+ }
+
+ fn visit_leave_enum(&mut self, n_variants: uint,
+ get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
+ sz: uint, align: uint) -> bool {
+ if ! self.inner.visit_leave_enum(n_variants, get_disr, sz, align) {
+ return false;
+ }
+ self.bump(sz);
+ true
+ }
+
+ fn visit_trait(&mut self, name: &str) -> bool {
+ self.align_to::<Box<TyVisitor>>();
+ if ! self.inner.visit_trait(name) { return false; }
+ self.bump_past::<Box<TyVisitor>>();
+ true
+ }
+
+ fn visit_param(&mut self, i: uint) -> bool {
+ if ! self.inner.visit_param(i) { return false; }
+ true
+ }
+
+ fn visit_self(&mut self) -> bool {
+ self.align_to::<&'static u8>();
+ if ! self.inner.visit_self() { return false; }
+ self.align_to::<&'static u8>();
+ true
+ }
+}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+/*!
+
+More runtime type reflection
+
+*/
+
+use std::char;
+use std::intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
+use std::io;
+use std::mem;
+use std::raw;
+
+use reflect;
+use reflect::{MovePtr, align};
+
+macro_rules! try( ($me:expr, $e:expr) => (
+ match $e {
+ Ok(()) => {},
+ Err(e) => { $me.last_err = Some(e); return false; }
+ }
+) )
+
+/// Representations
+
+trait Repr {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()>;
+}
+
+impl Repr for () {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
+ writer.write("()".as_bytes())
+ }
+}
+
+impl Repr for bool {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
+ let s = if *self { "true" } else { "false" };
+ writer.write(s.as_bytes())
+ }
+}
+
+impl Repr for int {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
+ write!(writer, "{}", *self)
+ }
+}
+
+macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
+ write!(writer, "{}{}", *self, $suffix)
+ }
+}))
+
+int_repr!(i8, "i8")
+int_repr!(i16, "i16")
+int_repr!(i32, "i32")
+int_repr!(i64, "i64")
+int_repr!(uint, "u")
+int_repr!(u8, "u8")
+int_repr!(u16, "u16")
+int_repr!(u32, "u32")
+int_repr!(u64, "u64")
+
+macro_rules! num_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
+ fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
+ let s = self.to_str();
+ writer.write(s.as_bytes()).and_then(|()| {
+ writer.write(bytes!($suffix))
+ })
+ }
+}))
+
+num_repr!(f32, "f32")
+num_repr!(f64, "f64")
+
+// New implementation using reflect::MovePtr
+
+enum VariantState {
+ SearchingFor(Disr),
+ Matched,
+ AlreadyFound
+}
+
+pub struct ReprVisitor<'a> {
+ ptr: *u8,
+ ptr_stk: Vec<*u8>,
+ var_stk: Vec<VariantState>,
+ writer: &'a mut io::Writer,
+ last_err: Option<io::IoError>,
+}
+
+pub fn ReprVisitor<'a>(ptr: *u8,
+ writer: &'a mut io::Writer) -> ReprVisitor<'a> {
+ ReprVisitor {
+ ptr: ptr,
+ ptr_stk: vec!(),
+ var_stk: vec!(),
+ writer: writer,
+ last_err: None,
+ }
+}
+
+impl<'a> MovePtr for ReprVisitor<'a> {
+ #[inline]
+ fn move_ptr(&mut self, adjustment: |*u8| -> *u8) {
+ self.ptr = adjustment(self.ptr);
+ }
+ fn push_ptr(&mut self) {
+ self.ptr_stk.push(self.ptr);
+ }
+ fn pop_ptr(&mut self) {
+ self.ptr = self.ptr_stk.pop().unwrap();
+ }
+}
+
+impl<'a> ReprVisitor<'a> {
+ // Various helpers for the TyVisitor impl
+
+ #[inline]
+ pub fn get<T>(&mut self, f: |&mut ReprVisitor, &T| -> bool) -> bool {
+ unsafe {
+ f(self, mem::transmute::<*u8,&T>(self.ptr))
+ }
+ }
+
+ #[inline]
+ pub fn visit_inner(&mut self, inner: *TyDesc) -> bool {
+ self.visit_ptr_inner(self.ptr, inner)
+ }
+
+ #[inline]
+ pub fn visit_ptr_inner(&mut self, ptr: *u8, inner: *TyDesc) -> bool {
+ unsafe {
+ // This should call the constructor up above, but due to limiting
+ // issues we have to recreate it here.
+ let u = ReprVisitor {
+ ptr: ptr,
+ ptr_stk: vec!(),
+ var_stk: vec!(),
+ writer: mem::transmute_copy(&self.writer),
+ last_err: None,
+ };
+ let mut v = reflect::MovePtrAdaptor(u);
+ // Obviously this should not be a thing, but blame #8401 for now
+ visit_tydesc(inner, &mut v as &mut TyVisitor);
+ match v.unwrap().last_err {
+ Some(e) => {
+ self.last_err = Some(e);
+ false
+ }
+ None => true,
+ }
+ }
+ }
+
+ #[inline]
+ pub fn write<T:Repr>(&mut self) -> bool {
+ self.get(|this, v:&T| {
+ try!(this, v.write_repr(this.writer));
+ true
+ })
+ }
+
+ pub fn write_escaped_slice(&mut self, slice: &str) -> bool {
+ try!(self, self.writer.write(['"' as u8]));
+ for ch in slice.chars() {
+ if !self.write_escaped_char(ch, true) { return false }
+ }
+ try!(self, self.writer.write(['"' as u8]));
+ true
+ }
+
+ pub fn write_mut_qualifier(&mut self, mtbl: uint) -> bool {
+ if mtbl == 0 {
+ try!(self, self.writer.write("mut ".as_bytes()));
+ } else if mtbl == 1 {
+ // skip, this is ast::m_imm
+ } else {
+ fail!("invalid mutability value");
+ }
+ true
+ }
+
+ pub fn write_vec_range(&mut self, ptr: *(), len: uint, inner: *TyDesc) -> bool {
+ let mut p = ptr as *u8;
+ let (sz, al) = unsafe { ((*inner).size, (*inner).align) };
+ try!(self, self.writer.write(['[' as u8]));
+ let mut first = true;
+ let mut left = len;
+ // unit structs have 0 size, and don't loop forever.
+ let dec = if sz == 0 {1} else {sz};
+ while left > 0 {
+ if first {
+ first = false;
+ } else {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ self.visit_ptr_inner(p as *u8, inner);
+ p = align(unsafe { p.offset(sz as int) as uint }, al) as *u8;
+ left -= dec;
+ }
+ try!(self, self.writer.write([']' as u8]));
+ true
+ }
+
+ pub fn write_unboxed_vec_repr(&mut self, _: uint, v: &raw::Vec<()>, inner: *TyDesc) -> bool {
+ self.write_vec_range(&v.data, v.fill, inner)
+ }
+
+ fn write_escaped_char(&mut self, ch: char, is_str: bool) -> bool {
+ try!(self, match ch {
+ '\t' => self.writer.write("\\t".as_bytes()),
+ '\r' => self.writer.write("\\r".as_bytes()),
+ '\n' => self.writer.write("\\n".as_bytes()),
+ '\\' => self.writer.write("\\\\".as_bytes()),
+ '\'' => {
+ if is_str {
+ self.writer.write("'".as_bytes())
+ } else {
+ self.writer.write("\\'".as_bytes())
+ }
+ }
+ '"' => {
+ if is_str {
+ self.writer.write("\\\"".as_bytes())
+ } else {
+ self.writer.write("\"".as_bytes())
+ }
+ }
+ '\x20'..'\x7e' => self.writer.write([ch as u8]),
+ _ => {
+ char::escape_unicode(ch, |c| {
+ let _ = self.writer.write([c as u8]);
+ });
+ Ok(())
+ }
+ });
+ return true;
+ }
+}
+
+impl<'a> TyVisitor for ReprVisitor<'a> {
+ fn visit_bot(&mut self) -> bool {
+ try!(self, self.writer.write("!".as_bytes()));
+ true
+ }
+ fn visit_nil(&mut self) -> bool { self.write::<()>() }
+ fn visit_bool(&mut self) -> bool { self.write::<bool>() }
+ fn visit_int(&mut self) -> bool { self.write::<int>() }
+ fn visit_i8(&mut self) -> bool { self.write::<i8>() }
+ fn visit_i16(&mut self) -> bool { self.write::<i16>() }
+ fn visit_i32(&mut self) -> bool { self.write::<i32>() }
+ fn visit_i64(&mut self) -> bool { self.write::<i64>() }
+
+ fn visit_uint(&mut self) -> bool { self.write::<uint>() }
+ fn visit_u8(&mut self) -> bool { self.write::<u8>() }
+ fn visit_u16(&mut self) -> bool { self.write::<u16>() }
+ fn visit_u32(&mut self) -> bool { self.write::<u32>() }
+ fn visit_u64(&mut self) -> bool { self.write::<u64>() }
+
+ fn visit_f32(&mut self) -> bool { self.write::<f32>() }
+ fn visit_f64(&mut self) -> bool { self.write::<f64>() }
+ fn visit_f128(&mut self) -> bool { fail!("not implemented") }
+
+ fn visit_char(&mut self) -> bool {
+ self.get::<char>(|this, &ch| {
+ try!(this, this.writer.write(['\'' as u8]));
+ if !this.write_escaped_char(ch, false) { return false }
+ try!(this, this.writer.write(['\'' as u8]));
+ true
+ })
+ }
+
+ fn visit_estr_box(&mut self) -> bool {
+ true
+ }
+
+ fn visit_estr_uniq(&mut self) -> bool {
+ self.get::<~str>(|this, s| {
+ try!(this, this.writer.write(['~' as u8]));
+ this.write_escaped_slice(*s)
+ })
+ }
+
+ fn visit_estr_slice(&mut self) -> bool {
+ self.get::<&str>(|this, s| this.write_escaped_slice(*s))
+ }
+
+ // Type no longer exists, vestigial function.
+ fn visit_estr_fixed(&mut self, _n: uint, _sz: uint,
+ _align: uint) -> bool { fail!(); }
+
+ fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ try!(self, self.writer.write(['@' as u8]));
+ self.write_mut_qualifier(mtbl);
+ self.get::<&raw::Box<()>>(|this, b| {
+ let p = &b.data as *() as *u8;
+ this.visit_ptr_inner(p, inner)
+ })
+ }
+
+ fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
+ try!(self, self.writer.write("box ".as_bytes()));
+ self.get::<*u8>(|this, b| {
+ this.visit_ptr_inner(*b, inner)
+ })
+ }
+
+ fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool {
+ self.get::<*u8>(|this, p| {
+ try!(this, write!(this.writer, "({} as *", *p));
+ this.write_mut_qualifier(mtbl);
+ try!(this, this.writer.write("())".as_bytes()));
+ true
+ })
+ }
+
+ fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ try!(self, self.writer.write(['&' as u8]));
+ self.write_mut_qualifier(mtbl);
+ self.get::<*u8>(|this, p| {
+ this.visit_ptr_inner(*p, inner)
+ })
+ }
+
+ fn visit_evec_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.get::<&raw::Box<raw::Vec<()>>>(|this, b| {
+ try!(this, this.writer.write(['@' as u8]));
+ this.write_mut_qualifier(mtbl);
+ this.write_unboxed_vec_repr(mtbl, &b.data, inner)
+ })
+ }
+
+ fn visit_evec_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.get::<&raw::Vec<()>>(|this, b| {
+ try!(this, this.writer.write("box ".as_bytes()));
+ this.write_unboxed_vec_repr(mtbl, *b, inner)
+ })
+ }
+
+ fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
+ self.get::<raw::Slice<()>>(|this, s| {
+ try!(this, this.writer.write(['&' as u8]));
+ this.write_mut_qualifier(mtbl);
+ let size = unsafe {
+ if (*inner).size == 0 { 1 } else { (*inner).size }
+ };
+ this.write_vec_range(s.data, s.len * size, inner)
+ })
+ }
+
+ fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
+ _: uint, inner: *TyDesc) -> bool {
+ let assumed_size = if sz == 0 { n } else { sz };
+ self.get::<()>(|this, b| {
+ this.write_vec_range(b, assumed_size, inner)
+ })
+ }
+
+ fn visit_enter_rec(&mut self, _n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ try!(self, self.writer.write(['{' as u8]));
+ true
+ }
+
+ fn visit_rec_field(&mut self, i: uint, name: &str,
+ mtbl: uint, inner: *TyDesc) -> bool {
+ if i != 0 {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ self.write_mut_qualifier(mtbl);
+ try!(self, self.writer.write(name.as_bytes()));
+ try!(self, self.writer.write(": ".as_bytes()));
+ self.visit_inner(inner);
+ true
+ }
+
+ fn visit_leave_rec(&mut self, _n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ try!(self, self.writer.write(['}' as u8]));
+ true
+ }
+
+ fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ try!(self, self.writer.write(name.as_bytes()));
+ if n_fields != 0 {
+ if named_fields {
+ try!(self, self.writer.write(['{' as u8]));
+ } else {
+ try!(self, self.writer.write(['(' as u8]));
+ }
+ }
+ true
+ }
+
+ fn visit_class_field(&mut self, i: uint, name: &str, named: bool,
+ _mtbl: uint, inner: *TyDesc) -> bool {
+ if i != 0 {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ if named {
+ try!(self, self.writer.write(name.as_bytes()));
+ try!(self, self.writer.write(": ".as_bytes()));
+ }
+ self.visit_inner(inner);
+ true
+ }
+
+ fn visit_leave_class(&mut self, _name: &str, named_fields: bool, n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ if n_fields != 0 {
+ if named_fields {
+ try!(self, self.writer.write(['}' as u8]));
+ } else {
+ try!(self, self.writer.write([')' as u8]));
+ }
+ }
+ true
+ }
+
+ fn visit_enter_tup(&mut self, _n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ try!(self, self.writer.write(['(' as u8]));
+ true
+ }
+
+ fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool {
+ if i != 0 {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ self.visit_inner(inner);
+ true
+ }
+
+ fn visit_leave_tup(&mut self, _n_fields: uint,
+ _sz: uint, _align: uint) -> bool {
+ if _n_fields == 1 {
+ try!(self, self.writer.write([',' as u8]));
+ }
+ try!(self, self.writer.write([')' as u8]));
+ true
+ }
+
+ fn visit_enter_enum(&mut self,
+ _n_variants: uint,
+ get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
+ _sz: uint,
+ _align: uint) -> bool {
+ let disr = unsafe {
+ get_disr(mem::transmute(self.ptr))
+ };
+ self.var_stk.push(SearchingFor(disr));
+ true
+ }
+
+ fn visit_enter_enum_variant(&mut self, _variant: uint,
+ disr_val: Disr,
+ n_fields: uint,
+ name: &str) -> bool {
+ let mut write = false;
+ match self.var_stk.pop().unwrap() {
+ SearchingFor(sought) => {
+ if disr_val == sought {
+ self.var_stk.push(Matched);
+ write = true;
+ } else {
+ self.var_stk.push(SearchingFor(sought));
+ }
+ }
+ Matched | AlreadyFound => {
+ self.var_stk.push(AlreadyFound);
+ }
+ }
+
+ if write {
+ try!(self, self.writer.write(name.as_bytes()));
+ if n_fields > 0 {
+ try!(self, self.writer.write(['(' as u8]));
+ }
+ }
+ true
+ }
+
+ fn visit_enum_variant_field(&mut self,
+ i: uint,
+ _offset: uint,
+ inner: *TyDesc)
+ -> bool {
+ match *self.var_stk.get(self.var_stk.len() - 1) {
+ Matched => {
+ if i != 0 {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ if ! self.visit_inner(inner) {
+ return false;
+ }
+ }
+ _ => ()
+ }
+ true
+ }
+
+ fn visit_leave_enum_variant(&mut self, _variant: uint,
+ _disr_val: Disr,
+ n_fields: uint,
+ _name: &str) -> bool {
+ match *self.var_stk.get(self.var_stk.len() - 1) {
+ Matched => {
+ if n_fields > 0 {
+ try!(self, self.writer.write([')' as u8]));
+ }
+ }
+ _ => ()
+ }
+ true
+ }
+
+ fn visit_leave_enum(&mut self,
+ _n_variants: uint,
+ _get_disr: unsafe extern fn(ptr: *Opaque) -> Disr,
+ _sz: uint,
+ _align: uint)
+ -> bool {
+ match self.var_stk.pop().unwrap() {
+ SearchingFor(..) => fail!("enum value matched no variant"),
+ _ => true
+ }
+ }
+
+ fn visit_enter_fn(&mut self, _purity: uint, _proto: uint,
+ _n_inputs: uint, _retstyle: uint) -> bool {
+ try!(self, self.writer.write("fn(".as_bytes()));
+ true
+ }
+
+ fn visit_fn_input(&mut self, i: uint, _mode: uint, inner: *TyDesc) -> bool {
+ if i != 0 {
+ try!(self, self.writer.write(", ".as_bytes()));
+ }
+ let name = unsafe { (*inner).name };
+ try!(self, self.writer.write(name.as_bytes()));
+ true
+ }
+
+ fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool,
+ inner: *TyDesc) -> bool {
+ if variadic {
+ try!(self, self.writer.write(", ...".as_bytes()));
+ }
+ try!(self, self.writer.write(")".as_bytes()));
+ let name = unsafe { (*inner).name };
+ if name != "()" {
+ try!(self, self.writer.write(" -> ".as_bytes()));
+ try!(self, self.writer.write(name.as_bytes()));
+ }
+ true
+ }
+
+ fn visit_leave_fn(&mut self, _purity: uint, _proto: uint,
+ _n_inputs: uint, _retstyle: uint) -> bool { true }
+
+
+ fn visit_trait(&mut self, name: &str) -> bool {
+ try!(self, self.writer.write(name.as_bytes()));
+ true
+ }
+
+ fn visit_param(&mut self, _i: uint) -> bool { true }
+ fn visit_self(&mut self) -> bool { true }
+}
+
+pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> {
+ unsafe {
+ let ptr = object as *T as *u8;
+ let tydesc = get_tydesc::<T>();
+ let u = ReprVisitor(ptr, writer);
+ let mut v = reflect::MovePtrAdaptor(u);
+ visit_tydesc(tydesc, &mut v as &mut TyVisitor);
+ match v.unwrap().last_err {
+ Some(e) => Err(e),
+ None => Ok(()),
+ }
+ }
+}
+
+pub fn repr_to_str<T>(t: &T) -> String {
+ let mut result = io::MemWriter::new();
+ write_repr(&mut result as &mut io::Writer, t).unwrap();
+ String::from_utf8(result.unwrap()).unwrap()
+}
+
+#[cfg(test)]
+struct P {a: int, b: f64}
+
+#[test]
+fn test_repr() {
+ use std::str;
+ use std::io::stdio::println;
+ use std::char::is_alphabetic;
+ use std::mem::swap;
+
+ fn exact_test<T>(t: &T, e:&str) {
+ let mut m = io::MemWriter::new();
+ write_repr(&mut m as &mut io::Writer, t).unwrap();
+ let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned();
+ assert_eq!(s.as_slice(), e);
+ }
+
+ exact_test(&10, "10");
+ exact_test(&true, "true");
+ exact_test(&false, "false");
+ exact_test(&1.234, "1.234f64");
+ exact_test(&("hello"), "\"hello\"");
+
+ exact_test(&(@10), "@10");
+ exact_test(&(box 10), "box 10");
+ exact_test(&(&10), "&10");
+ let mut x = 10;
+ exact_test(&(&mut x), "&mut 10");
+
+ exact_test(&(0 as *()), "(0x0 as *())");
+ exact_test(&(0 as *mut ()), "(0x0 as *mut ())");
+
+ exact_test(&(1,), "(1,)");
+ exact_test(&(&["hi", "there"]),
+ "&[\"hi\", \"there\"]");
+ exact_test(&(P{a:10, b:1.234}),
+ "repr::P{a: 10, b: 1.234f64}");
+ exact_test(&(@P{a:10, b:1.234}),
+ "@repr::P{a: 10, b: 1.234f64}");
+ exact_test(&(box P{a:10, b:1.234}),
+ "box repr::P{a: 10, b: 1.234f64}");
+
+ exact_test(&(&[1, 2]), "&[1, 2]");
+ exact_test(&(&mut [1, 2]), "&mut [1, 2]");
+
+ exact_test(&'\'', "'\\''");
+ exact_test(&'"', "'\"'");
+ exact_test(&("'"), "\"'\"");
+ exact_test(&("\""), "\"\\\"\"");
+
+ exact_test(&println, "fn(&str)");
+ exact_test(&swap::<int>, "fn(&mut int, &mut int)");
+ exact_test(&is_alphabetic, "fn(char) -> bool");
+
+ struct Bar(int, int);
+ exact_test(&(Bar(2, 2)), "repr::test_repr::Bar(2, 2)");
+}
/// String, but I think it does when this eventually uses conditions so it
/// might as well start using it now.
fn err(&mut self, msg: &str) {
- self.errors.push(msg.to_strbuf());
+ self.errors.push(msg.to_string());
}
/// Optionally consumes the specified character. If the character is not at
//!
//! fn main() {
//! let args: Vec<String> = os::args().iter()
-//! .map(|x| x.to_strbuf())
+//! .map(|x| x.to_string())
//! .collect();
//!
//! let program = args.get(0).clone();
#![deny(missing_doc)]
#![deny(deprecated_owned_vector)]
+#[cfg(test)] extern crate debug;
#[cfg(test)] #[phase(syntax, link)] extern crate log;
use std::cmp::Eq;
if nm.len() == 1u {
Short(nm.char_at(0u))
} else {
- Long(nm.to_strbuf())
+ Long(nm.to_string())
}
}
fn to_str(&self) -> String {
match *self {
- Short(ch) => ch.to_str().to_strbuf(),
- Long(ref s) => s.to_strbuf()
+ Short(ch) => ch.to_str().to_string(),
+ Long(ref s) => s.to_string()
}
}
}
}
match vals.get(0) {
&Val(ref s) => Some((*s).clone()),
- _ => Some(def.to_strbuf())
+ _ => Some(def.to_string())
}
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: hint.to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: hint.to_string(),
+ desc: desc.to_string(),
hasarg: Yes,
occur: Req
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: hint.to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: hint.to_string(),
+ desc: desc.to_string(),
hasarg: Yes,
occur: Optional
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: "".to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: "".to_string(),
+ desc: desc.to_string(),
hasarg: No,
occur: Optional
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: "".to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: "".to_string(),
+ desc: desc.to_string(),
hasarg: No,
occur: Multi
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: hint.to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: hint.to_string(),
+ desc: desc.to_string(),
hasarg: Maybe,
occur: Optional
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: hint.to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: hint.to_string(),
+ desc: desc.to_string(),
hasarg: Yes,
occur: Multi
}
let len = short_name.len();
assert!(len == 1 || len == 0);
OptGroup {
- short_name: short_name.to_strbuf(),
- long_name: long_name.to_strbuf(),
- hint: hint.to_strbuf(),
- desc: desc.to_strbuf(),
+ short_name: short_name.to_string(),
+ long_name: long_name.to_string(),
+ hint: hint.to_string(),
+ desc: desc.to_string(),
hasarg: hasarg,
occur: occur
}
let tail = cur.as_slice().slice(2, curlen);
let tail_eq: Vec<&str> = tail.split('=').collect();
if tail_eq.len() <= 1 {
- names = vec!(Long(tail.to_strbuf()));
+ names = vec!(Long(tail.to_string()));
} else {
names =
- vec!(Long((*tail_eq.get(0)).to_strbuf()));
- i_arg = Some((*tail_eq.get(1)).to_strbuf());
+ vec!(Long((*tail_eq.get(0)).to_string()));
+ i_arg = Some((*tail_eq.get(1)).to_string());
}
} else {
let mut j = 1;
};
if arg_follows && j < curlen {
i_arg = Some(cur.as_slice()
- .slice(j, curlen).to_strbuf());
+ .slice(j, curlen).to_string());
break;
} else {
last_valid_opt_id = None;
hasarg: hasarg,
..} = (*optref).clone();
- let mut row = String::from_owned_str(" ".repeat(4));
+ let mut row = " ".repeat(4);
// short option
match short_name.len() {
each_split_within(desc_normalized_whitespace.as_slice(),
54,
|substr| {
- desc_rows.push(substr.to_owned());
+ desc_rows.push(substr.to_string());
true
});
fn test_split_within() {
fn t(s: &str, i: uint, u: &[String]) {
let mut v = Vec::new();
- each_split_within(s, i, |s| { v.push(s.to_strbuf()); true });
+ each_split_within(s, i, |s| { v.push(s.to_string()); true });
assert!(v.iter().zip(u.iter()).all(|(a,b)| a == b));
}
t("", 0, []);
t("", 15, []);
- t("hello", 15, ["hello".to_strbuf()]);
+ t("hello", 15, ["hello".to_string()]);
t("\nMary had a little lamb\nLittle lamb\n", 15, [
- "Mary had a".to_strbuf(),
- "little lamb".to_strbuf(),
- "Little lamb".to_strbuf()
+ "Mary had a".to_string(),
+ "little lamb".to_string(),
+ "Little lamb".to_string()
]);
t("\nMary had a little lamb\nLittle lamb\n", ::std::uint::MAX,
- ["Mary had a little lamb\nLittle lamb".to_strbuf()]);
+ ["Mary had a little lamb\nLittle lamb".to_string()]);
}
#[cfg(test)]
// Tests for reqopt
#[test]
fn test_reqopt() {
- let long_args = vec!("--test=20".to_strbuf());
+ let long_args = vec!("--test=20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!(m.opt_present("t"));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => { fail!("test_reqopt failed (long arg)"); }
}
- let short_args = vec!("-t".to_strbuf(), "20".to_strbuf());
+ let short_args = vec!("-t".to_string(), "20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => { fail!("test_reqopt failed (short arg)"); }
}
#[test]
fn test_reqopt_missing() {
- let args = vec!("blah".to_strbuf());
+ let args = vec!("blah".to_string());
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".to_strbuf());
+ let long_args = vec!("--test".to_string());
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".to_strbuf());
+ let short_args = vec!("-t".to_string());
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".to_strbuf(), "-t".to_strbuf(), "30".to_strbuf());
+ let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
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".to_strbuf());
+ let long_args = vec!("--test=20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
}
- let short_args = vec!("-t".to_strbuf(), "20".to_strbuf());
+ let short_args = vec!("-t".to_string(), "20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
}
#[test]
fn test_optopt_missing() {
- let args = vec!("blah".to_strbuf());
+ let args = vec!("blah".to_string());
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".to_strbuf());
+ let long_args = vec!("--test".to_string());
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".to_strbuf());
+ let short_args = vec!("-t".to_string());
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".to_strbuf(), "-t".to_strbuf(), "30".to_strbuf());
+ let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
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".to_strbuf());
+ let long_args = vec!("--test".to_string());
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".to_strbuf());
+ let short_args = vec!("-t".to_string());
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".to_strbuf());
+ let args = vec!("blah".to_string());
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".to_strbuf());
+ let args = vec!("--test=20".to_string());
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".to_strbuf(), "-t".to_strbuf());
+ let args = vec!("--test".to_string(), "-t".to_string());
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".to_strbuf(), "20".to_strbuf());
+ let args = vec!("-t".to_string(), "20".to_string());
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".to_strbuf());
+ assert!(*m.free.get(0) == "20".to_string());
}
_ => fail!()
}
// Tests for optflagmulti
#[test]
fn test_optflagmulti_short1() {
- let args = vec!("-v".to_strbuf());
+ let args = vec!("-v".to_string());
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".to_strbuf(), "-v".to_strbuf());
+ let args = vec!("-v".to_string(), "-v".to_string());
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".to_strbuf());
+ let args = vec!("-vv".to_string());
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".to_strbuf());
+ let args = vec!("--verbose".to_string());
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".to_strbuf(), "--verbose".to_strbuf());
+ let args = vec!("--verbose".to_string(), "--verbose".to_string());
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".to_strbuf(), "-v".to_strbuf(),
- "-vv".to_strbuf(), "verbose".to_strbuf());
+ let args = vec!("--verbose".to_string(), "-v".to_string(),
+ "-vv".to_string(), "verbose".to_string());
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".to_strbuf());
+ let long_args = vec!("--test=20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
}
- let short_args = vec!("-t".to_strbuf(), "20".to_strbuf());
+ let short_args = vec!("-t".to_string(), "20".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!((m.opt_present("t")));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
}
#[test]
fn test_optmulti_missing() {
- let args = vec!("blah".to_strbuf());
+ let args = vec!("blah".to_string());
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".to_strbuf());
+ let long_args = vec!("--test".to_string());
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".to_strbuf());
+ let short_args = vec!("-t".to_string());
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".to_strbuf(), "-t".to_strbuf(), "30".to_strbuf());
+ let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
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".to_strbuf());
+ assert_eq!(m.opt_str("test").unwrap(), "20".to_string());
assert!(m.opt_present("t"));
- assert_eq!(m.opt_str("t").unwrap(), "20".to_strbuf());
+ assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
let pair = m.opt_strs("test");
- assert!(*pair.get(0) == "20".to_strbuf());
- assert!(*pair.get(1) == "30".to_strbuf());
+ assert!(*pair.get(0) == "20".to_string());
+ assert!(*pair.get(1) == "30".to_string());
}
_ => fail!()
}
#[test]
fn test_unrecognized_option() {
- let long_args = vec!("--untest".to_strbuf());
+ let long_args = vec!("--untest".to_string());
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".to_strbuf());
+ let short_args = vec!("-u".to_string());
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".to_strbuf(),
- "free1".to_strbuf(),
- "-s".to_strbuf(),
- "20".to_strbuf(),
- "free2".to_strbuf(),
- "--flag".to_strbuf(),
- "--long=30".to_strbuf(),
- "-f".to_strbuf(),
- "-m".to_strbuf(),
- "40".to_strbuf(),
- "-m".to_strbuf(),
- "50".to_strbuf(),
- "-n".to_strbuf(),
- "-A B".to_strbuf(),
- "-n".to_strbuf(),
- "-60 70".to_strbuf());
+ vec!("prog".to_string(),
+ "free1".to_string(),
+ "-s".to_string(),
+ "20".to_string(),
+ "free2".to_string(),
+ "--flag".to_string(),
+ "--long=30".to_string(),
+ "-f".to_string(),
+ "-m".to_string(),
+ "40".to_string(),
+ "-m".to_string(),
+ "50".to_string(),
+ "-n".to_string(),
+ "-A B".to_string(),
+ "-n".to_string(),
+ "-60 70".to_string());
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".to_strbuf());
- assert!(*m.free.get(1) == "free1".to_strbuf());
- assert_eq!(m.opt_str("s").unwrap(), "20".to_strbuf());
- assert!(*m.free.get(2) == "free2".to_strbuf());
+ assert!(*m.free.get(0) == "prog".to_string());
+ assert!(*m.free.get(1) == "free1".to_string());
+ assert_eq!(m.opt_str("s").unwrap(), "20".to_string());
+ assert!(*m.free.get(2) == "free2".to_string());
assert!((m.opt_present("flag")));
- assert_eq!(m.opt_str("long").unwrap(), "30".to_strbuf());
+ assert_eq!(m.opt_str("long").unwrap(), "30".to_string());
assert!((m.opt_present("f")));
let pair = m.opt_strs("m");
- assert!(*pair.get(0) == "40".to_strbuf());
- assert!(*pair.get(1) == "50".to_strbuf());
+ assert!(*pair.get(0) == "40".to_string());
+ assert!(*pair.get(1) == "50".to_string());
let pair = m.opt_strs("n");
- assert!(*pair.get(0) == "-A B".to_strbuf());
- assert!(*pair.get(1) == "-60 70".to_strbuf());
+ assert!(*pair.get(0) == "-A B".to_string());
+ assert!(*pair.get(1) == "-60 70".to_string());
assert!((!m.opt_present("notpresent")));
}
_ => fail!()
optopt("", "encrypt", "encrypt", "ENCRYPT"),
optopt("f", "", "flag", "FLAG"));
- let args_single = vec!("-e".to_strbuf(), "foo".to_strbuf());
+ let args_single = vec!("-e".to_string(), "foo".to_string());
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".to_strbuf()]));
- assert!(matches_single.opts_present(["encrypt".to_strbuf(), "e".to_strbuf()]));
- assert!(matches_single.opts_present(["e".to_strbuf(), "encrypt".to_strbuf()]));
- assert!(!matches_single.opts_present(["encrypt".to_strbuf()]));
- assert!(!matches_single.opts_present(["thing".to_strbuf()]));
+ assert!(matches_single.opts_present(["e".to_string()]));
+ assert!(matches_single.opts_present(["encrypt".to_string(), "e".to_string()]));
+ assert!(matches_single.opts_present(["e".to_string(), "encrypt".to_string()]));
+ assert!(!matches_single.opts_present(["encrypt".to_string()]));
+ assert!(!matches_single.opts_present(["thing".to_string()]));
assert!(!matches_single.opts_present([]));
- assert_eq!(matches_single.opts_str(["e".to_strbuf()]).unwrap(), "foo".to_strbuf());
- assert_eq!(matches_single.opts_str(["e".to_strbuf(), "encrypt".to_strbuf()]).unwrap(),
- "foo".to_strbuf());
- assert_eq!(matches_single.opts_str(["encrypt".to_strbuf(), "e".to_strbuf()]).unwrap(),
- "foo".to_strbuf());
+ assert_eq!(matches_single.opts_str(["e".to_string()]).unwrap(), "foo".to_string());
+ assert_eq!(matches_single.opts_str(["e".to_string(), "encrypt".to_string()]).unwrap(),
+ "foo".to_string());
+ assert_eq!(matches_single.opts_str(["encrypt".to_string(), "e".to_string()]).unwrap(),
+ "foo".to_string());
- let args_both = vec!("-e".to_strbuf(), "foo".to_strbuf(), "--encrypt".to_strbuf(),
- "foo".to_strbuf());
+ let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(),
+ "foo".to_string());
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".to_strbuf()]));
- assert!(matches_both.opts_present(["encrypt".to_strbuf()]));
- assert!(matches_both.opts_present(["encrypt".to_strbuf(), "e".to_strbuf()]));
- assert!(matches_both.opts_present(["e".to_strbuf(), "encrypt".to_strbuf()]));
- assert!(!matches_both.opts_present(["f".to_strbuf()]));
- assert!(!matches_both.opts_present(["thing".to_strbuf()]));
+ assert!(matches_both.opts_present(["e".to_string()]));
+ assert!(matches_both.opts_present(["encrypt".to_string()]));
+ assert!(matches_both.opts_present(["encrypt".to_string(), "e".to_string()]));
+ assert!(matches_both.opts_present(["e".to_string(), "encrypt".to_string()]));
+ assert!(!matches_both.opts_present(["f".to_string()]));
+ assert!(!matches_both.opts_present(["thing".to_string()]));
assert!(!matches_both.opts_present([]));
- assert_eq!(matches_both.opts_str(["e".to_strbuf()]).unwrap(), "foo".to_strbuf());
- assert_eq!(matches_both.opts_str(["encrypt".to_strbuf()]).unwrap(), "foo".to_strbuf());
- assert_eq!(matches_both.opts_str(["e".to_strbuf(), "encrypt".to_strbuf()]).unwrap(),
- "foo".to_strbuf());
- assert_eq!(matches_both.opts_str(["encrypt".to_strbuf(), "e".to_strbuf()]).unwrap(),
- "foo".to_strbuf());
+ assert_eq!(matches_both.opts_str(["e".to_string()]).unwrap(), "foo".to_string());
+ assert_eq!(matches_both.opts_str(["encrypt".to_string()]).unwrap(), "foo".to_string());
+ assert_eq!(matches_both.opts_str(["e".to_string(), "encrypt".to_string()]).unwrap(),
+ "foo".to_string());
+ assert_eq!(matches_both.opts_str(["encrypt".to_string(), "e".to_string()]).unwrap(),
+ "foo".to_string());
}
#[test]
fn test_nospace() {
- let args = vec!("-Lfoo".to_strbuf(), "-M.".to_strbuf());
+ let args = vec!("-Lfoo".to_string(), "-M.".to_string());
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".to_strbuf()]));
- assert_eq!(matches.opts_str(["L".to_strbuf()]).unwrap(), "foo".to_strbuf());
- assert!(matches.opts_present(["M".to_strbuf()]));
- assert_eq!(matches.opts_str(["M".to_strbuf()]).unwrap(), ".".to_strbuf());
+ assert!(matches.opts_present(["L".to_string()]));
+ assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "foo".to_string());
+ assert!(matches.opts_present(["M".to_string()]));
+ assert_eq!(matches.opts_str(["M".to_string()]).unwrap(), ".".to_string());
}
#[test]
fn test_long_to_short() {
let mut short = Opt {
- name: Long("banana".to_strbuf()),
+ name: Long("banana".to_string()),
hasarg: Yes,
occur: Req,
aliases: Vec::new(),
let opts = vec!(
optflagmulti("a", "apple", "Desc"));
- let args = vec!("-a".to_strbuf(), "--apple".to_strbuf(), "-a".to_strbuf());
+ let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string());
let matches = getopts(args.as_slice(), opts.as_slice()).unwrap();
assert_eq!(3, matches.opt_count("a"));
-k --kiwi Desc
-p [VAL] Desc
-l VAL Desc
-".to_strbuf();
+".to_string();
let generated_usage = usage("Usage: fruits", optgroups.as_slice());
-k --kiwi This is a long description which won't be wrapped..+..
-a --apple This is a long description which _will_ be
wrapped..+..
-".to_strbuf();
+".to_string();
let usage = usage("Usage: fruits", optgroups.as_slice());
-a --apple This “description” has some characters that could
confuse the line wrapping; an apple costs 0.51€ in
some parts of Europe.
-".to_strbuf();
+".to_string();
let usage = usage("Usage: fruits", optgroups.as_slice());
optflagopt("p", "", "Desc", "VAL"),
optmulti("l", "", "Desc", "VAL"));
- let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_strbuf();
+ let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string();
let generated_usage = short_usage("fruits", optgroups.as_slice());
debug!("expected: <<{}>>", expected);
#[test]
fn test_pattern_escape() {
let s = "_[_]_?_*_!_";
- assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_strbuf());
+ assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_string());
assert!(Pattern::new(Pattern::escape(s).as_slice()).matches(s));
}
/// Renders text as string suitable for a label in a .dot file.
pub fn escape(&self) -> String {
match self {
- &LabelStr(ref s) => s.as_slice().escape_default().to_strbuf(),
- &EscStr(ref s) => LabelText::escape_str(s.as_slice()).to_strbuf(),
+ &LabelStr(ref s) => s.as_slice().escape_default().to_string(),
+ &EscStr(ref s) => LabelText::escape_str(s.as_slice()).to_string(),
}
}
}
render(&g, &mut writer).unwrap();
let mut r = BufReader::new(writer.get_ref());
match r.read_to_str() {
- Ok(string) => Ok(string.to_strbuf()),
+ Ok(string) => Ok(string.to_string()),
Err(err) => Err(err),
}
}
type Registers = [uint, ..32];
#[cfg(target_arch = "mips")]
-fn new_regs() -> Box<Registers> { box [0, .. 32] }
+fn new_regs() -> Box<Registers> { box {[0, .. 32]} }
#[cfg(target_arch = "mips")]
fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint,
// page. It isn't guaranteed, but that's why FFI is unsafe. buf.data is
// guaranteed to be aligned properly.
if !protect_last_page(&stack) {
- fail!("Could not memory-protect guard page. stack={:?}, errno={}",
- stack, errno());
+ fail!("Could not memory-protect guard page. stack={}, errno={}",
+ stack.data, errno());
}
let mut stk = Stack {
let mut i = 0;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
if chars.next() != Some('0') {
- return Some((i, "Expected '0'".to_strbuf()));
+ return Some((i, "Expected '0'".to_string()));
} i+=1;
if chars.next() != Some('x') {
- return Some((i, "Expected 'x'".to_strbuf()));
+ return Some((i, "Expected 'x'".to_string()));
} 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 '.'".to_strbuf()));
+ return Some((i, "Expected '.'".to_string()));
} 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".to_strbuf()));
+ point".to_string()));
}
if chars.next() != Some('p') {
- return Some((i, "Expected 'p'".to_strbuf()));
+ return Some((i, "Expected 'p'".to_string()));
} 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".to_strbuf()));
+ return Some((i, "Expected exponent digits".to_string()));
}
match chars.next() {
None => None,
- Some(_) => Some((i, "Expected end of string".to_strbuf()))
+ Some(_) => Some((i, "Expected end of string".to_string()))
}
}
}
pub mod posix08 {
}
+ #[cfg(target_arch = "arm")]
+ #[cfg(target_arch = "x86")]
+ #[cfg(target_arch = "x86_64")]
pub mod bsd44 {
use types::os::arch::c95::c_int;
pub static SHUT_WR: c_int = 1;
pub static SHUT_RDWR: c_int = 2;
}
+ #[cfg(target_arch = "mips")]
+ pub mod bsd44 {
+ use types::os::arch::c95::c_int;
+
+ pub static MADV_NORMAL : c_int = 0;
+ pub static MADV_RANDOM : c_int = 1;
+ pub static MADV_SEQUENTIAL : c_int = 2;
+ pub static MADV_WILLNEED : c_int = 3;
+ pub static MADV_DONTNEED : c_int = 4;
+ pub static MADV_REMOVE : c_int = 9;
+ pub static MADV_DONTFORK : c_int = 10;
+ pub static MADV_DOFORK : c_int = 11;
+ pub static MADV_MERGEABLE : c_int = 12;
+ pub static MADV_UNMERGEABLE : c_int = 13;
+ pub static MADV_HWPOISON : c_int = 100;
+
+ pub static AF_UNIX: c_int = 1;
+ pub static AF_INET: c_int = 2;
+ pub static AF_INET6: c_int = 10;
+ pub static SOCK_STREAM: c_int = 2;
+ pub static SOCK_DGRAM: c_int = 1;
+ pub static IPPROTO_TCP: c_int = 6;
+ pub static IPPROTO_IP: c_int = 0;
+ pub static IPPROTO_IPV6: c_int = 41;
+ pub static IP_MULTICAST_TTL: c_int = 33;
+ pub static IP_MULTICAST_LOOP: c_int = 34;
+ pub static IP_TTL: c_int = 2;
+ pub static IP_ADD_MEMBERSHIP: c_int = 35;
+ pub static IP_DROP_MEMBERSHIP: c_int = 36;
+ pub static IPV6_ADD_MEMBERSHIP: c_int = 20;
+ pub static IPV6_DROP_MEMBERSHIP: c_int = 21;
+
+ pub static TCP_NODELAY: c_int = 1;
+ pub static SOL_SOCKET: c_int = 65535;
+ pub static SO_KEEPALIVE: c_int = 8;
+ pub static SO_BROADCAST: c_int = 32;
+ pub static SO_REUSEADDR: c_int = 4;
+ pub static SO_ERROR: c_int = 4103;
+
+ pub static SHUT_RD: c_int = 0;
+ pub static SHUT_WR: c_int = 1;
+ pub static SHUT_RDWR: c_int = 2;
+ }
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
#[cfg(target_arch = "arm")]
}
};
dirs.push(LogDirective {
- name: name.map(|s| s.to_strbuf()),
+ name: name.map(|s| s.to_string()),
level: log_level,
});
}
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".to_strbuf()));
+ assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
assert_eq!(dirs[0].level, 1);
- assert_eq!(dirs[1].name, Some("crate1::mod2".to_strbuf()));
+ assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
assert_eq!(dirs[1].level, ::MAX_LOG_LEVEL);
- assert_eq!(dirs[2].name, Some("crate2".to_strbuf()));
+ assert_eq!(dirs[2].name, Some("crate2".to_string()));
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".to_strbuf()));
+ assert_eq!(dirs[0].name, Some("crate2".to_string()));
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".to_strbuf()));
+ assert_eq!(dirs[0].name, Some("crate2".to_string()));
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".to_strbuf()));
+ assert_eq!(dirs[0].name, Some("crate2".to_string()));
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".to_strbuf()));
+ assert_eq!(dirs[1].name, Some("crate2".to_string()));
assert_eq!(dirs[1].level, 4);
}
}
fn match_full_path() {
let dirs = [
LogDirective {
- name: Some("crate2".to_strbuf()),
+ name: Some("crate2".to_string()),
level: 3
},
LogDirective {
- name: Some("crate1::mod1".to_strbuf()),
+ name: Some("crate1::mod1".to_string()),
level: 2
}
];
#[test]
fn no_match() {
let dirs = [
- LogDirective { name: Some("crate2".to_strbuf()), level: 3 },
- LogDirective { name: Some("crate1::mod1".to_strbuf()), level: 2 }
+ LogDirective { name: Some("crate2".to_string()), level: 3 },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
let dirs = [
- LogDirective { name: Some("crate2".to_strbuf()), level: 3 },
- LogDirective { name: Some("crate1::mod1".to_strbuf()), level: 2 }
+ LogDirective { name: Some("crate2".to_string()), level: 3 },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
let dirs = [
- LogDirective { name: Some("crate2".to_strbuf()), level: 3 },
- LogDirective { name: Some("crate2::mod".to_strbuf()), level: 4 },
- LogDirective { name: Some("crate1::mod1".to_strbuf()), level: 2 }
+ LogDirective { name: Some("crate2".to_string()), level: 3 },
+ LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
+ LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
fn match_default() {
let dirs = [
LogDirective { name: None, level: 3 },
- LogDirective { name: Some("crate1::mod1".to_strbuf()), level: 2 }
+ LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
- LogDirective { name: Some("crate1::mod1".to_strbuf()), level: 0 }
+ LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
use std::io;
let err_str = unsafe {
- CString::new(gai_strerror(s), false).as_str().unwrap().to_strbuf()
+ CString::new(gai_strerror(s), false).as_str().unwrap().to_string()
};
IoError {
kind: io::OtherIoError,
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub static FIONBIO: libc::c_ulong = 0x8004667e;
-#[cfg(target_os = "linux")]
+#[cfg(target_os = "linux", not(target_arch = "mips"))]
#[cfg(target_os = "android")]
pub static FIONBIO: libc::c_ulong = 0x5421;
+#[cfg(target_os = "linux", target_arch = "mips")]
+pub static FIONBIO: libc::c_ulong = 0x667e;
+
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub static FIOCLEX: libc::c_ulong = 0x20006601;
-#[cfg(target_os = "linux")]
+#[cfg(target_os = "linux", not(target_arch = "mips"))]
#[cfg(target_os = "android")]
pub static FIOCLEX: libc::c_ulong = 0x5451;
+#[cfg(target_os = "linux", target_arch = "mips")]
+pub static FIOCLEX: libc::c_ulong = 0x6601;
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
}
}
-#[cfg(target_os = "linux")]
+#[cfg(target_os = "linux", not(target_arch = "mips"))]
#[cfg(target_os = "android")]
mod signal {
use libc;
}
}
+#[cfg(target_os = "linux", target_arch = "mips")]
+mod signal {
+ use libc;
+
+ pub static SA_NOCLDSTOP: libc::c_ulong = 0x00000001;
+ pub static SA_NOCLDWAIT: libc::c_ulong = 0x00010000;
+ pub static SA_NODEFER: libc::c_ulong = 0x40000000;
+ pub static SA_ONSTACK: libc::c_ulong = 0x08000000;
+ pub static SA_RESETHAND: libc::c_ulong = 0x80000000;
+ pub static SA_RESTART: libc::c_ulong = 0x10000000;
+ pub static SA_SIGINFO: libc::c_ulong = 0x00000008;
+ pub static SIGCHLD: libc::c_int = 18;
+
+ // This definition is not as accurate as it could be, {pid, uid, status} is
+ // actually a giant union. Currently we're only interested in these fields,
+ // however.
+ pub struct siginfo {
+ si_signo: libc::c_int,
+ si_code: libc::c_int,
+ si_errno: libc::c_int,
+ pub pid: libc::pid_t,
+ pub uid: libc::uid_t,
+ pub status: libc::c_int,
+ }
+
+ pub struct sigaction {
+ pub sa_flags: libc::c_uint,
+ pub sa_handler: extern fn(libc::c_int),
+ pub sa_mask: sigset_t,
+ sa_restorer: *mut libc::c_void,
+ sa_resv: [libc::c_int, ..1],
+ }
+
+ pub struct sigset_t {
+ __val: [libc::c_ulong, ..32],
+ }
+}
+
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
mod signal {
fn ip_to_inaddr(ip: ip::IpAddr) -> InAddr {
match ip {
ip::Ipv4Addr(a, b, c, d) => {
+ let ip = (a as u32 << 24) |
+ (b as u32 << 16) |
+ (c as u32 << 8) |
+ (d as u32 << 0);
InAddr(libc::in_addr {
- s_addr: (d as u32 << 24) |
- (c as u32 << 16) |
- (b as u32 << 8) |
- (a as u32 << 0)
+ s_addr: mem::from_be32(ip)
})
}
ip::Ipv6Addr(a, b, c, d, e, f, g, h) => {
let storage: &libc::sockaddr_in = unsafe {
mem::transmute(storage)
};
- let addr = storage.sin_addr.s_addr as u32;
- let a = (addr >> 0) as u8;
- let b = (addr >> 8) as u8;
- let c = (addr >> 16) as u8;
- let d = (addr >> 24) as u8;
+ let ip = mem::to_be32(storage.sin_addr.s_addr as u32);
+ let a = (ip >> 24) as u8;
+ let b = (ip >> 16) as u8;
+ let c = (ip >> 8) as u8;
+ let d = (ip >> 0) as u8;
Ok(ip::SocketAddr {
ip: ip::Ipv4Addr(a, b, c, d),
port: ntohs(storage.sin_port),
assert_eq!(
test_wrapper("prog", ["aaa", "bbb", "ccc"]),
- "prog aaa bbb ccc".to_owned()
+ "prog aaa bbb ccc".to_string()
);
assert_eq!(
test_wrapper("C:\\Program Files\\blah\\blah.exe", ["aaa"]),
- "\"C:\\Program Files\\blah\\blah.exe\" aaa".to_owned()
+ "\"C:\\Program Files\\blah\\blah.exe\" aaa".to_string()
);
assert_eq!(
test_wrapper("C:\\Program Files\\test", ["aa\"bb"]),
- "\"C:\\Program Files\\test\" aa\\\"bb".to_owned()
+ "\"C:\\Program Files\\test\" aa\\\"bb".to_string()
);
assert_eq!(
test_wrapper("echo", ["a b c"]),
- "echo \"a b c\"".to_owned()
+ "echo \"a b c\"".to_string()
);
assert_eq!(
test_wrapper("\u03c0\u042f\u97f3\u00e6\u221e", []),
- "\u03c0\u042f\u97f3\u00e6\u221e".to_owned()
+ "\u03c0\u042f\u97f3\u00e6\u221e".to_string()
);
}
}
extern crate alloc;
extern crate libc;
+#[cfg(test)] extern crate debug;
use std::os;
use std::rt;
fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
if v.is_empty() {
- return "0".to_strbuf()
+ return "0".to_string()
}
let mut s = String::with_capacity(v.len() * l);
for n in v.iter().rev() {
s.push_str("0".repeat(l - ss.len()).as_slice());
s.push_str(ss.as_slice());
}
- s.as_slice().trim_left_chars('0').to_strbuf()
+ s.as_slice().trim_left_chars('0').to_string()
}
}
}
fn to_str_radix(&self, radix: uint) -> String {
match self.sign {
Plus => self.data.to_str_radix(radix),
- Zero => "0".to_strbuf(),
+ Zero => "0".to_string(),
Minus => format_strbuf!("-{}", self.data.to_str_radix(radix)),
}
}
fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
let bits = BigDigit::bits;
vec!(( Zero::zero(), vec!(
- (2, "0".to_strbuf()), (3, "0".to_strbuf())
+ (2, "0".to_string()), (3, "0".to_string())
)), ( BigUint::from_slice([ 0xff ]), vec!(
- (2, "11111111".to_strbuf()),
- (3, "100110".to_strbuf()),
- (4, "3333".to_strbuf()),
- (5, "2010".to_strbuf()),
- (6, "1103".to_strbuf()),
- (7, "513".to_strbuf()),
- (8, "377".to_strbuf()),
- (9, "313".to_strbuf()),
- (10, "255".to_strbuf()),
- (11, "212".to_strbuf()),
- (12, "193".to_strbuf()),
- (13, "168".to_strbuf()),
- (14, "143".to_strbuf()),
- (15, "120".to_strbuf()),
- (16, "ff".to_strbuf())
+ (2, "11111111".to_string()),
+ (3, "100110".to_string()),
+ (4, "3333".to_string()),
+ (5, "2010".to_string()),
+ (6, "1103".to_string()),
+ (7, "513".to_string()),
+ (8, "377".to_string()),
+ (9, "313".to_string()),
+ (10, "255".to_string()),
+ (11, "212".to_string()),
+ (12, "193".to_string()),
+ (13, "168".to_string()),
+ (14, "143".to_string()),
+ (15, "120".to_string()),
+ (16, "ff".to_string())
)), ( BigUint::from_slice([ 0xfff ]), vec!(
- (2, "111111111111".to_strbuf()),
- (4, "333333".to_strbuf()),
- (16, "fff".to_strbuf())
+ (2, "111111111111".to_string()),
+ (4, "333333".to_string()),
+ (16, "fff".to_string())
)), ( BigUint::from_slice([ 1, 2 ]), vec!(
(2,
format_strbuf!("10{}1", "0".repeat(bits - 1))),
(4,
format_strbuf!("2{}1", "0".repeat(bits / 2 - 1))),
(10, match bits {
- 32 => "8589934593".to_strbuf(),
- 16 => "131073".to_strbuf(),
+ 32 => "8589934593".to_string(),
+ 16 => "131073".to_string(),
_ => fail!()
}),
(16,
"0".repeat(bits / 2 - 1),
"0".repeat(bits / 2 - 1))),
(10, match bits {
- 32 => "55340232229718589441".to_strbuf(),
- 16 => "12885032961".to_strbuf(),
+ 32 => "55340232229718589441".to_string(),
+ 16 => "12885032961".to_string(),
_ => fail!()
}),
(16,
#[test]
fn test_to_str() {
fn test(c : Complex64, s: String) {
- assert_eq!(c.to_str().to_strbuf(), s);
+ assert_eq!(c.to_str().to_string(), s);
}
- test(_0_0i, "0+0i".to_strbuf());
- test(_1_0i, "1+0i".to_strbuf());
- test(_0_1i, "0+1i".to_strbuf());
- test(_1_1i, "1+1i".to_strbuf());
- test(_neg1_1i, "-1+1i".to_strbuf());
- test(-_neg1_1i, "1-1i".to_strbuf());
- test(_05_05i, "0.5+0.5i".to_strbuf());
+ test(_0_0i, "0+0i".to_string());
+ test(_1_0i, "1+0i".to_string());
+ test(_0_1i, "0+1i".to_string());
+ test(_1_1i, "1+1i".to_string());
+ test(_neg1_1i, "-1+1i".to_string());
+ test(-_neg1_1i, "1-1i".to_string());
+ test(_05_05i, "0.5+0.5i".to_string());
}
}
fn test_to_from_str() {
fn test(r: Rational, s: String) {
assert_eq!(FromStr::from_str(s.as_slice()), Some(r));
- assert_eq!(r.to_str().to_strbuf(), s);
+ assert_eq!(r.to_str().to_string(), s);
}
- test(_1, "1/1".to_strbuf());
- test(_0, "0/1".to_strbuf());
- test(_1_2, "1/2".to_strbuf());
- test(_3_2, "3/2".to_strbuf());
- test(_2, "2/1".to_strbuf());
- test(_neg1_2, "-1/2".to_strbuf());
+ test(_1, "1/1".to_string());
+ test(_0, "0/1".to_string());
+ test(_1_2, "1/2".to_string());
+ test(_3_2, "3/2".to_string());
+ test(_2, "2/1".to_string());
+ test(_neg1_2, "-1/2".to_string());
}
#[test]
fn test_from_str_fail() {
fn test(r: Rational, s: String, n: uint) {
assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n),
Some(r));
- assert_eq!(r.to_str_radix(n).to_strbuf(), s);
+ assert_eq!(r.to_str_radix(n).to_string(), s);
}
fn test3(r: Rational, s: String) { test(r, s, 3) }
fn test16(r: Rational, s: String) { test(r, s, 16) }
- test3(_1, "1/1".to_strbuf());
- test3(_0, "0/1".to_strbuf());
- test3(_1_2, "1/2".to_strbuf());
- test3(_3_2, "10/2".to_strbuf());
- test3(_2, "2/1".to_strbuf());
- test3(_neg1_2, "-1/2".to_strbuf());
- test3(_neg1_2 / _2, "-1/11".to_strbuf());
-
- test16(_1, "1/1".to_strbuf());
- test16(_0, "0/1".to_strbuf());
- test16(_1_2, "1/2".to_strbuf());
- test16(_3_2, "3/2".to_strbuf());
- test16(_2, "2/1".to_strbuf());
- test16(_neg1_2, "-1/2".to_strbuf());
- test16(_neg1_2 / _2, "-1/4".to_strbuf());
- test16(Ratio::new(13,15), "d/f".to_strbuf());
- test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_strbuf());
+ test3(_1, "1/1".to_string());
+ test3(_0, "0/1".to_string());
+ test3(_1_2, "1/2".to_string());
+ test3(_3_2, "10/2".to_string());
+ test3(_2, "2/1".to_string());
+ test3(_neg1_2, "-1/2".to_string());
+ test3(_neg1_2 / _2, "-1/11".to_string());
+
+ test16(_1, "1/1".to_string());
+ test16(_0, "0/1".to_string());
+ test16(_1_2, "1/2".to_string());
+ test16(_3_2, "3/2".to_string());
+ test16(_2, "2/1".to_string());
+ test16(_neg1_2, "-1/2".to_string());
+ test16(_neg1_2 / _2, "-1/4".to_string());
+ test16(Ratio::new(13,15), "d/f".to_string());
+ test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_string());
}
#[test]
```rust
let tuple_ptr = rand::random::<Box<(f64, char)>>();
-println!("{:?}", tuple_ptr)
+println!("{}", tuple_ptr)
```
*/
#![feature(macro_rules, managed_boxes, phase)]
#![deny(deprecated_owned_vector)]
-#[cfg(test)]
-#[phase(syntax, link)] extern crate log;
+#[cfg(test)] extern crate debug;
+#[cfg(test)] #[phase(syntax, link)] extern crate log;
use std::io::IoResult;
use std::kinds::marker;
///
/// let mut v = [0u8, .. 13579];
/// task_rng().fill_bytes(v);
- /// println!("{:?}", v);
+ /// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
- /// println!("{:?}", rng.gen::<(f64, bool)>());
+ /// println!("{}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
self.caps += 1;
self.stack.push(Paren(self.flags,
self.caps,
- "".to_strbuf()))
+ "".to_string()))
}
}
')' => {
}
if self.cur() == ':' {
// Save the old flags with the opening paren.
- self.stack.push(Paren(self.flags, 0, "".to_strbuf()));
+ self.stack.push(Paren(self.flags, 0, "".to_string()));
}
self.flags = flags;
return Ok(())
fn err<T>(&self, msg: &str) -> Result<T, Error> {
Err(Error {
pos: self.chari,
- msg: msg.to_strbuf(),
+ msg: msg.to_string(),
})
}
}
fn slice(&self, start: uint, end: uint) -> String {
- str::from_chars(self.chars.as_slice().slice(start, end)).to_strbuf()
+ str::from_chars(self.chars.as_slice().slice(start, end)).to_string()
}
}
let ast = try!(parse::parse(re));
let (prog, names) = Program::new(ast);
Ok(Dynamic(Dynamic {
- original: re.to_strbuf(),
+ original: re.to_string(),
names: names,
prog: prog,
}))
impl<'a> Iterator<Option<String>> for NamesIter<'a> {
fn next(&mut self) -> Option<Option<String>> {
match *self {
- NamesIterNative(ref mut i) => i.next().map(|x| x.map(|s| s.to_strbuf())),
- NamesIterDynamic(ref mut i) => i.next().map(|x| x.as_ref().map(|s| s.to_strbuf())),
+ NamesIterNative(ref mut i) => i.next().map(|x| x.map(|s| s.to_string())),
+ NamesIterDynamic(ref mut i) => i.next().map(|x| x.as_ref().map(|s| s.to_string())),
}
}
}
format_strbuf!("{}{}",
pre,
match from_str::<uint>(name.as_slice()) {
- None => self.name(name).to_strbuf(),
- Some(i) => self.at(i).to_strbuf(),
+ None => self.name(name).to_string(),
+ Some(i) => self.at(i).to_string(),
})
});
let re = Regex::new(r"\$\$").unwrap();
*b = '\n' as u8
}
}
- str::from_utf8(bytes.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(bytes.as_slice()).unwrap().to_string()
}
throughput!(easy0_32, easy0(), 32)
let mut gen = NfaGen {
cx: &*cx, sp: sp, prog: prog,
- names: re.names_iter().collect(), original: re.as_str().to_strbuf(),
+ names: re.names_iter().collect(), original: re.as_str().to_string(),
};
MacExpr::new(gen.code())
}
let regex = match entry.node {
ast::ExprLit(lit) => {
match lit.node {
- ast::LitStr(ref s, _) => s.to_str().to_strbuf(),
+ ast::LitStr(ref s, _) => s.to_str().to_string(),
_ => {
cx.span_err(entry.span, format!(
"expected string literal but got `{}`",
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
- output.lines_any().map(|s| s.to_strbuf()).collect()
+ output.lines_any().map(|s| s.to_string()).collect()
}
fn add_archive(&mut self, archive: &Path, name: &str,
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
let cc_args = if target_triple.as_slice().contains("thumb") {
- vec!("-mthumb".to_strbuf())
+ vec!("-mthumb".to_string())
} else {
- vec!("-marm".to_strbuf())
+ vec!("-marm".to_string())
};
return target_strs::t {
- module_asm: "".to_strbuf(),
+ module_asm: "".to_string(),
meta_sect_name:
- meta_section_name(cfg_os_to_meta_os(target_os)).to_strbuf(),
+ meta_section_name(cfg_os_to_meta_os(target_os)).to_string(),
data_layout: match target_os {
abi::OsMacos => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsWin32 => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsLinux => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsAndroid => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsFreebsd => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
},
let result = llvm::LLVMRustWriteOutputFile(
target, pm, m, output, file_type);
if !result {
- llvm_err(sess, "could not write output".to_strbuf());
+ llvm_err(sess, "could not write output".to_string());
}
})
}
// not by path.
let mut s = Sha256::new();
s.input_str(crate_id.short_name_with_version().as_slice());
- truncated_hash_result(&mut s).as_slice().slice_to(8).to_strbuf()
+ truncated_hash_result(&mut s).as_slice().slice_to(8).to_string()
}
// FIXME (#9639): This needs to handle non-utf8 `out_filestem` values
fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
let output = symbol_hasher.result_bytes();
// 64 bits should be enough to avoid collisions.
- output.slice_to(8).to_hex().to_strbuf()
+ output.slice_to(8).to_hex().to_string()
}
fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> String {
match ccx.type_hashcodes.borrow().find(&t) {
- Some(h) => return h.to_strbuf(),
+ Some(h) => return h.to_string(),
None => {}
}
if result.len() > 0u &&
result.as_slice()[0] != '_' as u8 &&
! char::is_XID_start(result.as_slice()[0] as char) {
- return format!("_{}", result.as_slice()).to_strbuf();
+ return format!("_{}", result.as_slice()).to_string();
}
return result;
let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
format!("v{}", vers)
} else {
- vers.to_owned()
+ vers.to_string()
};
mangle(path, Some(hash), Some(vers.as_slice()))
pub fn get_cc_prog(sess: &Session) -> String {
match sess.opts.cg.linker {
- Some(ref linker) => return linker.to_strbuf(),
+ Some(ref linker) => return linker.to_string(),
None => {}
}
match sess.targ_cfg.os {
abi::OsWin32 => "gcc",
_ => "cc",
- }.to_strbuf()
+ }.to_string()
}
pub fn get_ar_prog(sess: &Session) -> String {
match sess.opts.cg.ar {
Some(ref ar) => (*ar).clone(),
- None => "ar".to_strbuf()
+ None => "ar".to_string()
}
}
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
- module_asm: "".to_strbuf(),
+ module_asm: "".to_string(),
meta_sect_name:
- meta_section_name(cfg_os_to_meta_os(target_os)).to_strbuf(),
+ meta_section_name(cfg_os_to_meta_os(target_os)).to_string(),
data_layout: match target_os {
abi::OsMacos => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsWin32 => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsLinux => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsAndroid => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
abi::OsFreebsd => {
-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\
- -a0:0:64-n32".to_strbuf()
+ -a0:0:64-n32".to_string()
}
},
let mut flags = Vec::new();
if sess.targ_cfg.os == abi::OsFreebsd {
- flags.push_all(["-Wl,-rpath,/usr/local/lib/gcc46".to_strbuf(),
- "-Wl,-rpath,/usr/local/lib/gcc44".to_strbuf(),
- "-Wl,-z,origin".to_strbuf()]);
+ flags.push_all(["-Wl,-rpath,/usr/local/lib/gcc46".to_string(),
+ "-Wl,-rpath,/usr/local/lib/gcc44".to_string(),
+ "-Wl,-z,origin".to_string()]);
}
debug!("preparing the RPATH!");
path.push(&tlib);
let path = os::make_absolute(&path);
// FIXME (#9639): This needs to handle non-utf8 paths
- path.as_str().expect("non-utf8 component in rpath").to_strbuf()
+ path.as_str().expect("non-utf8 component in rpath").to_string()
}
pub fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
#[test]
fn test_rpaths_to_flags() {
let flags = rpaths_to_flags([
- "path1".to_strbuf(),
- "path2".to_strbuf()
+ "path1".to_string(),
+ "path2".to_string()
]);
assert_eq!(flags,
- vec!("-Wl,-rpath,path1".to_strbuf(),
- "-Wl,-rpath,path2".to_strbuf()));
+ vec!("-Wl,-rpath,path1".to_string(),
+ "-Wl,-rpath,path2".to_string()));
}
#[test]
#[test]
fn test_minimize1() {
let res = minimize_rpaths([
- "rpath1".to_strbuf(),
- "rpath2".to_strbuf(),
- "rpath1".to_strbuf()
+ "rpath1".to_string(),
+ "rpath2".to_string(),
+ "rpath1".to_string()
]);
assert!(res.as_slice() == [
- "rpath1".to_strbuf(),
- "rpath2".to_strbuf()
+ "rpath1".to_string(),
+ "rpath2".to_string()
]);
}
#[test]
fn test_minimize2() {
let res = minimize_rpaths([
- "1a".to_strbuf(),
- "2".to_strbuf(),
- "2".to_strbuf(),
- "1a".to_strbuf(),
- "4a".to_strbuf(),
- "1a".to_strbuf(),
- "2".to_strbuf(),
- "3".to_strbuf(),
- "4a".to_strbuf(),
- "3".to_strbuf()
+ "1a".to_string(),
+ "2".to_string(),
+ "2".to_string(),
+ "1a".to_string(),
+ "4a".to_string(),
+ "1a".to_string(),
+ "2".to_string(),
+ "3".to_string(),
+ "4a".to_string(),
+ "3".to_string()
]);
assert!(res.as_slice() == [
- "1a".to_strbuf(),
- "2".to_strbuf(),
- "4a".to_strbuf(),
- "3".to_strbuf()
+ "1a".to_string(),
+ "2".to_string(),
+ "4a".to_string(),
+ "3".to_string()
]);
}
impl Svh {
pub fn new(hash: &str) -> Svh {
assert!(hash.len() == 16);
- Svh { hash: hash.to_strbuf() }
+ Svh { hash: hash.to_string() }
}
pub fn as_str<'a>(&'a self) -> &'a str {
pub fn get_target_strs(target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
- module_asm: "".to_strbuf(),
+ module_asm: "".to_string(),
meta_sect_name:
- meta_section_name(cfg_os_to_meta_os(target_os)).to_strbuf(),
+ meta_section_name(cfg_os_to_meta_os(target_os)).to_string(),
data_layout: match target_os {
abi::OsMacos => {
-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".to_strbuf()
+ -n8:16:32".to_string()
}
abi::OsWin32 => {
- "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_strbuf()
+ "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
- "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_strbuf()
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
- "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_strbuf()
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsFreebsd => {
- "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_strbuf()
+ "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
},
target_triple: target_triple,
- cc_args: vec!("-m32".to_strbuf()),
+ cc_args: vec!("-m32".to_string()),
};
}
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
- module_asm: "".to_strbuf(),
+ module_asm: "".to_string(),
meta_sect_name:
- meta_section_name(cfg_os_to_meta_os(target_os)).to_strbuf(),
+ meta_section_name(cfg_os_to_meta_os(target_os)).to_string(),
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-\
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".to_strbuf()
+ s0:64:64-f80:128:128-n8:16:32:64".to_string()
}
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-\
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".to_strbuf()
+ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsLinux => {
"e-p:64:64:64-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:128:128-a0:0:64-\
- s0:64:64-f80:128:128-n8:16:32:64-S128".to_strbuf()
+ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsAndroid => {
"e-p:64:64:64-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:128:128-a0:0:64-\
- s0:64:64-f80:128:128-n8:16:32:64-S128".to_strbuf()
+ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsFreebsd => {
"e-p:64:64:64-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:128:128-a0:0:64-\
- s0:64:64-f80:128:128-n8:16:32:64-S128".to_strbuf()
+ s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
},
target_triple: target_triple,
- cc_args: vec!("-m64".to_strbuf()),
+ cc_args: vec!("-m64".to_string()),
};
}
output_types: Vec::new(),
addl_lib_search_paths: RefCell::new(HashSet::new()),
maybe_sysroot: None,
- target_triple: driver::host_triple().to_strbuf(),
+ target_triple: driver::host_triple().to_string(),
cfg: Vec::new(),
test: false,
parse_only: false,
fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
match v {
- Some(s) => { *slot = Some(s.to_strbuf()); true },
+ Some(s) => { *slot = Some(s.to_string()); true },
None => false,
}
}
fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
match v {
- Some(s) => { *slot = s.to_strbuf(); true },
+ Some(s) => { *slot = s.to_string(); true },
None => false,
}
}
match v {
Some(s) => {
for s in s.words() {
- slot.push(s.to_strbuf());
+ slot.push(s.to_string());
}
true
},
"system linker to link outputs with"),
link_args: Vec<String> = (Vec::new(), parse_list,
"extra arguments to pass to the linker (space separated)"),
- target_cpu: String = ("generic".to_strbuf(), parse_string,
+ target_cpu: String = ("generic".to_string(), parse_string,
"select target processor (llc -mcpu=help for details)"),
- target_feature: String = ("".to_strbuf(), parse_string,
+ target_feature: String = ("".to_string(), parse_string,
"target specific attributes (llc -mattr=help for details)"),
passes: Vec<String> = (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: String = ("pic".to_strbuf(), parse_string,
+ relocation_model: String = ("pic".to_string(), parse_string,
"choose the relocation model to use (llc -relocation-model for details)"),
)
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
cfgspecs.move_iter().map(|s| {
- parse::parse_meta_from_source_str("cfgspec".to_strbuf(),
- s.to_strbuf(),
+ parse::parse_meta_from_source_str("cfgspec".to_string(),
+ s.to_string(),
Vec::new(),
&parse::new_parse_sess())
}).collect::<ast::CrateConfig>()
.collect::<Vec<_>>()
.append(matches.opt_strs(level_name).as_slice());
for lint_name in flags.iter() {
- let lint_name = lint_name.replace("-", "_").into_strbuf();
+ let lint_name = lint_name.replace("-", "_").into_string();
match lint_dict.find_equiv(&lint_name) {
None => {
early_error(format!("unknown {} flag: {}",
let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
let target = match matches.opt_str("target") {
- Some(supplied_target) => supplied_target.to_strbuf(),
- None => driver::host_triple().to_strbuf(),
+ Some(supplied_target) => supplied_target.to_string(),
+ None => driver::host_triple().to_string(),
};
let opt_level = {
if (debugging_opts & NO_OPT) != 0 {
let cfg = parse_cfgspecs(matches.opt_strs("cfg")
.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect());
let test = matches.opt_present("test");
let write_dependency_info = (matches.opt_present("dep-info"),
#[test]
fn test_switch_implies_cfg_test() {
let matches =
- &match getopts(["--test".to_strbuf()], optgroups().as_slice()) {
+ &match getopts(["--test".to_string()], 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".to_strbuf(), "--cfg=test".to_strbuf()],
+ &match getopts(["--test".to_string(), "--cfg=test".to_string()],
optgroups().as_slice()) {
Ok(m) => m,
Err(f) => {
* (e.g. source from stdin or a string)
*/
pub fn anon_src() -> String {
- "<anon>".to_strbuf()
+ "<anon>".to_string()
}
pub fn source_name(input: &Input) -> String {
match *input {
// FIXME (#9639): This needs to handle non-utf8 paths
- FileInput(ref ifile) => ifile.as_str().unwrap().to_strbuf(),
+ FileInput(ref ifile) => ifile.as_str().unwrap().to_string(),
StrInput(_) => anon_src()
}
}
impl Input {
fn filestem(&self) -> String {
match *self {
- FileInput(ref ifile) => ifile.filestem_str().unwrap().to_strbuf(),
- StrInput(_) => "rust_out".to_strbuf(),
+ FileInput(ref ifile) => ifile.filestem_str().unwrap().to_string(),
+ StrInput(_) => "rust_out".to_string(),
}
}
}
parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
}
StrInput(ref src) => {
- parse::parse_crate_from_source_str(anon_src().to_strbuf(),
- src.to_strbuf(),
+ parse::parse_crate_from_source_str(anon_src().to_string(),
+ src.to_string(),
cfg.clone(),
&sess.parse_sess)
}
// write Makefile-compatible dependency rules
let files: Vec<String> = sess.codemap().files.borrow()
.iter().filter(|fmap| fmap.is_real_file())
- .map(|fmap| fmap.name.to_strbuf())
+ .map(|fmap| fmap.name.to_string())
.collect();
let mut file = try!(io::File::create(&deps_filename));
for path in out_filenames.iter() {
match node {
pprust::NodeItem(item) => {
try!(pp::space(&mut s.s));
- s.synth_comment(item.id.to_str().to_strbuf())
+ s.synth_comment(item.id.to_str().to_string())
}
pprust::NodeBlock(blk) => {
try!(pp::space(&mut s.s));
- s.synth_comment((format!("block {}", blk.id)).to_strbuf())
+ s.synth_comment((format!("block {}", blk.id)).to_string())
}
pprust::NodeExpr(expr) => {
try!(pp::space(&mut s.s));
- try!(s.synth_comment(expr.id.to_str().to_strbuf()));
+ try!(s.synth_comment(expr.id.to_str().to_string()));
s.pclose()
}
pprust::NodePat(pat) => {
try!(pp::space(&mut s.s));
- s.synth_comment((format!("pat {}", pat.id)).to_strbuf())
+ s.synth_comment((format!("pat {}", pat.id)).to_string())
}
}
}
pprust::print_crate(sess.codemap(),
sess.diagnostic(),
&krate,
- src_name.to_strbuf(),
+ src_name.to_string(),
&mut rdr,
out,
&IdentifiedAnnotation,
pprust::print_crate(annotation.analysis.ty_cx.sess.codemap(),
annotation.analysis.ty_cx.sess.diagnostic(),
&krate,
- src_name.to_strbuf(),
+ src_name.to_string(),
&mut rdr,
out,
&annotation,
pprust::print_crate(sess.codemap(),
sess.diagnostic(),
&krate,
- src_name.to_strbuf(),
+ src_name.to_string(),
&mut rdr,
out,
&pprust::NoAnn,
let cfg = cfg::CFG::new(ty_cx, block);
let lcfg = LabelledCFG { ast_map: &ty_cx.map,
cfg: &cfg,
- name: format!("block{}", block.id).to_strbuf(), };
+ name: format!("block{}", block.id).to_string(), };
debug!("cfg: {:?}", cfg);
let r = dot::render(&lcfg, &mut out);
return expand_err_details(r);
let m = "graphviz::render failed";
io::IoError {
detail: Some(match orig_detail {
- None => m.into_strbuf(),
+ None => m.into_string(),
Some(d) => format_strbuf!("{}: {}", m, d)
}),
..ioerr
ast::CRATE_NODE_ID,
a.span,
"invalid `crate_type` \
- value".to_strbuf());
+ value".to_string());
None
}
_ => {
ast::CRATE_NODE_ID,
a.span,
"`crate_type` requires a \
- value".to_strbuf());
+ value".to_string());
None
}
}
let crateid = attr::find_crateid(attrs);
match crateid {
None => {}
- Some(crateid) => stem = crateid.name.to_strbuf(),
+ Some(crateid) => stem = crateid.name.to_string(),
}
OutputFilenames {
out_directory: dirpath,
}
OutputFilenames {
out_directory: out_file.dir_path(),
- out_filestem: out_file.filestem_str().unwrap().to_strbuf(),
+ out_filestem: out_file.filestem_str().unwrap().to_string(),
single_output_file: ofile,
}
}
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8(contents.as_slice()).unwrap()
- .to_strbuf();
+ .to_string();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))
}
let r = matches.opt_strs("Z");
- if r.contains(&("ls".to_strbuf())) {
+ if r.contains(&("ls".to_string())) {
match input {
FileInput(ref ifile) => {
let mut stdout = io::stdout();
return None;
}
- if cg_flags.contains(&"passes=list".to_strbuf()) {
+ if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
return None;
}
}
StrInput(ref src) => {
parse::parse_crate_attrs_from_source_str(
- driver::anon_src().to_strbuf(),
- src.to_strbuf(),
+ driver::anon_src().to_string(),
+ src.to_string(),
Vec::new(),
&sess.parse_sess)
}
}
let xs = [
- "the compiler hit an unexpected failure path. this is a bug.".to_owned(),
+ "the compiler hit an unexpected failure path. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
- "run with `RUST_BACKTRACE=1` for a backtrace".to_owned(),
+ "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
];
for note in xs.iter() {
emitter.emit(None, note.as_slice(), diagnostic::Note)
sess.add_lint(lint::UnknownFeatures,
ast::CRATE_NODE_ID,
mi.span,
- "unknown feature".to_strbuf());
+ "unknown feature".to_string());
}
}
}
cx.ext_cx.bt_push(ExpnInfo {
call_site: DUMMY_SP,
callee: NameAndSpan {
- name: "test".to_strbuf(),
+ name: "test".to_string(),
format: MacroAttribute,
span: None
}
#![feature(macro_rules, globs, struct_variant, managed_boxes, quote,
default_type_params, phase)]
-extern crate flate;
extern crate arena;
+extern crate collections;
+extern crate debug;
+extern crate flate;
+extern crate getopts;
extern crate graphviz;
-extern crate syntax;
+extern crate libc;
extern crate serialize;
extern crate sync;
-extern crate getopts;
-extern crate collections;
+extern crate syntax;
extern crate time;
-extern crate libc;
#[phase(syntax, link)]
extern crate log;
pub fn main() {
let args = std::os::args().iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>();
std::os::set_exit_status(driver::main_args(args.as_slice()));
}
}
pub fn associate_type(&self, s: &str, t: &Type) {
- assert!(self.named_types.borrow_mut().insert(s.to_strbuf(),
+ assert!(self.named_types.borrow_mut().insert(s.to_string(),
t.to_ref()));
}
let s = llvm::LLVMTypeToString(ty.to_ref());
let ret = from_c_str(s);
free(s as *mut c_void);
- ret.to_strbuf()
+ ret.to_string()
}
}
pub fn types_to_str(&self, tys: &[Type]) -> String {
let strs: Vec<String> = tys.iter().map(|t| self.type_to_str(*t)).collect();
- format_strbuf!("[{}]", strs.connect(",").to_strbuf())
+ format_strbuf!("[{}]", strs.connect(",").to_string())
}
pub fn val_to_str(&self, val: ValueRef) -> String {
let s = llvm::LLVMValueToString(val);
let ret = from_c_str(s);
free(s as *mut c_void);
- ret.to_strbuf()
+ ret.to_string()
}
}
}
None => from_str(ident.get().to_str().as_slice()).unwrap()
};
Some(CrateInfo {
- ident: ident.get().to_strbuf(),
+ ident: ident.get().to_string(),
crate_id: crate_id,
id: id,
should_link: should_link(i),
} else {
e.sess
.cstore
- .add_used_library(n.get().to_strbuf(), kind);
+ .add_used_library(n.get().to_string(), kind);
}
}
None => {}
// Stash paths for top-most crate locally if necessary.
let crate_paths = if root.is_none() {
Some(CratePaths {
- ident: ident.to_strbuf(),
+ ident: ident.to_string(),
dylib: lib.dylib.clone(),
rlib: lib.rlib.clone(),
})
let loader::Library{ dylib, rlib, metadata } = lib;
let cmeta = Rc::new( cstore::crate_metadata {
- name: crate_id.name.to_strbuf(),
+ name: crate_id.name.to_string(),
data: metadata,
cnum_map: cnum_map,
cnum: cnum,
};
let macros = decoder::get_exported_macros(library.metadata.as_slice());
let registrar = decoder::get_macro_registrar_fn(library.metadata.as_slice()).map(|id| {
- decoder::get_symbol(library.metadata.as_slice(), id).to_strbuf()
+ decoder::get_symbol(library.metadata.as_slice(), id).to_string()
});
let mc = MacroCrate {
lib: library.dylib.clone(),
- macros: macros.move_iter().map(|x| x.to_strbuf()).collect(),
+ macros: macros.move_iter().map(|x| x.to_string()).collect(),
registrar_symbol: registrar,
};
if should_link {
decoder::maybe_find_item(class_id.node, all_items),
|| {
(format!("get_field_type: class ID {:?} not found",
- class_id)).to_strbuf()
+ class_id)).to_string()
});
let the_field = expect(tcx.sess.diagnostic(),
decoder::maybe_find_item(def.node, class_doc),
|| {
(format!("get_field_type: in class {:?}, field ID {:?} not found",
class_id,
- def)).to_strbuf()
+ def)).to_string()
});
let ty = decoder::item_type(def, the_field, tcx, &*cdata);
ty::ty_param_bounds_and_ty {
pub fn add_used_link_args(&self, args: &str) {
for s in args.split(' ') {
- self.used_link_args.borrow_mut().push(s.to_strbuf());
+ self.used_link_args.borrow_mut().push(s.to_string());
}
}
}
fn item_symbol(item: ebml::Doc) -> String {
- reader::get_doc(item, tag_items_data_item_symbol).as_str().to_strbuf()
+ reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
}
fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
let mut crate_num = 1;
fn docstr(doc: ebml::Doc, tag_: uint) -> String {
let d = reader::get_doc(doc, tag_);
- d.as_str_slice().to_strbuf()
+ d.as_str_slice().to_string()
}
reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
let crate_id =
pub fn get_crate_triple(data: &[u8]) -> String {
let cratedoc = reader::Doc(data);
let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
- triple_doc.expect("No triple in crate").as_str().to_strbuf()
+ triple_doc.expect("No triple in crate").as_str().to_string()
}
pub fn get_crate_id(data: &[u8]) -> CrateId {
let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
let kind: cstore::NativeLibaryKind =
FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
- let name = name_doc.as_str().to_strbuf();
+ let name = name_doc.as_str().to_string();
result.push((kind, name));
true
});
tag_exported_macros);
let mut result = Vec::new();
reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
- result.push(macro_doc.as_str().to_strbuf());
+ result.push(macro_doc.as_str().to_string());
true
});
result
match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
Some(args_doc) => {
reader::tagged_docs(args_doc, tag_method_argument_name, |name_doc| {
- ret.push(name_doc.as_str_slice().to_strbuf());
+ ret.push(name_doc.as_str_slice().to_string());
true
});
}
slot.map(|kind| (format!("{}:{}", i + 1, match kind {
cstore::RequireDynamic => "d",
cstore::RequireStatic => "s",
- })).to_strbuf())
+ })).to_string())
}).collect::<Vec<String>>();
ebml_w.writer.write(s.connect(",").as_bytes());
}
tcx: tcx,
abbrevs: &RefCell::new(HashMap::new())
}, t);
- str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_strbuf()
+ str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_string()
}
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
- os::getenv("RUST_PATH").map(|x| x.to_strbuf())
+ os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
#[cfg(target_word_size = "64")]
fn primary_libdir_name() -> String {
- "lib64".to_strbuf()
+ "lib64".to_string()
}
#[cfg(target_word_size = "32")]
fn primary_libdir_name() -> String {
- "lib32".to_strbuf()
+ "lib32".to_string()
}
fn secondary_libdir_name() -> String {
- "lib".to_strbuf()
+ "lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
- "bin".to_strbuf()
+ "bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
- "rustlib".to_strbuf()
+ "rustlib".to_string()
}
Some(..) => {} // check the hash
// hash is irrelevant, no version specified
- None => return Some(hash.to_strbuf())
+ None => return Some(hash.to_string())
}
debug!("matching -- {}, vers ok", file);
// hashes in filenames are prefixes of the "true hash"
if self.id_hash == hash.as_slice() {
debug!("matching -- {}, hash ok", file);
- Some(hash.to_strbuf())
+ Some(hash.to_string())
} else {
None
}
info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
self.rejected_via_triple.push(CrateMismatch {
path: libpath.clone(),
- got: triple.to_strbuf()
+ got: triple.to_string()
});
return false;
}
info!("Rejecting via hash: expected {} got {}", *myhash, hash);
self.rejected_via_hash.push(CrateMismatch {
path: libpath.clone(),
- got: myhash.as_str().to_strbuf()
+ got: myhash.as_str().to_string()
});
false
} else {
fn parse_abi_set(st: &mut PState) -> abi::Abi {
assert_eq!(next(st), '[');
scan(st, |c| c == ']', |bytes| {
- let abi_str = str::from_utf8(bytes).unwrap().to_owned();
+ let abi_str = str::from_utf8(bytes).unwrap().to_string();
abi::lookup(abi_str.as_slice()).expect(abi_str)
})
}
if restr.loan_path != loan2.loan_path { continue; }
let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
- "it".to_strbuf()
+ "it".to_string()
} else {
format!("`{}`",
self.bccx.loan_path_to_str(&*old_loan.loan_path))
}
err_out_of_scope(..) => {
let msg = match opt_loan_path(&err.cmt) {
- None => "borrowed value".to_strbuf(),
+ None => "borrowed value".to_string(),
Some(lp) => {
format_strbuf!("`{}`", self.loan_path_to_str(&*lp))
}
self.kind,
self.gen_scope,
self.kill_scope,
- self.restrictions.repr(tcx))).to_strbuf()
+ self.restrictions.repr(tcx))).to_string()
}
}
fn repr(&self, tcx: &ty::ctxt) -> String {
(format!("Restriction({}, {:x})",
self.loan_path.repr(tcx),
- self.set.bits as uint)).to_strbuf()
+ self.set.bits as uint)).to_string()
}
}
fn repr(&self, tcx: &ty::ctxt) -> String {
match self {
&LpVar(id) => {
- (format!("$({})", tcx.map.node_to_str(id))).to_strbuf()
+ (format!("$({})", tcx.map.node_to_str(id))).to_string()
}
&LpExtend(ref lp, _, LpDeref(_)) => {
- (format!("{}.*", lp.repr(tcx))).to_strbuf()
+ (format!("{}.*", lp.repr(tcx))).to_string()
}
&LpExtend(ref lp, _, LpInterior(ref interior)) => {
(format!("{}.{}",
lp.repr(tcx),
- interior.repr(tcx))).to_strbuf()
+ interior.repr(tcx))).to_string()
}
}
}
self.pats_all(post.iter().map(|p| *p), vec_exit);
self.add_node(pat.id, [post_exit])
}
+
+ ast::PatMac(_) => {
+ self.tcx.sess.span_bug(pat.span, "unexpanded macro");
+ }
}
}
if last_two.as_slice() != ['\\', 'l'] {
s = s.append("\\l");
}
- s.to_strbuf()
+ s.to_string()
} else {
s
}
match ty::get(ty).sty {
ty::ty_bool => {
match *ctor {
- val(const_bool(true)) => Some("true".to_strbuf()),
- val(const_bool(false)) => Some("false".to_strbuf()),
+ val(const_bool(true)) => Some("true".to_string()),
+ val(const_bool(false)) => Some("false".to_string()),
_ => None
}
}
Some(v) => {
Some(token::get_ident(v.name).get()
.to_str()
- .into_strbuf())
+ .into_string())
}
None => {
fail!("check_exhaustive: bad variant in ctor")
};
let msg = format_strbuf!("non-exhaustive patterns{}", match ext {
Some(ref s) => format_strbuf!(": {} not covered", *s),
- None => "".to_strbuf()
+ None => "".to_string()
});
cx.tcx.sess.span_err(sp, msg.as_slice());
}
None => Some(vec(before.len() + after.len()))
}
}
+ PatMac(_) => cx.tcx.sess.bug("unexpanded macro"),
}
}
_ => None
}
}
+ PatMac(_) => {
+ cx.tcx.sess.span_err(pat_span, "unexpanded macro");
+ None
+ }
}
}
}
fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
visit::walk_local(cx, loc, ());
- if is_refutable(cx, loc.pat) {
- cx.tcx.sess.span_err(loc.pat.span,
- "refutable pattern in local binding");
+
+ let name = match loc.source {
+ LocalLet => "local",
+ LocalFor => "`for` loop"
+ };
+
+ let mut spans = vec![];
+ find_refutable(cx, loc.pat, &mut spans);
+
+ for span in spans.iter() {
+ cx.tcx.sess.span_err(*span,
+ format!("refutable pattern in {} binding", name).as_slice());
}
// Check legality of move bindings.
sp: Span) {
visit::walk_fn(cx, kind, decl, body, sp, ());
for input in decl.inputs.iter() {
- if is_refutable(cx, input.pat) {
- cx.tcx.sess.span_err(input.pat.span,
+ let mut spans = vec![];
+ find_refutable(cx, input.pat, &mut spans);
+
+ for span in spans.iter() {
+ cx.tcx.sess.span_err(*span,
"refutable pattern in function argument");
}
}
}
-fn is_refutable(cx: &MatchCheckCtxt, pat: &Pat) -> bool {
+fn find_refutable(cx: &MatchCheckCtxt, pat: &Pat, spans: &mut Vec<Span>) {
+ macro_rules! this_pattern {
+ () => {
+ {
+ spans.push(pat.span);
+ return
+ }
+ }
+ }
let opt_def = cx.tcx.def_map.borrow().find_copy(&pat.id);
match opt_def {
Some(DefVariant(enum_id, _, _)) => {
if ty::enum_variants(cx.tcx, enum_id).len() != 1u {
- return true;
+ this_pattern!()
}
}
- Some(DefStatic(..)) => return true,
+ Some(DefStatic(..)) => this_pattern!(),
_ => ()
}
match pat.node {
PatUniq(sub) | PatRegion(sub) | PatIdent(_, _, Some(sub)) => {
- is_refutable(cx, sub)
+ find_refutable(cx, sub, spans)
}
- PatWild | PatWildMulti | PatIdent(_, _, None) => { false }
+ PatWild | PatWildMulti | PatIdent(_, _, None) => {}
PatLit(lit) => {
match lit.node {
ExprLit(lit) => {
match lit.node {
- LitNil => false, // `()`
- _ => true,
+ LitNil => {} // `()`
+ _ => this_pattern!(),
}
}
- _ => true,
+ _ => this_pattern!(),
}
}
- PatRange(_, _) => { true }
+ PatRange(_, _) => { this_pattern!() }
PatStruct(_, ref fields, _) => {
- fields.iter().any(|f| is_refutable(cx, f.pat))
- }
- PatTup(ref elts) => {
- elts.iter().any(|elt| is_refutable(cx, *elt))
+ for f in fields.iter() {
+ find_refutable(cx, f.pat, spans);
+ }
}
- PatEnum(_, Some(ref args)) => {
- args.iter().any(|a| is_refutable(cx, *a))
+ PatTup(ref elts) | PatEnum(_, Some(ref elts))=> {
+ for elt in elts.iter() {
+ find_refutable(cx, *elt, spans)
+ }
}
- PatEnum(_,_) => { false }
- PatVec(..) => { true }
+ PatEnum(_,_) => {}
+ PatVec(..) => { this_pattern!() }
+ PatMac(_) => cx.tcx.sess.bug("unexpanded macro"),
}
}
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
Some("static items are not allowed to have \
- destructors".to_strbuf()));
+ destructors".to_string()));
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".to_strbuf()),
- Ok(const_bool(_)) => Err("negate on boolean".to_strbuf()),
+ Ok(const_str(_)) => Err("negate on string".to_string()),
+ Ok(const_bool(_)) => Err("negate on boolean".to_string()),
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".to_strbuf())
+ _ => Err("not on float or string".to_string())
}
}
ExprBinary(op, a, b) => {
BiNe => fromb(a != b),
BiGe => fromb(a >= b),
BiGt => fromb(a > b),
- _ => Err("can't do this op on floats".to_strbuf())
+ _ => Err("can't do this op on floats".to_string())
}
}
(Ok(const_int(a)), Ok(const_int(b))) => {
BiSub => Ok(const_int(a - b)),
BiMul => Ok(const_int(a * b)),
BiDiv if b == 0 => {
- Err("attempted to divide by zero".to_strbuf())
+ Err("attempted to divide by zero".to_string())
}
BiDiv => Ok(const_int(a / b)),
BiRem if b == 0 => {
Err("attempted remainder with a divisor of \
- zero".to_strbuf())
+ zero".to_string())
}
BiRem => Ok(const_int(a % b)),
BiAnd | BiBitAnd => Ok(const_int(a & b)),
BiSub => Ok(const_uint(a - b)),
BiMul => Ok(const_uint(a * b)),
BiDiv if b == 0 => {
- Err("attempted to divide by zero".to_strbuf())
+ Err("attempted to divide by zero".to_string())
}
BiDiv => Ok(const_uint(a / b)),
BiRem if b == 0 => {
Err("attempted remainder with a divisor of \
- zero".to_strbuf())
+ zero".to_string())
}
BiRem => Ok(const_uint(a % b)),
BiAnd | BiBitAnd => 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".to_strbuf())
+ _ => Err("can't do this op on an int and uint".to_string())
}
}
(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".to_strbuf())
+ _ => Err("can't do this op on a uint and int".to_string())
}
}
(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".to_strbuf())
+ _ => return Err("can't do this op on bools".to_string())
}))
}
- _ => Err("bad operands for binary".to_strbuf())
+ _ => Err("bad operands for binary".to_string())
}
}
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".to_strbuf()),
+ _ => Err("can't cast float to str".to_string()),
}
}
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".to_strbuf()),
+ _ => Err("can't cast str to uint".to_string()),
}
}
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".to_strbuf()),
+ _ => Err("can't cast str to int".to_string()),
}
}
- _ => Err("can't cast this type".to_strbuf())
+ _ => Err("can't cast this type".to_string())
}
}
}
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".to_strbuf())
+ None => Err("non-constant path in constant expr".to_string())
}
}
ExprLit(lit) => Ok(lit_to_const(lit)),
None => Ok(const_int(0i64))
}
}
- _ => Err("unsupported constant expr".to_strbuf())
+ _ => Err("unsupported constant expr".to_string())
}
}
let gens_str = if gens.iter().any(|&u| u != 0) {
format!(" gen: {}", bits_to_str(gens))
} else {
- "".to_strbuf()
+ "".to_string()
};
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_strbuf()
+ "".to_string()
};
try!(ps.synth_comment(format_strbuf!("id {}: {}{}{}",
// Check that any variables in a pattern have types with statically known size.
fn check_pat(cx: &mut Context, pat: &Pat) {
let var_name = match pat.node {
- PatWild => Some("_".to_strbuf()),
- PatIdent(_, ref path, _) => Some(path_to_str(path).to_strbuf()),
+ PatWild => Some("_".to_string()),
+ PatIdent(_, ref path, _) => Some(path_to_str(path).to_string()),
_ => None
};
VarDefNode(s) => {
format_strbuf!("Var def node [{}]", cm.span_to_str(s))
}
- ExitNode => "Exit node".to_strbuf(),
+ ExitNode => "Exit node".to_string(),
}
}
fn variable_name(&self, var: Variable) -> String {
match self.var_kinds.get(var.get()) {
&Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
- token::get_ident(nm).get().to_str().to_strbuf()
+ token::get_ident(nm).get().to_str().to_string()
},
- &ImplicitRet => "<implicit-ret>".to_strbuf()
+ &ImplicitRet => "<implicit-ret>".to_string()
}
}
self.write_vars(wr, ln, |idx| self.users.get(idx).writer);
write!(wr, " precedes {}]", self.successors.get(ln.get()).to_str());
}
- str::from_utf8(wr.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string()
}
fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) {
ast::PatLit(_) | ast::PatRange(_, _) => {
/*always ok*/
}
+
+ ast::PatMac(_) => {
+ self.tcx().sess.span_bug(pat.span, "unexpanded macro");
+ }
}
Ok(())
pub fn cmt_to_str(&self, cmt: &cmt_) -> String {
match cmt.cat {
cat_static_item => {
- "static item".to_strbuf()
+ "static item".to_string()
}
cat_copied_upvar(_) => {
- "captured outer variable in a proc".to_strbuf()
+ "captured outer variable in a proc".to_string()
}
cat_rvalue(..) => {
- "non-lvalue".to_strbuf()
+ "non-lvalue".to_string()
}
cat_local(_) => {
- "local variable".to_strbuf()
+ "local variable".to_string()
}
cat_arg(..) => {
- "argument".to_strbuf()
+ "argument".to_string()
}
cat_deref(ref base, _, pk) => {
match base.cat {
cat_upvar(..) => {
- "captured outer variable".to_strbuf()
+ "captured outer variable".to_string()
}
_ => {
format_strbuf!("dereference of `{}`-pointer",
}
}
cat_interior(_, InteriorField(NamedField(_))) => {
- "field".to_strbuf()
+ "field".to_string()
}
cat_interior(_, InteriorField(PositionalField(_))) => {
- "anonymous field".to_strbuf()
+ "anonymous field".to_string()
}
cat_interior(_, InteriorElement(VecElement)) => {
- "vec content".to_strbuf()
+ "vec content".to_string()
}
cat_interior(_, InteriorElement(StrElement)) => {
- "str content".to_strbuf()
+ "str content".to_string()
}
cat_interior(_, InteriorElement(OtherElement)) => {
- "indexed content".to_strbuf()
+ "indexed content".to_string()
}
cat_upvar(..) => {
- "captured outer variable".to_strbuf()
+ "captured outer variable".to_string()
}
cat_discr(ref cmt, _) => {
self.cmt_to_str(&**cmt)
fn repr(&self, _tcx: &ty::ctxt) -> String {
match *self {
InteriorField(NamedField(fld)) => {
- token::get_name(fld).get().to_str().to_strbuf()
+ token::get_name(fld).get().to_str().to_string()
}
InteriorField(PositionalField(i)) => format_strbuf!("\\#{:?}", i),
- InteriorElement(_) => "[]".to_strbuf(),
+ InteriorElement(_) => "[]".to_string(),
}
}
}
impl<'a> PrivacyVisitor<'a> {
// used when debugging
fn nodestr(&self, id: ast::NodeId) -> String {
- self.tcx.map.node_to_str(id).to_strbuf()
+ self.tcx.map.node_to_str(id).to_string()
}
// Determines whether the given definition is public from the point of view
lint::VisiblePrivateTypes,
path_id, p.span,
"private type in exported type \
- signature".to_strbuf());
+ signature".to_string());
}
}
_ => {}
-> String {
match subclass {
SingleImport(_, source) => {
- token::get_ident(source).get().to_strbuf()
+ token::get_ident(source).get().to_string()
}
- GlobImport => "*".to_strbuf()
+ GlobImport => "*".to_string()
}
}
(format!("{}::{}",
self.idents_to_str(idents),
self.import_directive_subclass_to_str(
- subclass))).to_strbuf()
+ subclass))).to_string()
}
}
debug!("(computing exports) YES: export '{}' => {:?}",
name, def_id_of_def(d));
exports2.push(Export2 {
- name: name.get().to_strbuf(),
+ name: name.get().to_string(),
def_id: def_id_of_def(d)
});
}
.add_lint(UnnecessaryQualification,
id,
path.span,
- "unnecessary qualification".to_strbuf());
+ "unnecessary qualification".to_string());
}
_ => ()
}
*values.get(smallest) <= max_distance &&
name != maybes.get(smallest).get() {
- Some(maybes.get(smallest).get().to_strbuf())
+ Some(maybes.get(smallest).get().to_string())
} else {
None
// limit search to 5 to reduce the number
// of stupid suggestions
self.find_best_match_for_name(wrong_name.as_slice(), 5)
- .map_or("".to_strbuf(),
+ .map_or("".to_string(),
|x| format!("`{}`", x))
}
Field =>
.add_lint(UnusedImports,
id,
p.span,
- "unused import".to_strbuf());
+ "unused import".to_string());
}
},
}
self.session.add_lint(UnusedImports,
id,
span,
- "unused import".to_strbuf());
+ "unused import".to_string());
}
let (v_priv, t_priv) = match self.last_private.find(&id) {
collect_mod(&mut idents, module);
if idents.len() == 0 {
- return "???".to_strbuf();
+ return "???".to_string();
}
self.idents_to_str(idents.move_iter().rev()
.collect::<Vec<ast::Ident>>()
for (&name, import_resolution) in import_resolutions.iter() {
let value_repr;
match import_resolution.target_for_namespace(ValueNS) {
- None => { value_repr = "".to_owned(); }
+ None => { value_repr = "".to_string(); }
Some(_) => {
- value_repr = " value:?".to_owned();
+ value_repr = " value:?".to_string();
// FIXME #4954
}
}
let type_repr;
match import_resolution.target_for_namespace(TypeNS) {
- None => { type_repr = "".to_owned(); }
+ None => { type_repr = "".to_string(); }
Some(_) => {
- type_repr = " type:?".to_owned();
+ type_repr = " type:?".to_string();
// FIXME #4954
}
}
let root_msg = match self.root_ty {
Some(root) => format!(" in the substitution of `{}`",
root.repr(self.tcx)),
- None => "".to_strbuf()
+ None => "".to_string()
};
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 => "".to_strbuf()
+ None => "".to_string()
};
let m = format!("missing `Self` type param{}",
root_msg);
bcx.sess().span_bug(pat.span,
"vector patterns are never irrefutable!");
}
+ ast::PatMac(..) => {
+ bcx.sess().span_bug(pat.span, "unexpanded macro");
+ }
ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => ()
}
return bcx;
let mut constraints =
String::from_str(constraints.iter()
- .map(|s| s.get().to_strbuf())
+ .map(|s| s.get().to_string())
.collect::<Vec<String>>()
.connect(",")
.as_slice());
#[cfg(target_arch = "arm")]
#[cfg(target_arch = "mips")]
fn getClobbers() -> String {
- "".to_strbuf()
+ "".to_string()
}
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
fn getClobbers() -> String {
- "~{dirflag},~{fpsr},~{flags}".to_strbuf()
+ "~{dirflag},~{fpsr},~{flags}".to_string()
}
None => {}
}
let f = decl_fn(ccx.llmod, name, cc, ty, output);
- externs.insert(name.to_strbuf(), f);
+ externs.insert(name.to_string(), f);
f
}
set_llvm_fn_attrs(attrs.as_slice(), f)
});
- ccx.externs.borrow_mut().insert(name.to_strbuf(), f);
+ ccx.externs.borrow_mut().insert(name.to_string(), f);
f
}
let c = name.with_c_str(|buf| {
llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
});
- externs.insert(name.to_strbuf(), c);
+ externs.insert(name.to_string(), c);
return c;
}
}
debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
if id == -1 {
- "".to_owned()
+ "".to_string()
} else {
- ccx.tcx.map.path_to_str(id).to_owned()
+ ccx.tcx.map.path_to_str(id).to_string()
},
id, param_substs.map(|s| s.repr(ccx.tcx())));
param_substs: Option<¶m_substs>,
id: ast::NodeId,
attrs: &[ast::Attribute]) {
- let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_strbuf());
+ let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_string());
debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
let _icx = push_ctxt("trans_fn");
let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
ty: ty::t, attrs: &[ast::Attribute]) -> String {
match attr::first_attr_value_str_by_name(attrs, "export_name") {
// Use provided name
- Some(name) => name.get().to_strbuf(),
+ Some(name) => name.get().to_string(),
_ => ccx.tcx.map.with_path(id, |mut path| {
if attr::contains_name(attrs, "no_mangle") {
// Don't mangle
- path.last().unwrap().to_str().to_strbuf()
+ path.last().unwrap().to_str().to_string()
} else {
match weak_lang_items::link_name(attrs) {
- Some(name) => name.get().to_strbuf(),
+ Some(name) => name.get().to_string(),
None => {
// Usual name mangling
mangle_exported_name(ccx, path, ty, id)
let llmod = ccx.llmod;
let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
- ccx.item_symbols.borrow().find(id).map(|s| s.to_strbuf())
+ ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
}).collect();
// Make sure that some other crucial symbols are not eliminated from the
// 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".to_strbuf());
- reachable.push("rust_stack_exhausted".to_strbuf());
+ reachable.push("main".to_string());
+ reachable.push("rust_stack_exhausted".to_string());
// referenced from .eh_frame section on some platforms
- reachable.push("rust_eh_personality".to_strbuf());
+ reachable.push("rust_eh_personality".to_string());
// referenced from rt/rust_try.ll
- reachable.push("rust_eh_personality_catch".to_strbuf());
+ reachable.push("rust_eh_personality_catch".to_string());
let metadata_module = ccx.metadata_llmod;
let formats = ccx.tcx.dependency_formats.borrow().clone();
let map_node = session::expect(
ccx.sess(),
tcx.map.find(def_id.node),
- || "local item should be in ast map".to_strbuf());
+ || "local item should be in ast map".to_string());
match map_node {
ast_map::NodeForeignItem(_) => {
pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
pub fn ident(&self, ident: Ident) -> String {
- token::get_ident(ident).get().to_strbuf()
+ token::get_ident(ident).get().to_string()
}
pub fn node_id_to_str(&self, id: ast::NodeId) -> String {
- self.tcx().map.node_to_str(id).to_strbuf()
+ self.tcx().map.node_to_str(id).to_string()
}
pub fn expr_to_str(&self, e: &ast::Expr) -> String {
let containing_scope = namespace_node.scope;
(linkage_name, containing_scope)
} else {
- (function_name.as_slice().to_strbuf(), file_metadata)
+ (function_name.as_slice().to_string(), file_metadata)
};
// Clang sets this parameter to the opening brace of the function's block, so let's do this too.
});
let mut created_files = debug_context(cx).created_files.borrow_mut();
- created_files.insert(full_path.to_strbuf(), file_metadata);
+ created_files.insert(full_path.to_string(), file_metadata);
return file_metadata;
}
debug!("basic_type_metadata: {:?}", ty::get(t));
let (name, encoding) = match ty::get(t).sty {
- 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_nil => ("()".to_string(), DW_ATE_unsigned),
+ ty::ty_bot => ("!".to_string(), DW_ATE_unsigned),
+ ty::ty_bool => ("bool".to_string(), DW_ATE_boolean),
+ ty::ty_char => ("char".to_string(), DW_ATE_unsigned_char),
ty::ty_int(int_ty) => match int_ty {
- 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)
+ ast::TyI => ("int".to_string(), DW_ATE_signed),
+ ast::TyI8 => ("i8".to_string(), DW_ATE_signed),
+ ast::TyI16 => ("i16".to_string(), DW_ATE_signed),
+ ast::TyI32 => ("i32".to_string(), DW_ATE_signed),
+ ast::TyI64 => ("i64".to_string(), DW_ATE_signed)
},
ty::ty_uint(uint_ty) => match uint_ty {
- 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)
+ ast::TyU => ("uint".to_string(), DW_ATE_unsigned),
+ ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned),
+ ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned),
+ ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned),
+ ast::TyU64 => ("u64".to_string(), DW_ATE_unsigned)
},
ty::ty_float(float_ty) => match float_ty {
- ast::TyF32 => ("f32".to_owned(), DW_ATE_float),
- ast::TyF64 => ("f64".to_owned(), DW_ATE_float),
- ast::TyF128 => ("f128".to_owned(), DW_ATE_float)
+ ast::TyF32 => ("f32".to_string(), DW_ATE_float),
+ ast::TyF64 => ("f64".to_string(), DW_ATE_float),
+ ast::TyF128 => ("f128".to_string(), DW_ATE_float)
},
_ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
};
self.fields.iter().enumerate().map(|(i, field)| {
let name = if field.ident.name == special_idents::unnamed_field.name {
- "".to_strbuf()
+ "".to_string()
} else {
- token::get_ident(field.ident).get().to_strbuf()
+ token::get_ident(field.ident).get().to_string()
};
let offset = if self.is_simd {
-> Vec<MemberDescription> {
self.component_types.iter().map(|&component_type| {
MemberDescription {
- name: "".to_strbuf(),
+ name: "".to_string(),
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: "".to_strbuf(),
+ name: "".to_string(),
llvm_type: variant_llvm_type,
type_metadata: variant_type_metadata,
offset: FixedMemberOffset { bytes: 0 },
-> Vec<MemberDescription> {
self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
MemberDescription {
- name: name.to_strbuf(),
+ name: name.to_string(),
llvm_type: type_of::type_of(cx, ty),
type_metadata: match self.discriminant_type_metadata {
Some(metadata) if i == 0 => metadata,
Some(ref names) => {
names.iter()
.map(|ident| {
- token::get_ident(*ident).get().to_str().into_strbuf()
+ token::get_ident(*ident).get().to_str().into_string()
}).collect()
}
- None => variant_info.args.iter().map(|_| "".to_strbuf()).collect()
+ None => variant_info.args.iter().map(|_| "".to_string()).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, "".to_strbuf());
+ arg_names.insert(0, "".to_string());
}
// Build an array of (field name, field type) pairs to be captured in the factory closure.
let args: Vec<(String, ty::t)> = arg_names.iter()
.zip(struct_def.fields.iter())
- .map(|(s, &t)| (s.to_strbuf(), t))
+ .map(|(s, &t)| (s.to_string(), t))
.collect();
let member_description_factory =
-> DICompositeType {
let box_type_name = match content_type_name {
Some(content_type_name) => format!("Boxed<{}>", content_type_name),
- None => "BoxedType".to_strbuf()
+ None => "BoxedType".to_string()
};
let box_llvm_type = Type::at_box(cx, content_llvm_type);
let member_descriptions = [
MemberDescription {
- name: "refcnt".to_strbuf(),
+ name: "refcnt".to_string(),
llvm_type: *member_llvm_types.get(0),
type_metadata: type_metadata(cx, int_type, codemap::DUMMY_SP),
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "drop_glue".to_strbuf(),
+ name: "drop_glue".to_string(),
llvm_type: *member_llvm_types.get(1),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "prev".to_strbuf(),
+ name: "prev".to_string(),
llvm_type: *member_llvm_types.get(2),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "next".to_strbuf(),
+ name: "next".to_string(),
llvm_type: *member_llvm_types.get(3),
type_metadata: nil_pointer_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "val".to_strbuf(),
+ name: "val".to_string(),
llvm_type: *member_llvm_types.get(4),
type_metadata: content_type_metadata,
offset: ComputedMemberOffset,
let member_descriptions = [
MemberDescription {
- name: "fill".to_strbuf(),
+ name: "fill".to_string(),
llvm_type: *member_llvm_types.get(0),
type_metadata: int_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "alloc".to_strbuf(),
+ name: "alloc".to_string(),
llvm_type: *member_llvm_types.get(1),
type_metadata: int_type_metadata,
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "elements".to_strbuf(),
+ name: "elements".to_string(),
llvm_type: *member_llvm_types.get(2),
type_metadata: array_type_metadata,
offset: ComputedMemberOffset,
let member_descriptions = [
MemberDescription {
- name: "data_ptr".to_strbuf(),
+ name: "data_ptr".to_string(),
llvm_type: *member_llvm_types.get(0),
type_metadata: type_metadata(cx, data_ptr_type, span),
offset: ComputedMemberOffset,
},
MemberDescription {
- name: "length".to_strbuf(),
+ name: "length".to_string(),
llvm_type: *member_llvm_types.get(1),
type_metadata: type_metadata(cx, ty::mk_uint(), span),
offset: ComputedMemberOffset,
walk_pattern(cx, sub_pat, scope_stack, scope_map);
}
}
+
+ ast::PatMac(_) => {
+ cx.sess().span_bug(pat.span, "debuginfo::populate_scope_map() - \
+ Found unexpanded macro.");
+ }
}
}
pub fn to_str(&self, ccx: &CrateContext) -> String {
match *self {
SaveIn(v) => format_strbuf!("SaveIn({})", ccx.tn.val_to_str(v)),
- Ignore => "Ignore".to_strbuf()
+ Ignore => "Ignore".to_string()
}
}
}
});
lib::llvm::SetLinkage(g1, linkage);
- let mut real_name = "_rust_extern_with_linkage_".to_strbuf();
+ let mut real_name = "_rust_extern_with_linkage_".to_string();
real_name.push_str(ident.get());
let g2 = real_name.with_c_str(|buf| {
llvm::LLVMAddGlobal(ccx.llmod, llty.to_ref(), buf)
}
ccx.item_symbols.borrow_mut().insert(foreign_item.id,
- lname.get().to_strbuf());
+ lname.get().to_string());
}
}
ty::ty_rptr(_, ref mt) => {
match ty::get(mt.ty).sty {
ty::ty_vec(ref mt, None) => {
- let (name, extra) = ("slice".to_owned(), Vec::new());
+ let (name, extra) = ("slice".to_string(), Vec::new());
let extra = extra.append(self.c_mt(mt).as_slice());
self.visit(format!("evec_{}", name).as_slice(),
extra.as_slice())
content_expr: &ast::Expr)
-> DatumBlock<'a, Expr> {
/*!
- * ~[...] and "...".to_owned() allocate boxes in the exchange heap and write
+ * ~[...] and "...".to_string() allocate boxes in the exchange heap and write
* the array elements into them.
*/
let fcx = bcx.fcx;
let ccx = fcx.ccx;
- // Handle "".to_owned().
+ // Handle "".to_string().
match content_expr.node {
ast::ExprLit(lit) => {
match lit.node {
"no field named `{}` found in the list of fields `{:?}`",
token::get_name(name),
fields.iter()
- .map(|f| token::get_ident(f.ident).get().to_strbuf())
+ .map(|f| token::get_ident(f.ident).get().to_string())
.collect::<Vec<String>>()).as_slice());
}
}
ty_enum(id, _) => format_strbuf!("enum {}", item_path_str(cx, id)),
- ty_box(_) => "@-ptr".to_strbuf(),
- ty_uniq(_) => "box".to_strbuf(),
- ty_vec(_, _) => "vector".to_strbuf(),
- ty_ptr(_) => "*-ptr".to_strbuf(),
- ty_rptr(_, _) => "&-ptr".to_strbuf(),
- ty_bare_fn(_) => "extern fn".to_strbuf(),
- ty_closure(_) => "fn".to_strbuf(),
+ ty_box(_) => "@-ptr".to_string(),
+ ty_uniq(_) => "box".to_string(),
+ ty_vec(_, _) => "vector".to_string(),
+ ty_ptr(_) => "*-ptr".to_string(),
+ ty_rptr(_, _) => "&-ptr".to_string(),
+ ty_bare_fn(_) => "extern fn".to_string(),
+ ty_closure(_) => "fn".to_string(),
ty_trait(ref inner) => {
format_strbuf!("trait {}", item_path_str(cx, inner.def_id))
}
ty_struct(id, _) => {
format_strbuf!("struct {}", item_path_str(cx, id))
}
- ty_tup(_) => "tuple".to_strbuf(),
- ty_infer(TyVar(_)) => "inferred type".to_strbuf(),
- ty_infer(IntVar(_)) => "integral variable".to_strbuf(),
- ty_infer(FloatVar(_)) => "floating-point variable".to_strbuf(),
- ty_param(_) => "type parameter".to_strbuf(),
- ty_self(_) => "self".to_strbuf(),
- ty_err => "type error".to_strbuf(),
+ ty_tup(_) => "tuple".to_string(),
+ ty_infer(TyVar(_)) => "inferred type".to_string(),
+ ty_infer(IntVar(_)) => "integral variable".to_string(),
+ ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
+ ty_param(_) => "type parameter".to_string(),
+ ty_self(_) => "self".to_string(),
+ ty_err => "type error".to_string(),
}
}
fn tstore_to_closure(s: &TraitStore) -> String {
match s {
- &UniqTraitStore => "proc".to_strbuf(),
- &RegionTraitStore(..) => "closure".to_strbuf()
+ &UniqTraitStore => "proc".to_string(),
+ &RegionTraitStore(..) => "closure".to_string()
}
}
match *err {
- terr_mismatch => "types differ".to_strbuf(),
+ terr_mismatch => "types differ".to_string(),
terr_fn_style_mismatch(values) => {
format_strbuf!("expected {} fn but found {} fn",
values.expected.to_str(),
tstore_to_closure(&values.expected),
tstore_to_closure(&values.found))
}
- terr_mutability => "values differ in mutability".to_strbuf(),
+ terr_mutability => "values differ in mutability".to_string(),
terr_box_mutability => {
- "boxed values differ in mutability".to_strbuf()
+ "boxed values differ in mutability".to_string()
}
- terr_vec_mutability => "vectors differ in mutability".to_strbuf(),
- terr_ptr_mutability => "pointers differ in mutability".to_strbuf(),
- terr_ref_mutability => "references differ in mutability".to_strbuf(),
+ terr_vec_mutability => "vectors differ in mutability".to_string(),
+ terr_ptr_mutability => "pointers differ in mutability".to_string(),
+ terr_ref_mutability => "references differ in mutability".to_string(),
terr_ty_param_size(values) => {
format_strbuf!("expected a type with {} type params \
but found one with {} type params",
values.found)
}
terr_record_mutability => {
- "record elements differ in mutability".to_strbuf()
+ "record elements differ in mutability".to_string()
}
terr_record_fields(values) => {
format_strbuf!("expected a record with field `{}` but found one \
token::get_ident(values.found))
}
terr_arg_count => {
- "incorrect number of function parameters".to_strbuf()
+ "incorrect number of function parameters".to_string()
}
terr_regions_does_not_outlive(..) => {
- "lifetime mismatch".to_strbuf()
+ "lifetime mismatch".to_string()
}
terr_regions_not_same(..) => {
- "lifetimes are not the same".to_strbuf()
+ "lifetimes are not the same".to_string()
}
terr_regions_no_overlap(..) => {
- "lifetimes do not intersect".to_strbuf()
+ "lifetimes do not intersect".to_string()
}
terr_regions_insufficiently_polymorphic(br, _) => {
format_strbuf!("expected bound lifetime parameter {}, \
}
}
terr_integer_as_char => {
- "expected an integral type but found `char`".to_strbuf()
+ "expected an integral type but found `char`".to_string()
}
terr_int_mismatch(ref values) => {
format_strbuf!("expected `{}` but found `{}`",
}
pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
- with_path(cx, id, |path| ast_map::path_to_str(path)).to_strbuf()
+ with_path(cx, id, |path| ast_map::path_to_str(path)).to_string()
}
pub enum DtorKind {
// 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("".to_strbuf(), |e| {
+ expected.map_or("".to_string(), |e| {
format_strbuf!("mismatched types: expected `{}` but \
found {}",
e,
actual)
})},
Some(expected),
- "a structure pattern".to_strbuf(),
+ "a structure pattern".to_string(),
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("".to_strbuf(),
+ expected.map_or("".to_string(),
|e| {
format_strbuf!("mismatched types: expected `{}` but \
found {}",
})
},
Some(expected),
- "an enum or structure pattern".to_strbuf(),
+ "an enum or structure pattern".to_string(),
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".to_strbuf())
+ || "mismatched types in range".to_string())
{
// 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("".to_strbuf(),
+ expected.map_or("".to_string(),
|e| {
format_strbuf!("mismatched types: expected \
`{}` but found {}",
actual)
})},
Some(expected),
- "a structure pattern".to_strbuf(),
+ "a structure pattern".to_string(),
None);
match tcx.def_map.borrow().find(&pat.id) {
Some(&ast::DefStruct(supplied_def_id)) => {
fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected,
actual| {
- expected.map_or("".to_strbuf(), |e| {
+ expected.map_or("".to_string(), |e| {
format_strbuf!("mismatched types: expected `{}` \
but found {}",
e,
}
)},
Some(expected),
- "tuple".to_strbuf(),
+ "tuple".to_string(),
Some(&type_error));
fcx.write_error(pat.id);
}
fcx.infcx().type_error_message_str_with_expected(
pat.span,
|expected, actual| {
- expected.map_or("".to_strbuf(),
+ expected.map_or("".to_string(),
|e| {
format_strbuf!("mismatched types: expected `{}` but \
found {}",
})
},
Some(expected),
- "a vector pattern".to_strbuf(),
+ "a vector pattern".to_string(),
None);
fcx.write_error(pat.id);
};
fcx.type_error_message(pat.span,
|_| {
"unique vector patterns are no \
- longer supported".to_strbuf()
+ longer supported".to_string()
},
expected,
None);
}
fcx.write_ty(pat.id, expected);
}
+
+ ast::PatMac(_) => tcx.sess.bug("unexpanded macro"),
}
}
fcx.infcx().type_error_message_str_with_expected(
span,
|expected, actual| {
- expected.map_or("".to_strbuf(), |e| {
+ expected.map_or("".to_string(), |e| {
format_strbuf!("mismatched types: expected `{}` but \
found {}",
e,
let error = if vst == ast::ExprVstoreSlice {
"`&\"string\"` has been removed; use `\"string\"` instead"
} else {
- "`~\"string\"` has been removed; use `\"string\".to_owned()` instead"
+ "`~\"string\"` has been removed; use `\"string\".to_string()` instead"
};
tcx.sess.span_err(expr.span, error);
ty::mk_err()
ppaux::ty_to_str(tcx, fcx.expr_ty(expr)),
match expected {
Some(t) => ppaux::ty_to_str(tcx, t),
- _ => "empty".to_strbuf()
+ _ => "empty".to_string()
});
unifier();
.add_lint(UnreachableCode,
s_id,
s.span,
- "unreachable statement".to_strbuf());
+ "unreachable statement".to_string());
warned = true;
}
if ty::type_is_bot(s_ty) {
.add_lint(UnreachableCode,
e.id,
e.span,
- "unreachable expression".to_strbuf());
+ "unreachable expression".to_string());
}
check_expr_with_opt_hint(fcx, e, expected);
let ety = fcx.expr_ty(e);
_ => {
fcx.type_error_message(sp, |_actual| {
"the type of this value must be known in this \
- context".to_strbuf()
+ context".to_string()
}, tp, None);
demand::suptype(fcx, sp, ty::mk_err(), tp);
tp
// choice of lifetime name deterministic and thus easier to test.
let mut names = Vec::new();
for rn in region_names.iter() {
- let lt_name = token::get_name(*rn).get().to_owned();
+ let lt_name = token::get_name(*rn).get().to_string();
names.push(lt_name);
}
names.sort();
fn report_inference_failure(&self,
var_origin: RegionVariableOrigin) {
let var_description = match var_origin {
- infer::MiscVariable(_) => "".to_strbuf(),
- infer::PatternRegion(_) => " for pattern".to_strbuf(),
- infer::AddrOfRegion(_) => " for borrow expression".to_strbuf(),
- infer::AddrOfSlice(_) => " for slice expression".to_strbuf(),
- infer::Autoref(_) => " for autoref".to_strbuf(),
- infer::Coercion(_) => " for automatic coercion".to_strbuf(),
+ infer::MiscVariable(_) => "".to_string(),
+ infer::PatternRegion(_) => " for pattern".to_string(),
+ infer::AddrOfRegion(_) => " for borrow expression".to_string(),
+ infer::AddrOfSlice(_) => " for slice expression".to_string(),
+ infer::Autoref(_) => " for autoref".to_string(),
+ infer::Coercion(_) => " for automatic coercion".to_string(),
infer::LateBoundRegion(_, br) => {
format!(" for {}in function call",
bound_region_to_str(self.tcx, "lifetime parameter ", true, br))
fn with_taken(taken: &[ast::Lifetime]) -> LifeGiver {
let mut taken_ = HashSet::new();
for lt in taken.iter() {
- let lt_name = token::get_name(lt.name).get().to_strbuf();
+ let lt_name = token::get_name(lt.name).get().to_string();
taken_.insert(lt_name);
}
LifeGiver {
impl<'f> Combine for Glb<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> String { "glb".to_strbuf() }
+ fn tag(&self) -> String { "glb".to_string() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
impl<'f> Combine for Lub<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> String { "lub".to_strbuf() }
+ fn tag(&self) -> String { "lub".to_string() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
pub fn fixup_err_to_str(f: fixup_err) -> String {
match f {
- unresolved_int_ty(_) => "unconstrained integral type".to_strbuf(),
- unresolved_ty(_) => "unconstrained type".to_strbuf(),
- cyclic_ty(_) => "cyclic type of infinite size".to_strbuf(),
- unresolved_region(_) => "unconstrained region".to_strbuf(),
+ unresolved_int_ty(_) => "unconstrained integral type".to_string(),
+ unresolved_ty(_) => "unconstrained type".to_string(),
+ cyclic_ty(_) => "cyclic type of infinite size".to_string(),
+ unresolved_region(_) => "unconstrained region".to_string(),
region_var_bound_by_region_var(r1, r2) => {
format_strbuf!("region var {:?} bound by another region var {:?}; \
this is a bug in rustc",
err: Option<&ty::type_err>) {
debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
- let error_str = err.map_or("".to_strbuf(), |t_err| {
+ let error_str = err.map_or("".to_string(), |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) -> String { "sub".to_strbuf() }
+ fn tag(&self) -> String { "sub".to_string() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
fn setup_env(test_name: &str, source_string: &str) -> Env {
let messages = @DVec();
- let matches = getopts(vec!("-Z".to_owned(), "verbose".to_owned()), optgroups()).get();
+ let matches = getopts(vec!("-Z".to_string(), "verbose".to_string()), optgroups()).get();
let diag = diagnostic::collect(messages);
- let sessopts = build_session_options("rustc".to_owned(), &matches, diag);
+ let sessopts = build_session_options("rustc".to_string(), &matches, diag);
let sess = build_session(sessopts, None, diag);
- let cfg = build_configuration(sess, "whatever".to_owned(), str_input("".to_owned()));
+ let cfg = build_configuration(sess, "whatever".to_string(), str_input("".to_string()));
let dm = HashMap();
let amap = HashMap();
let freevars = HashMap();
fn inf_str(&self, cx: &InferCtxt) -> String {
match *self {
Some(ref v) => v.inf_str(cx),
- None => "none".to_strbuf()
+ None => "none".to_string()
}
}
}
impl InferStr for IntVarValue {
fn inf_str(&self, _cx: &InferCtxt) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
impl InferStr for ast::FloatTy {
fn inf_str(&self, _cx: &InferCtxt) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
format_strbuf!("the anonymous lifetime \\#{} defined on",
idx + 1)
}
- BrFresh(_) => "an anonymous lifetime defined on".to_strbuf(),
+ BrFresh(_) => "an anonymous lifetime defined on".to_string(),
_ => {
format_strbuf!("the lifetime {} as defined on",
bound_region_ptr_to_str(cx, fr.bound_region))
}
}
- ReStatic => { ("the static lifetime".to_strbuf(), None) }
+ ReStatic => { ("the static lifetime".to_string(), None) }
- ReEmpty => { ("the empty lifetime".to_strbuf(), None) }
+ ReEmpty => { ("the empty lifetime".to_string(), None) }
// I believe these cases should not occur (except when debugging,
// perhaps)
token::get_name(name),
space_str)
}
- BrAnon(_) => prefix.to_strbuf(),
- BrFresh(_) => prefix.to_strbuf(),
+ BrAnon(_) => prefix.to_string(),
+ BrFresh(_) => prefix.to_string(),
}
}
// to fit that into a short string. Hence the recommendation to use
// `explain_region()` or `note_and_explain_region()`.
match region {
- ty::ReScope(_) => prefix.to_strbuf(),
+ ty::ReScope(_) => prefix.to_string(),
ty::ReEarlyBound(_, _, name) => {
- token::get_name(name).get().to_strbuf()
+ token::get_name(name).get().to_string()
}
ty::ReLateBound(_, br) => bound_region_to_str(cx, prefix, space, br),
ty::ReFree(ref fr) => bound_region_to_str(cx, prefix, space, fr.bound_region),
ty::ReInfer(ReSkolemized(_, br)) => {
bound_region_to_str(cx, prefix, space, br)
}
- ty::ReInfer(ReVar(_)) => prefix.to_strbuf(),
+ ty::ReInfer(ReVar(_)) => prefix.to_string(),
ty::ReStatic => format_strbuf!("{}'static{}", prefix, space_str),
ty::ReEmpty => format_strbuf!("{}'<empty>{}", prefix, space_str),
}
pub fn mutability_to_str(m: ast::Mutability) -> String {
match m {
- ast::MutMutable => "mut ".to_strbuf(),
- ast::MutImmutable => "".to_strbuf(),
+ ast::MutMutable => "mut ".to_string(),
+ ast::MutImmutable => "".to_string(),
}
}
pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> String {
match s {
- ty::UniqTraitStore => "Box ".to_strbuf(),
+ ty::UniqTraitStore => "Box ".to_string(),
ty::RegionTraitStore(r, m) => {
format_strbuf!("{}{}",
region_ptr_to_str(cx, r),
}
pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> String {
- trait_ref.user_string(cx).to_strbuf()
+ trait_ref.user_string(cx).to_string()
}
pub fn ty_to_str(cx: &ctxt, typ: t) -> String {
fn fn_input_to_str(cx: &ctxt, input: ty::t) -> String {
- ty_to_str(cx, input).to_strbuf()
+ ty_to_str(cx, input).to_string()
}
fn bare_fn_to_str(cx: &ctxt,
fn_style: ast::FnStyle,
// pretty print the structural type representation:
return match ty::get(typ).sty {
- ty_nil => "()".to_strbuf(),
- ty_bot => "!".to_strbuf(),
- ty_bool => "bool".to_strbuf(),
- ty_char => "char".to_strbuf(),
+ ty_nil => "()".to_string(),
+ ty_bot => "!".to_string(),
+ ty_bool => "bool".to_string(),
+ ty_char => "char".to_string(),
ty_int(t) => ast_util::int_ty_to_str(t, None,
- ast_util::AutoSuffix).to_strbuf(),
+ ast_util::AutoSuffix).to_string(),
ty_uint(t) => ast_util::uint_ty_to_str(t, None,
- ast_util::AutoSuffix).to_strbuf(),
- ty_float(t) => ast_util::float_ty_to_str(t).to_strbuf(),
+ ast_util::AutoSuffix).to_string(),
+ ty_float(t) => ast_util::float_ty_to_str(t).to_string(),
ty_box(typ) => format_strbuf!("@{}", ty_to_str(cx, typ)),
ty_uniq(typ) => format_strbuf!("~{}", ty_to_str(cx, typ)),
ty_ptr(ref tm) => format_strbuf!("*{}", mt_to_str(cx, tm)),
ty_bare_fn(ref f) => {
bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig)
}
- ty_infer(infer_ty) => infer_ty.to_str().to_strbuf(),
- ty_err => "[type error]".to_strbuf(),
+ ty_infer(infer_ty) => infer_ty.to_str().to_string(),
+ ty_err => "[type error]".to_string(),
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_strbuf(),
+ Some(def) => token::get_ident(def.ident).get().to_string(),
// This can only happen when a type mismatch error happens and
// the actual type has more type parameters than the expected one.
None => format_strbuf!("<generic \\#{}>", id)
format_strbuf!("{}:{:?}", ident, did)
}
}
- ty_self(..) => "Self".to_strbuf(),
+ ty_self(..) => "Self".to_string(),
ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
let base = ty::item_path_str(cx, did);
parameterized(cx,
bound_sep,
bound_str)
}
- ty_str => "str".to_strbuf(),
+ ty_str => "str".to_string(),
ty_vec(ref mt, sz) => {
match sz {
Some(n) => {
}
pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
- let mut s = typ.repr(cx).to_strbuf();
+ let mut s = typ.repr(cx).to_string();
if s.len() >= 32u {
- s = s.as_slice().slice(0u, 32u).to_strbuf();
+ s = s.as_slice().slice(0u, 32u).to_string();
}
return s;
}
impl<T:Repr> Repr for Option<T> {
fn repr(&self, tcx: &ctxt) -> String {
match self {
- &None => "None".to_strbuf(),
+ &None => "None".to_string(),
&Some(ref t) => t.repr(tcx),
}
}
impl Repr for () {
fn repr(&self, _tcx: &ctxt) -> String {
- "()".to_strbuf()
+ "()".to_string()
}
}
impl Repr for ty::RegionSubsts {
fn repr(&self, tcx: &ctxt) -> String {
match *self {
- ty::ErasedRegions => "erased".to_strbuf(),
+ ty::ErasedRegions => "erased".to_string(),
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".to_strbuf(),
- ty::BoundSend => "Send".to_strbuf(),
- ty::BoundSized => "Sized".to_strbuf(),
- ty::BoundCopy => "Copy".to_strbuf(),
- ty::BoundShare => "Share".to_strbuf(),
+ ty::BoundStatic => "'static".to_string(),
+ ty::BoundSend => "Send".to_string(),
+ ty::BoundSized => "Sized".to_string(),
+ ty::BoundCopy => "Copy".to_string(),
+ ty::BoundShare => "Share".to_string(),
});
}
for t in self.trait_bounds.iter() {
res.push(t.repr(tcx));
}
- res.connect("+").to_strbuf()
+ res.connect("+").to_string()
}
}
}
ty::ReStatic => {
- "ReStatic".to_strbuf()
+ "ReStatic".to_string()
}
ty::ReInfer(ReVar(ref vid)) => {
}
ty::ReEmpty => {
- "ReEmpty".to_strbuf()
+ "ReEmpty".to_string()
}
}
}
impl Repr for ty::Variance {
fn repr(&self, _: &ctxt) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
impl Repr for ast::Name {
fn repr(&self, _tcx: &ctxt) -> String {
- token::get_name(*self).get().to_strbuf()
+ token::get_name(*self).get().to_string()
}
}
impl Repr for ast::Ident {
fn repr(&self, _tcx: &ctxt) -> String {
- token::get_ident(*self).get().to_strbuf()
+ token::get_ident(*self).get().to_string()
}
}
impl UserString for ty::BuiltinBound {
fn user_string(&self, _tcx: &ctxt) -> String {
match *self {
- ty::BoundStatic => "'static".to_strbuf(),
- ty::BoundSend => "Send".to_strbuf(),
- ty::BoundSized => "Sized".to_strbuf(),
- ty::BoundCopy => "Copy".to_strbuf(),
- ty::BoundShare => "Share".to_strbuf(),
+ ty::BoundStatic => "'static".to_string(),
+ ty::BoundSend => "Send".to_string(),
+ ty::BoundSized => "Sized".to_string(),
+ ty::BoundCopy => "Copy".to_string(),
+ ty::BoundShare => "Share".to_string(),
}
}
}
impl Repr for Span {
fn repr(&self, tcx: &ctxt) -> String {
- tcx.sess.codemap().span_to_str(*self).to_strbuf()
+ tcx.sess.codemap().span_to_str(*self).to_string()
}
}
.map(|bb| bb.user_string(tcx))
.collect::<Vec<String>>()
.connect("+")
- .to_strbuf()
+ .to_string()
}
}
impl UserString for ast::Ident {
fn user_string(&self, _tcx: &ctxt) -> String {
- token::get_name(self.name).get().to_strbuf()
+ token::get_name(self.name).get().to_string()
}
}
impl Repr for abi::Abi {
fn repr(&self, _tcx: &ctxt) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
impl UserString for abi::Abi {
fn user_string(&self, _tcx: &ctxt) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
- self.result_bytes().as_slice().to_hex().to_strbuf()
+ self.result_bytes().as_slice().to_hex().to_string()
}
}
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
- input: "".to_strbuf(),
+ input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
- f4c8996fb92427ae41e4649b934ca495991b7852b855".to_strbuf()
+ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
- dog".to_strbuf(),
+ dog".to_string(),
output_str: "d7a8fbb307d7809469ca\
- 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_strbuf()
+ 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
- dog.".to_strbuf(),
+ dog.".to_string(),
output_str: "ef537f25c895bfa78252\
- 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_strbuf()
+ 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string()
});
let tests = wikipedia_tests;
_ => return None,
};
let fqn = csearch::get_item_path(tcx, did);
+ cx.inlined.borrow_mut().get_mut_ref().insert(did);
ret.push(clean::Item {
source: clean::Span::empty(),
- name: Some(fqn.last().unwrap().to_str().to_strbuf()),
+ name: Some(fqn.last().unwrap().to_str().to_string()),
attrs: load_attrs(tcx, did),
inner: inner,
visibility: Some(ast::Public),
match cx.maybe_typed {
core::Typed(ref tcx) => {
let fqn = csearch::get_item_path(tcx, did);
- let fqn = fqn.move_iter().map(|i| i.to_str().to_strbuf()).collect();
+ let fqn = fqn.move_iter().map(|i| i.to_str().to_string()).collect();
cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
}
core::NotTyped(..) => {}
let id = link::find_crate_id(self.attrs.as_slice(),
t_outputs.out_filestem.as_slice());
Crate {
- name: id.name.to_strbuf(),
+ name: id.name.to_string(),
module: Some(self.module.clean()),
externs: externs,
}
impl Clean<ExternalCrate> for cstore::crate_metadata {
fn clean(&self) -> ExternalCrate {
ExternalCrate {
- name: self.name.to_strbuf(),
+ name: self.name.to_string(),
attrs: decoder::get_crate_attributes(self.data()).clean()
.move_iter()
.collect(),
let name = if self.name.is_some() {
self.name.unwrap().clean()
} else {
- "".to_strbuf()
+ "".to_string()
};
let mut foreigns = Vec::new();
for subforeigns in self.foreigns.clean().move_iter() {
impl Clean<Attribute> for ast::MetaItem {
fn clean(&self) -> Attribute {
match self.node {
- ast::MetaWord(ref s) => Word(s.get().to_strbuf()),
+ ast::MetaWord(ref s) => Word(s.get().to_string()),
ast::MetaList(ref s, ref l) => {
- List(s.get().to_strbuf(), l.clean().move_iter().collect())
+ List(s.get().to_string(), l.clean().move_iter().collect())
}
ast::MetaNameValue(ref s, ref v) => {
- NameValue(s.get().to_strbuf(), lit_to_str(v))
+ NameValue(s.get().to_string(), lit_to_str(v))
}
}
}
Path {
global: false,
segments: vec![PathSegment {
- name: name.to_strbuf(),
+ name: name.to_string(),
lifetimes: Vec::new(),
types: Vec::new(),
}]
(tcx.lang_items.share_trait().unwrap(), external_path("Share")),
};
let fqn = csearch::get_item_path(tcx, did);
- let fqn = fqn.move_iter().map(|i| i.to_str().to_strbuf()).collect();
+ let fqn = fqn.move_iter().map(|i| i.to_str().to_string()).collect();
cx.external_paths.borrow_mut().get_mut_ref().insert(did,
(fqn, TypeTrait));
TraitBound(ResolvedPath {
core::NotTyped(_) => return RegionBound,
};
let fqn = csearch::get_item_path(tcx, self.def_id);
- let fqn = fqn.move_iter().map(|i| i.to_str().to_strbuf())
+ let fqn = fqn.move_iter().map(|i| i.to_str().to_string())
.collect::<Vec<String>>();
let path = external_path(fqn.last().unwrap().as_slice());
cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
impl Clean<Lifetime> for ast::Lifetime {
fn clean(&self) -> Lifetime {
- Lifetime(token::get_name(self.name).get().to_strbuf())
+ Lifetime(token::get_name(self.name).get().to_string())
}
}
impl Clean<Lifetime> for ty::RegionParameterDef {
fn clean(&self) -> Lifetime {
- Lifetime(token::get_name(self.name).get().to_strbuf())
+ Lifetime(token::get_name(self.name).get().to_string())
}
}
impl Clean<Option<Lifetime>> for ty::Region {
fn clean(&self) -> Option<Lifetime> {
match *self {
- ty::ReStatic => Some(Lifetime("static".to_strbuf())),
+ ty::ReStatic => Some(Lifetime("static".to_string())),
ty::ReLateBound(_, ty::BrNamed(_, name)) =>
- Some(Lifetime(token::get_name(name).get().to_strbuf())),
+ Some(Lifetime(token::get_name(name).get().to_string())),
ty::ReLateBound(..) |
ty::ReEarlyBound(..) |
Argument {
type_: t.clean(),
id: 0,
- name: names.next().unwrap_or("".to_strbuf()),
+ name: names.next().unwrap_or("".to_string()),
}
}).collect(),
},
lifetimes: Vec::new(), type_params: Vec::new()
},
decl: (ast_util::local_def(0), &fty.sig).clean(),
- abi: fty.abi.to_str().to_strbuf(),
+ abi: fty.abi.to_str(),
}),
ty::ty_closure(ref fty) => {
let decl = box ClosureDecl {
};
let fqn = csearch::get_item_path(tcx, did);
let fqn: Vec<String> = fqn.move_iter().map(|i| {
- i.to_str().to_strbuf()
+ i.to_str().to_string()
}).collect();
let mut path = external_path(fqn.last()
.unwrap()
impl Span {
fn empty() -> Span {
Span {
- filename: "".to_strbuf(),
+ filename: "".to_string(),
loline: 0, locol: 0,
hiline: 0, hicol: 0,
}
let lo = cm.lookup_char_pos(self.lo);
let hi = cm.lookup_char_pos(self.hi);
Span {
- filename: filename.to_strbuf(),
+ filename: filename.to_string(),
loline: lo.line,
locol: lo.col.to_uint(),
hiline: hi.line,
impl Clean<String> for ast::Ident {
fn clean(&self) -> String {
- token::get_ident(*self).get().to_strbuf()
+ token::get_ident(*self).get().to_string()
}
}
impl Clean<String> for ast::Name {
fn clean(&self) -> String {
- token::get_name(*self).get().to_strbuf()
+ token::get_name(*self).get().to_string()
}
}
type_params: Vec::new(),
},
decl: self.decl.clean(),
- abi: self.abi.to_str().to_strbuf(),
+ abi: self.abi.to_str().to_string(),
}
}
}
&ast::ViewItemExternCrate(ref i, ref p, ref id) => {
let string = match *p {
None => None,
- Some((ref x, _)) => Some(x.get().to_strbuf()),
+ Some((ref x, _)) => Some(x.get().to_string()),
};
ExternCrate(i.clean(), string, *id)
}
ForeignStaticItem(Static {
type_: ty.clean(),
mutability: if mutbl {Mutable} else {Immutable},
- expr: "".to_strbuf(),
+ expr: "".to_string(),
})
}
};
let ctxt = super::ctxtkey.get().unwrap();
let cm = ctxt.sess().codemap().clone();
let sn = match cm.span_to_snippet(*self) {
- Some(x) => x.to_strbuf(),
- None => "".to_strbuf()
+ Some(x) => x.to_string(),
+ None => "".to_string()
};
debug!("got snippet {}", sn);
sn
fn lit_to_str(lit: &ast::Lit) -> String {
match lit.node {
- ast::LitStr(ref st, _) => st.get().to_strbuf(),
+ ast::LitStr(ref st, _) => st.get().to_string(),
ast::LitBinary(ref data) => format_strbuf!("{:?}", data.as_slice()),
ast::LitChar(c) => format_strbuf!("'{}'", c),
- ast::LitInt(i, _t) => i.to_str().to_strbuf(),
- ast::LitUint(u, _t) => u.to_str().to_strbuf(),
- ast::LitIntUnsuffixed(i) => i.to_str().to_strbuf(),
- ast::LitFloat(ref f, _t) => f.get().to_strbuf(),
- ast::LitFloatUnsuffixed(ref f) => f.get().to_strbuf(),
- ast::LitBool(b) => b.to_str().to_strbuf(),
- ast::LitNil => "".to_strbuf(),
+ ast::LitInt(i, _t) => i.to_str().to_string(),
+ ast::LitUint(u, _t) => u.to_str().to_string(),
+ ast::LitIntUnsuffixed(i) => i.to_str().to_string(),
+ ast::LitFloat(ref f, _t) => f.get().to_string(),
+ ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
+ ast::LitBool(b) => b.to_str().to_string(),
+ ast::LitNil => "".to_string(),
}
}
debug!("Trying to get a name from pattern: {:?}", p);
match p.node {
- PatWild => "_".to_strbuf(),
- PatWildMulti => "..".to_strbuf(),
+ PatWild => "_".to_string(),
+ PatWildMulti => "..".to_string(),
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)".to_strbuf(),
+ PatTup(..) => "(tuple arg NYI)".to_string(),
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_strbuf()
+ "()".to_string()
},
PatRange(..) => fail!("tried to get argument name from PatRange, \
which is not allowed in function arguments"),
PatVec(..) => fail!("tried to get argument name from pat_vec, \
- which is not allowed in function arguments")
+ which is not allowed in function arguments"),
+ PatMac(..) => {
+ warn!("can't document the name of a function argument \
+ produced by a pattern macro");
+ "(argument produced by macro)".to_string()
+ }
}
}
pub external_paths: ExternalPaths,
pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
+ pub inlined: RefCell<Option<HashSet<ast::DefId>>>,
}
impl DocContext {
pub external_paths: ExternalPaths,
pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
+ pub inlined: RefCell<Option<HashSet<ast::DefId>>>,
}
/// Parses, resolves, and typechecks the given crate
external_traits: RefCell::new(Some(HashMap::new())),
external_typarams: RefCell::new(Some(HashMap::new())),
external_paths: RefCell::new(Some(HashMap::new())),
+ inlined: RefCell::new(Some(HashSet::new())),
}, CrateAnalysis {
exported_items: exported_items,
public_items: public_items,
external_paths: RefCell::new(None),
external_traits: RefCell::new(None),
external_typarams: RefCell::new(None),
+ inlined: RefCell::new(None),
})
}
*analysis.external_traits.borrow_mut() = map;
let map = ctxt.external_typarams.borrow_mut().take();
*analysis.external_typarams.borrow_mut() = map;
+ let map = ctxt.inlined.borrow_mut().take();
+ *analysis.inlined.borrow_mut() = map;
(krate, analysis)
}
print_all: bool) -> fmt::Result {
path(w, p, print_all,
|cache, loc| {
- if ast_util::is_local(did) || cache.paths.contains_key(&did) {
- Some(("../".repeat(loc.len())).to_strbuf())
+ if ast_util::is_local(did) || cache.inlined.contains(&did) {
+ Some(("../".repeat(loc.len())).to_string())
} else {
match *cache.extern_locations.get(&did.krate) {
- render::Remote(ref s) => Some(s.to_strbuf()),
+ render::Remote(ref s) => Some(s.to_string()),
render::Local => {
- Some(("../".repeat(loc.len())).to_strbuf())
+ Some(("../".repeat(loc.len())).to_string())
}
render::Unknown => None,
}
let cache = cache_key.get().unwrap();
let abs_root = root(&**cache, loc.as_slice());
let rel_root = match path.segments.get(0).name.as_slice() {
- "self" => Some("./".to_owned()),
+ "self" => Some("./".to_string()),
_ => None,
};
{arrow, select, yes{ -> {ret}} other{}}",
style = FnStyleSpace(decl.fn_style),
lifetimes = if decl.lifetimes.len() == 0 {
- "".to_strbuf()
+ "".to_string()
} else {
format!("<{:#}>", decl.lifetimes)
},
{arrow, select, yes{ -> {ret}} other{}}",
style = FnStyleSpace(decl.fn_style),
lifetimes = if decl.lifetimes.len() == 0 {
- "".to_strbuf()
+ "".to_string()
} else {
format_strbuf!("<{:#}>", decl.lifetimes)
},
args = decl.decl.inputs,
bounds = if decl.bounds.len() == 0 {
- "".to_strbuf()
+ "".to_string()
} else {
let mut m = decl.bounds
.iter()
- .map(|s| s.to_str().to_strbuf());
+ .map(|s| s.to_str().to_string());
format_strbuf!(
": {}",
m.collect::<Vec<String>>().connect(" + "))
write!(f, "{}{}fn{}{}",
FnStyleSpace(decl.fn_style),
match decl.abi.as_slice() {
- "" => " extern ".to_strbuf(),
- "\"Rust\"" => "".to_strbuf(),
+ "" => " extern ".to_string(),
+ "\"Rust\"" => "".to_string(),
s => format_strbuf!(" extern {} ", s)
},
decl.generics,
clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
let lt = match *l {
Some(ref l) => format!("{} ", *l),
- _ => "".to_strbuf(),
+ _ => "".to_string(),
};
write!(f, "&{}{}{}",
lt,
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
- src.to_strbuf(),
- "<stdin>".to_strbuf());
+ src.to_string(),
+ "<stdin>".to_string());
let mut out = io::MemWriter::new();
doit(&sess,
lexer::new_string_reader(&sess.span_diagnostic, fm),
class,
&mut out).unwrap();
- str::from_utf8_lossy(out.unwrap().as_slice()).to_strbuf()
+ str::from_utf8_lossy(out.unwrap().as_slice()).to_string()
}
/// Exhausts the `lexer` writing the output into `out`.
// Extract the text provided
let s = if text.is_null() {
- "".to_owned()
+ "".to_string()
} else {
unsafe {
str::raw::from_buf_len((*text).data, (*text).size as uint)
// Transform the contents of the header into a hyphenated string
let id = (s.as_slice().words().map(|s| {
match s.to_ascii_opt() {
- Some(s) => s.to_lower().into_str().to_strbuf(),
- None => s.to_strbuf()
+ Some(s) => s.to_lower().into_str().to_string(),
+ None => s.to_string()
}
- }).collect::<Vec<String>>().connect("-")).to_strbuf();
+ }).collect::<Vec<String>>().connect("-")).to_string();
// This is a terrible hack working around how hoedown gives us rendered
// html for text rather than the raw text.
- let id = id.replace("<code>", "").replace("</code>", "").to_strbuf();
+ let id = id.replace("<code>", "").replace("</code>", "").to_string();
let opaque = opaque as *mut hoedown_html_renderer_state;
let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
let sec = match opaque.toc_builder {
Some(ref mut builder) => {
- builder.push(level as u32, s.to_strbuf(), id.clone())
+ builder.push(level as u32, s.to_string(), id.clone())
}
None => {""}
};
stripped_filtered_line(l).unwrap_or(l)
});
let text = lines.collect::<Vec<&str>>().connect("\n");
- tests.add_test(text.to_strbuf(), should_fail, no_run, ignore);
+ tests.add_test(text.to_string(), should_fail, no_run, ignore);
})
}
}
/// Cache of where external crate documentation can be found.
pub extern_locations: HashMap<ast::CrateNum, ExternalLocation>,
+ /// Set of definitions which have been inlined from external crates.
+ pub inlined: HashSet<ast::DefId>,
+
// Private fields only used when initially crawling a crate to build a cache
stack: Vec<String>,
root_path: String::new(),
sidebar: HashMap::new(),
layout: layout::Layout {
- logo: "".to_strbuf(),
- favicon: "".to_strbuf(),
+ logo: "".to_string(),
+ favicon: "".to_string(),
krate: krate.name.clone(),
},
include_sources: true,
match *attr {
clean::NameValue(ref x, ref s)
if "html_favicon_url" == x.as_slice() => {
- cx.layout.favicon = s.to_strbuf();
+ cx.layout.favicon = s.to_string();
}
clean::NameValue(ref x, ref s)
if "html_logo_url" == x.as_slice() => {
- cx.layout.logo = s.to_strbuf();
+ cx.layout.logo = s.to_string();
}
clean::Word(ref x)
if "html_no_source" == x.as_slice() => {
typarams: analysis.as_ref().map(|a| {
a.external_typarams.borrow_mut().take_unwrap()
}).unwrap_or(HashMap::new()),
+ inlined: analysis.as_ref().map(|a| {
+ a.inlined.borrow_mut().take_unwrap()
+ }).unwrap_or(HashSet::new()),
};
cache.stack.push(krate.name.clone());
krate = cache.fold_crate(krate);
ty: shortty(item),
name: item.name.clone().unwrap(),
path: fqp.slice_to(fqp.len() - 1).connect("::")
- .to_strbuf(),
- desc: shorter(item.doc_value()).to_strbuf(),
+ .to_string(),
+ desc: shorter(item.doc_value()).to_string(),
parent: Some(did),
});
},
let mut w = MemWriter::new();
try!(write!(&mut w, r#"searchIndex['{}'] = \{"items":["#, krate.name));
- let mut lastpath = "".to_strbuf();
+ let mut lastpath = "".to_string();
for (i, item) in cache.search_index.iter().enumerate() {
// Omit the path if it is same to that of the prior item.
let path;
if lastpath.as_slice() == item.path.as_slice() {
path = "";
} else {
- lastpath = item.path.to_strbuf();
+ lastpath = item.path.to_string();
path = item.path.as_slice();
};
try!(write!(&mut w, r"]\};"));
- str::from_utf8(w.unwrap().as_slice()).unwrap().to_owned()
+ str::from_utf8(w.unwrap().as_slice()).unwrap().to_string()
};
// Write out the shared files. Note that these are shared among all rustdoc
format!("{}['{}']", key, krate).as_slice()) {
continue
}
- ret.push(line.to_strbuf());
+ ret.push(line.to_string());
}
}
return Ok(ret);
cx: &mut cx,
};
// skip all invalid spans
- folder.seen.insert("".to_strbuf());
+ folder.seen.insert("".to_string());
krate = folder.fold_crate(krate);
}
for &(n, ref e) in krate.externs.iter() {
cache.extern_locations.insert(n, extern_location(e, &cx.dst));
let did = ast::DefId { krate: n, node: ast::CRATE_NODE_ID };
- cache.paths.insert(did, (vec![e.name.to_strbuf()], item_type::Module));
+ cache.paths.insert(did, (vec![e.name.to_string()], item_type::Module));
}
// And finally render the whole crate's documentation
clean::NameValue(ref x, ref s)
if "html_root_url" == x.as_slice() => {
if s.as_slice().ends_with("/") {
- return Remote(s.to_strbuf());
+ return Remote(s.to_string());
}
return Remote(format_strbuf!("{}/", s));
}
(parent, Some(path)) if !self.privmod => {
self.search_index.push(IndexItem {
ty: shortty(&item),
- name: s.to_strbuf(),
- path: path.connect("::").to_strbuf(),
- desc: shorter(item.doc_value()).to_strbuf(),
+ name: s.to_string(),
+ path: path.connect("::").to_string(),
+ desc: shorter(item.doc_value()).to_string(),
parent: parent,
});
}
let pushed = if item.name.is_some() {
let n = item.name.get_ref();
if n.len() > 0 {
- self.stack.push(n.to_strbuf());
+ self.stack.push(n.to_string());
true
} else { false }
} else { false };
// modules are special because they add a namespace. We also need to
// recurse into the items of the module as well.
clean::ModuleItem(..) => {
- let name = item.name.get_ref().to_strbuf();
+ let name = item.name.get_ref().to_string();
let mut item = Some(item);
self.recurse(name, |this| {
let item = item.take_unwrap();
if ast_util::is_local(self.item.def_id) {
let mut path = Vec::new();
clean_srcpath(self.item.source.filename.as_bytes(), |component| {
- path.push(component.to_owned());
+ path.push(component.to_string());
});
let href = if self.item.source.loline == self.item.source.hiline {
format!("{}", self.item.source.loline)
let cache = cache_key.get().unwrap();
let path = cache.external_paths.get(&self.item.def_id);
let root = match *cache.extern_locations.get(&self.item.def_id.krate) {
- Remote(ref s) => s.to_strbuf(),
- Local => format!("{}/..", self.cx.root_path),
+ Remote(ref s) => s.to_string(),
+ Local => self.cx.root_path.clone(),
Unknown => return None,
};
- Some(format!("{root}/{path}/{file}?gotosrc={goto}",
+ Some(format!("{root}{path}/{file}?gotosrc={goto}",
root = root,
path = path.slice_to(path.len() - 1).connect("/"),
file = item_path(self.item),
let short = shortty(item).to_static_str();
let myname = match item.name {
None => continue,
- Some(ref s) => s.to_strbuf(),
+ Some(ref s) => s.to_string(),
};
- let v = map.find_or_insert_with(short.to_strbuf(), |_| Vec::new());
+ let v = map.find_or_insert_with(short.to_string(), |_| Vec::new());
v.push(myname);
}
macro_rules! push {
($level: expr, $name: expr) => {
assert_eq!(builder.push($level,
- $name.to_strbuf(),
- "".to_strbuf()),
+ $name.to_string(),
+ "".to_string()),
$name);
}
}
$(
TocEntry {
level: $level,
- name: $name.to_strbuf(),
- sec_number: $name.to_strbuf(),
- id: "".to_strbuf(),
+ name: $name.to_string(),
+ sec_number: $name.to_string(),
+ id: "".to_string(),
children: toc!($($sub),*)
}
),*
#![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
-extern crate syntax;
+extern crate collections;
+extern crate debug;
+extern crate getopts;
+extern crate libc;
+#[phase(syntax, link)]
+extern crate log;
extern crate rustc;
extern crate serialize;
extern crate sync;
-extern crate getopts;
-extern crate collections;
+extern crate syntax;
extern crate testing = "test";
extern crate time;
-#[phase(syntax, link)]
-extern crate log;
-extern crate libc;
use std::io;
use std::io::{File, MemWriter};
pub fn main() {
std::os::set_exit_status(main_args(std::os::args().iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice()));
}
let test_args = matches.opt_strs("test-args");
let test_args: Vec<String> = test_args.iter()
.flat_map(|s| s.as_slice().words())
- .map(|s| s.to_strbuf())
+ .map(|s| s.to_string())
.collect();
let should_test = matches.opt_present("test");
(true, false) => {
return test::run(input,
cfgs.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect(),
libs,
test_args)
(false, false) => {}
}
- if matches.opt_strs("passes").as_slice() == &["list".to_strbuf()] {
+ if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
println!("Available passes for running rustdoc:");
for &(name, _, description) in PASSES.iter() {
println!("{:>20s} - {}", name, description);
let mut passes = matches.opt_strs("passes");
let mut plugins = matches.opt_strs("plugins")
.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>();
// First, parse the crate and extract all relevant information.
let (krate, analysis) = std::task::try(proc() {
let cr = cr;
core::run_core(libs.move_iter().map(|x| x.clone()).collect(),
- cfgs.move_iter().map(|x| x.to_strbuf()).collect(),
+ cfgs.move_iter().map(|x| x.to_string()).collect(),
&cr)
}).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
info!("finished with rustc");
clean::NameValue(ref x, ref value)
if "passes" == x.as_slice() => {
for pass in value.as_slice().words() {
- passes.push(pass.to_strbuf());
+ passes.push(pass.to_string());
}
}
clean::NameValue(ref x, ref value)
if "plugins" == x.as_slice() => {
for p in value.as_slice().words() {
- plugins.push(p.to_strbuf());
+ plugins.push(p.to_string());
}
}
_ => {}
}
if default_passes {
for name in DEFAULT_PASSES.iter().rev() {
- passes.unshift(name.to_strbuf());
+ passes.unshift(name.to_string());
}
}
// Load all plugins/passes into a PluginManager
let path = matches.opt_str("plugin-path")
- .unwrap_or("/tmp/rustdoc/plugins".to_strbuf());
+ .unwrap_or("/tmp/rustdoc/plugins".to_string());
let mut pm = plugins::PluginManager::new(Path::new(path));
for pass in passes.iter() {
let plugin = match PASSES.iter()
}
};
match json::from_reader(&mut input) {
- Err(s) => Err(s.to_str().to_strbuf()),
+ Err(s) => Err(s.to_str().to_string()),
Ok(json::Object(obj)) => {
let mut obj = obj;
// Make sure the schema is what we expect
- match obj.pop(&"schema".to_strbuf()) {
+ match obj.pop(&"schema".to_string()) {
Some(json::String(version)) => {
if version.as_slice() != SCHEMA_VERSION {
return Err(format_strbuf!(
SCHEMA_VERSION))
}
}
- Some(..) => return Err("malformed json".to_strbuf()),
- None => return Err("expected a schema version".to_strbuf()),
+ Some(..) => return Err("malformed json".to_string()),
+ None => return Err("expected a schema version".to_string()),
}
- let krate = match obj.pop(&"crate".to_strbuf()) {
+ let krate = match obj.pop(&"crate".to_string()) {
Some(json) => {
let mut d = json::Decoder::new(json);
Decodable::decode(&mut d).unwrap()
}
- None => return Err("malformed json".to_strbuf()),
+ None => return Err("malformed json".to_string()),
};
// FIXME: this should read from the "plugins" field, but currently
// Json doesn't implement decodable...
}
Ok(..) => {
Err("malformed json input: expected an object at the \
- top".to_strbuf())
+ top".to_string())
}
}
}
// "plugins": { output of plugins ... }
// }
let mut json = box collections::TreeMap::new();
- json.insert("schema".to_strbuf(),
- json::String(SCHEMA_VERSION.to_strbuf()));
+ json.insert("schema".to_string(),
+ json::String(SCHEMA_VERSION.to_string()));
let plugins_json = box res.move_iter()
.filter_map(|opt| {
match opt {
None => None,
Some((string, json)) => {
- Some((string.to_strbuf(), json))
+ Some((string.to_string(), json))
}
}
}).collect();
let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
krate.encode(&mut encoder).unwrap();
}
- str::from_utf8(w.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(w.unwrap().as_slice()).unwrap().to_string()
};
let crate_json = match json::from_str(crate_json_str.as_slice()) {
Ok(j) => j,
Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
};
- json.insert("crate".to_strbuf(), crate_json);
- json.insert("plugins".to_strbuf(), json::Object(plugins_json));
+ json.insert("crate".to_string(), crate_json);
+ json.insert("plugins".to_string(), json::Object(plugins_json));
let mut file = try!(File::create(&dst));
try!(json::Object(json).to_writer(&mut file));
fn load_string(input: &Path) -> io::IoResult<Option<String>> {
let mut f = try!(io::File::open(input));
let d = try!(f.read_to_end());
- Ok(str::from_utf8(d.as_slice()).map(|s| s.to_strbuf()))
+ Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string()))
}
macro_rules! load_or_return {
($input: expr, $cant_read: expr, $not_utf8: expr) => {
let (in_header, before_content, after_content) =
match (load_external_files(matches.opt_strs("markdown-in-header")
.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice()),
load_external_files(matches.opt_strs("markdown-before-content")
.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice()),
load_external_files(matches.opt_strs("markdown-after-content")
.move_iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice())) {
(Some(a), Some(b), Some(c)) => (a,b,c),
pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<String>) -> int {
let input_str = load_or_return!(input, 1, 2);
- let mut collector = Collector::new(input.to_strbuf(), libs, true, true);
+ let mut collector = Collector::new(input.to_string(), libs, true, true);
find_testable_code(input_str.as_slice(), &mut collector);
- test_args.unshift("rustdoctest".to_strbuf());
+ test_args.unshift("rustdoctest".to_string());
testing::test_main(test_args.as_slice(), collector.tests);
0
}
match attr {
&clean::NameValue(ref x, ref s)
if "doc" == x.as_slice() => {
- avec.push(clean::NameValue("doc".to_strbuf(),
+ avec.push(clean::NameValue("doc".to_string(),
unindent(s.as_slice())))
}
x => avec.push(x.clone())
_ => true
}).map(|x| x.clone()).collect();
if docstr.len() > 0 {
- a.push(clean::NameValue("doc".to_strbuf(), docstr));
+ a.push(clean::NameValue("doc".to_string(), docstr));
}
i.attrs = a;
self.fold_item_recur(i)
});
if lines.len() >= 1 {
- let mut unindented = vec![ lines.get(0).trim().to_strbuf() ];
+ let mut unindented = vec![ lines.get(0).trim().to_string() ];
unindented.push_all(lines.tail().iter().map(|&line| {
if line.is_whitespace() {
- line.to_strbuf()
+ line.to_string()
} else {
assert!(line.len() >= min_indent);
- line.slice_from(min_indent).to_strbuf()
+ line.slice_from(min_indent).to_string()
}
}).collect::<Vec<_>>().as_slice());
- unindented.connect("\n").to_strbuf()
+ unindented.connect("\n").to_string()
} else {
- s.to_strbuf()
+ s.to_string()
}
}
#[test]
fn should_unindent() {
- let s = " line1\n line2".to_owned();
+ let s = " line1\n line2".to_string();
let r = unindent(s.as_slice());
assert_eq!(r.as_slice(), "line1\nline2");
}
#[test]
fn should_unindent_multiple_paragraphs() {
- let s = " line1\n\n line2".to_owned();
+ let s = " line1\n\n line2".to_string();
let r = unindent(s.as_slice());
assert_eq!(r.as_slice(), "line1\n\nline2");
}
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".to_owned();
+ let s = " line1\n\n line2".to_string();
let r = unindent(s.as_slice());
assert_eq!(r.as_slice(), "line1\n\n line2");
}
//
// #[doc = "Start way over here
// and continue here"]
- let s = "line1\n line2".to_owned();
+ let s = "line1\n line2".to_string();
let r = unindent(s.as_slice());
assert_eq!(r.as_slice(), "line1\nline2");
}
#[test]
fn should_not_ignore_first_line_indent_in_a_single_line_para() {
- let s = "line1\n\n line2".to_owned();
+ let s = "line1\n\n line2".to_string();
let r = unindent(s.as_slice());
assert_eq!(r.as_slice(), "line1\n\n line2");
}
external_paths: RefCell::new(Some(HashMap::new())),
external_traits: RefCell::new(None),
external_typarams: RefCell::new(None),
+ inlined: RefCell::new(None),
};
super::ctxtkey.replace(Some(ctx));
let (krate, _) = passes::unindent_comments(krate);
let (krate, _) = passes::collapse_docs(krate);
- let mut collector = Collector::new(krate.name.to_strbuf(),
+ let mut collector = Collector::new(krate.name.to_string(),
libs,
false,
false);
collector.fold_crate(krate);
- test_args.unshift("rustdoctest".to_strbuf());
+ test_args.unshift("rustdoctest".to_string());
testing::test_main(test_args.as_slice(),
collector.tests.move_iter().collect());
fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
no_run: bool, loose_feature_gating: bool) {
let test = maketest(test, cratename, loose_feature_gating);
- let input = driver::StrInput(test.to_strbuf());
+ let input = driver::StrInput(test.to_string());
let sessopts = config::Options {
maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
// Add the new dylib search path var
let newpath = DynamicLibrary::create_path(path.as_slice());
- env.push((var.to_owned(),
- str::from_utf8(newpath.as_slice()).unwrap().to_owned()));
+ env.push((var.to_string(),
+ str::from_utf8(newpath.as_slice()).unwrap().to_string()));
env
};
match Command::new(exe).env(env.as_slice()).output() {
};
self.cnt += 1;
let libs = self.libs.clone();
- let cratename = self.cratename.to_owned();
+ let cratename = self.cratename.to_string();
let loose_feature_gating = self.loose_feature_gating;
debug!("Creating test {}: {}", name, test);
self.tests.push(testing::TestDescAndFn {
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
let pushed = match item.name {
Some(ref name) if name.len() == 0 => false,
- Some(ref name) => { self.names.push(name.to_strbuf()); true }
+ Some(ref name) => { self.names.push(name.to_string()); true }
None => false
};
match item.doc_value() {
#![allow(visible_private_types)]
#[cfg(test)] extern crate green;
+#[cfg(test)] extern crate debug;
#[cfg(test)] extern crate realrustuv = "rustuv";
extern crate libc;
extern crate alloc;
let inner = match self { &UvError(a) => a };
let name_str = uvll::uv_err_name(inner);
assert!(name_str.is_not_null());
- from_c_str(name_str).to_strbuf()
+ from_c_str(name_str).to_string()
}
}
let inner = match self { &UvError(a) => a };
let desc_str = uvll::uv_strerror(inner);
assert!(desc_str.is_not_null());
- from_c_str(desc_str).to_strbuf()
+ from_c_str(desc_str).to_string()
}
}
#[test]
fn error_smoke_test() {
let err: UvError = UvError(uvll::EOF);
- assert_eq!(err.to_str(), "EOF: end of file".to_strbuf());
+ assert_eq!(err.to_str(), "EOF: end of file".to_string());
}
pub fn uv_error_to_io_error(uverr: UvError) -> IoError {
let storage: &libc::sockaddr_in = unsafe {
mem::transmute(storage)
};
- let addr = storage.sin_addr.s_addr as u32;
- let a = (addr >> 0) as u8;
- let b = (addr >> 8) as u8;
- let c = (addr >> 16) as u8;
- let d = (addr >> 24) as u8;
+ let ip = mem::to_be32(storage.sin_addr.s_addr as u32);
+ let a = (ip >> 24) as u8;
+ let b = (ip >> 16) as u8;
+ let c = (ip >> 8) as u8;
+ let d = (ip >> 0) as u8;
ip::SocketAddr {
ip: ip::Ipv4Addr(a, b, c, d),
port: ntohs(storage.sin_port),
let mut storage: libc::sockaddr_storage = mem::zeroed();
let len = match addr.ip {
ip::Ipv4Addr(a, b, c, d) => {
+ let ip = (a as u32 << 24) |
+ (b as u32 << 16) |
+ (c as u32 << 8) |
+ (d as u32 << 0);
let storage: &mut libc::sockaddr_in =
mem::transmute(&mut storage);
(*storage).sin_family = libc::AF_INET as libc::sa_family_t;
(*storage).sin_port = htons(addr.port);
(*storage).sin_addr = libc::in_addr {
- s_addr: (d as u32 << 24) |
- (c as u32 << 16) |
- (b as u32 << 8) |
- (a as u32 << 0)
+ s_addr: mem::from_be32(ip)
};
mem::size_of::<libc::sockaddr_in>()
}
fn connect_close_ip4() {
match TcpWatcher::connect(local_loop(), next_test_ip4(), None) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_strbuf()),
+ Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_string()),
}
}
fn connect_close_ip6() {
match TcpWatcher::connect(local_loop(), next_test_ip6(), None) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_strbuf()),
+ Err(e) => assert_eq!(e.name(), "ECONNREFUSED".to_string()),
}
}
fn bind_err() {
match PipeListener::bind(local_loop(), &"path/to/nowhere".to_c_str()) {
Ok(..) => fail!(),
- Err(e) => assert_eq!(e.name(), "EACCES".to_strbuf()),
+ Err(e) => assert_eq!(e.name(), "EACCES".to_string()),
}
}
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric("alpha1".to_strbuf())),
+ pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(),
}));
assert!(parse(" 1.2.3-alpha1 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric("alpha1".to_strbuf())),
+ pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!()
}));
assert!(parse("1.2.3+build5") == Some(Version {
minor: 2u,
patch: 3u,
pre: vec!(),
- build: vec!(AlphaNumeric("build5".to_strbuf()))
+ build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse(" 1.2.3+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
- build: vec!(AlphaNumeric("build5".to_strbuf()))
+ build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse("1.2.3-alpha1+build5") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric("alpha1".to_strbuf())),
- build: vec!(AlphaNumeric("build5".to_strbuf()))
+ pre: vec!(AlphaNumeric("alpha1".to_string())),
+ build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse(" 1.2.3-alpha1+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
- pre: vec!(AlphaNumeric("alpha1".to_strbuf())),
- build: vec!(AlphaNumeric("build5".to_strbuf()))
+ pre: vec!(AlphaNumeric("alpha1".to_string())),
+ build: vec!(AlphaNumeric("build5".to_string()))
}));
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".to_strbuf()),Numeric(9)),
- build: vec!(AlphaNumeric("build5".to_strbuf()),
+ pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_string()),Numeric(9)),
+ build: vec!(AlphaNumeric("build5".to_string()),
Numeric(7),
- AlphaNumeric("3aedf".to_strbuf()))
+ AlphaNumeric("3aedf".to_string()))
}));
}
#[test]
fn test_show() {
assert_eq!(format_strbuf!("{}", parse("1.2.3").unwrap()),
- "1.2.3".to_strbuf());
+ "1.2.3".to_string());
assert_eq!(format_strbuf!("{}", parse("1.2.3-alpha1").unwrap()),
- "1.2.3-alpha1".to_strbuf());
+ "1.2.3-alpha1".to_string());
assert_eq!(format_strbuf!("{}", parse("1.2.3+build.42").unwrap()),
- "1.2.3+build.42".to_strbuf());
+ "1.2.3+build.42".to_string());
assert_eq!(format_strbuf!("{}", parse("1.2.3-alpha1+42").unwrap()),
- "1.2.3-alpha1+42".to_strbuf());
+ "1.2.3-alpha1+42".to_string());
}
#[test]
fn test_to_str() {
- 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());
+ assert_eq!(parse("1.2.3").unwrap().to_str(), "1.2.3".to_string());
+ assert_eq!(parse("1.2.3-alpha1").unwrap().to_str(), "1.2.3-alpha1".to_string());
+ assert_eq!(parse("1.2.3+build.42").unwrap().to_str(), "1.2.3+build.42".to_string());
+ assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_str(), "1.2.3-alpha1+42".to_string());
}
#[test]
}
unsafe {
- str::raw::from_utf8(v.as_slice()).to_strbuf()
+ str::raw::from_utf8(v.as_slice()).to_string()
}
}
}
#[test]
fn test_to_base64_basic() {
- assert_eq!("".as_bytes().to_base64(STANDARD), "".to_strbuf());
- assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_strbuf());
- assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_strbuf());
- assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_strbuf());
- assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_strbuf());
- assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_strbuf());
- assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_strbuf());
+ assert_eq!("".as_bytes().to_base64(STANDARD), "".to_string());
+ assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_string());
+ assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_string());
+ assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_string());
+ assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_string());
+ assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_string());
+ assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_string());
}
#[test]
.contains("\r\n"));
assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
..STANDARD}),
- "Zm9v\r\nYmFy".to_strbuf());
+ "Zm9v\r\nYmFy".to_string());
}
#[test]
fn test_to_base64_padding() {
- assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_strbuf());
- assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_strbuf());
+ assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_string());
+ assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_string());
}
#[test]
fn test_to_base64_url_safe() {
- assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf());
- assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf());
+ assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_string());
+ assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_string());
}
#[test]
}
pub fn as_str(&self) -> String {
- self.as_str_slice().to_strbuf()
+ self.as_str_slice().to_string()
}
}
pub doc: Doc<'a>,
}
+#[deriving(Show)]
pub enum EbmlEncoderTag {
EsUint, // 0
EsU64, // 1
}
fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
- debug!(". next_doc(exp_tag={:?})", exp_tag);
+ debug!(". next_doc(exp_tag={})", exp_tag);
if self.pos >= self.parent.end {
return Err(Expected(format_strbuf!("no more documents in \
current node!")));
r_doc.end);
if r_tag != (exp_tag as uint) {
return Err(Expected(format_strbuf!("expected EBML doc with \
- tag {:?} but found tag \
- {:?}",
+ tag {} but found tag \
+ {}",
exp_tag,
r_tag)));
}
fn _next_uint(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<uint> {
let r = doc_as_u32(try!(self.next_doc(exp_tag)));
- debug!("_next_uint exp_tag={:?} result={}", exp_tag, r);
+ debug!("_next_uint exp_tag={} result={}", exp_tag, r);
Ok(r as uint)
}
#[test]
fn test_option_int() {
fn test_v(v: Option<int>) {
- debug!("v == {:?}", v);
+ debug!("v == {}", v);
let mut wr = MemWriter::new();
{
let mut ebml_w = writer::Encoder(&mut wr);
let ebml_doc = reader::Doc(wr.get_ref());
let mut deser = reader::Decoder(ebml_doc);
let v1 = Decodable::decode(&mut deser).unwrap();
- debug!("v1 == {:?}", v1);
+ debug!("v1 == {}", v1);
assert_eq!(v, v1);
}
}
unsafe {
- str::raw::from_utf8(v.as_slice()).to_strbuf()
+ str::raw::from_utf8(v.as_slice()).to_string()
}
}
}
* let hello_str = "Hello, World".as_bytes().to_hex();
* println!("{}", hello_str);
* let bytes = hello_str.as_slice().from_hex().unwrap();
- * println!("{:?}", bytes);
+ * println!("{}", bytes);
* let result_str = String::from_utf8(bytes).unwrap();
* println!("{}", result_str);
* }
#[test]
pub fn test_to_hex() {
- assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172".to_strbuf());
+ assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172".to_string());
}
#[test]
}
fn main() {
- let to_encode_object = TestStruct{data_str:"example of string to encode".to_strbuf()};
+ let to_encode_object = TestStruct{data_str:"example of string to encode".to_string()};
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".to_strbuf();
+let to_encode_object = "example of string to encode".to_string();
let encoded_str: String = json::Encoder::str_encode(&to_encode_object);
```
impl ToJson for MyStruct {
fn to_json( &self ) -> json::Json {
let mut d = box TreeMap::new();
- d.insert("attr1".to_strbuf(), self.attr1.to_json());
- d.insert("attr2".to_strbuf(), self.attr2.to_json());
+ d.insert("attr1".to_string(), self.attr1.to_json());
+ d.insert("attr2".to_string(), self.attr2.to_json());
json::Object(d)
}
}
fn main() {
- let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_strbuf()};
+ let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_string()};
let tjson: json::Json = test2.to_json();
- let json_str: String = tjson.to_str().into_strbuf();
+ let json_str: String = tjson.to_str().into_string();
}
```
fn main() {
let json_str_to_decode: String =
- "{\"attr1\":1,\"attr2\":\"toto\"}".to_strbuf();
+ "{\"attr1\":1,\"attr2\":\"toto\"}".to_string();
let json_object = json::from_str(json_str_to_decode.as_slice());
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".to_strbuf(), data_vector:vec![2,3,4,5]};
+ {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]};
let encoded_str: String = 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 = box TreeMap::new();
- d.insert("data_int".to_strbuf(), self.data_int.to_json());
- d.insert("data_str".to_strbuf(), self.data_str.to_json());
- d.insert("data_vector".to_strbuf(), self.data_vector.to_json());
+ d.insert("data_int".to_string(), self.data_int.to_json());
+ d.insert("data_str".to_string(), self.data_str.to_json());
+ d.insert("data_vector".to_string(), 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".to_strbuf(),
+ let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_string(),
data_vector:vec![2,3,4,5]};
let tjson: json::Json = test2.to_json();
- let json_str: String = tjson.to_str().into_strbuf();
+ let json_str: String = tjson.to_str().into_string();
// Deserialize like before.
to_encode_object: &T)
-> String {
let buff = Encoder::buffer_encode(to_encode_object);
- str::from_utf8(buff.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(buff.as_slice()).unwrap().to_string()
}
}
pub fn to_pretty_str(&self) -> String {
let mut s = MemWriter::new();
self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
- str::from_utf8(s.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(s.unwrap().as_slice()).unwrap().to_string()
}
/// If the Json value is an Object, returns the value associated with the provided key.
},
},
_ => return self.error(InvalidEscape),
-/*=======
- 'u' => {
- // Parse \u1234.
- let mut i = 0u;
- let mut n = 0u;
- while i < 4u && !self.eof() {
- self.bump();
- n = match self.ch_or_null() {
- c @ '0' .. '9' => n * 16u + (c as uint) - ('0' as uint),
- 'a' | 'A' => n * 16u + 10u,
- 'b' | 'B' => n * 16u + 11u,
- 'c' | 'C' => n * 16u + 12u,
- 'd' | 'D' => n * 16u + 13u,
- 'e' | 'E' => n * 16u + 14u,
- 'f' | 'F' => n * 16u + 15u,
- _ => return self.error(UnrecognizedHex)
- };
-
- i += 1u;
- }
-
- // Error out if we didn't parse 4 digits.
- if i != 4u {
- return self.error(NotFourDigit);
- }
-
- res.push_char(char::from_u32(n as u32).unwrap());
- }
- _ => return self.error(InvalidEscape),
->>>>>>> Add a streaming parser to serialize::json.*/
}
escape = false;
} else if self.ch_is('\\') {
_ => {}
}
let key = match self.parser.stack().top() {
- Some(Key(k)) => { k.to_strbuf() }
+ Some(Key(k)) => { k.to_string() }
_ => { fail!("invalid state"); }
};
match self.build_value() {
Err(e) => return Err(io_error_to_error(e))
};
let s = match str::from_utf8(contents.as_slice()) {
- Some(s) => s.to_strbuf(),
+ Some(s) => s.to_string(),
None => return Err(SyntaxError(NotUtf8, 0, 0))
};
let mut builder = Builder::new(s.as_slice().chars());
($e:expr, Null) => ({
match $e {
Null => Ok(()),
- other => Err(ExpectedError("Null".to_strbuf(),
+ other => Err(ExpectedError("Null".to_string(),
format_strbuf!("{}", other)))
}
});
match $e {
$t(v) => Ok(v),
other => {
- Err(ExpectedError(stringify!($t).to_strbuf(),
+ Err(ExpectedError(stringify!($t).to_string(),
format_strbuf!("{}", other)))
}
}
Ok(FromStr::from_str(s.as_slice()).unwrap())
},
value => {
- Err(ExpectedError("Number".to_strbuf(),
+ Err(ExpectedError("Number".to_string(),
format_strbuf!("{}", value)))
}
}
_ => ()
}
}
- Err(ExpectedError("single character string".to_strbuf(),
+ Err(ExpectedError("single character string".to_string(),
format_strbuf!("{}", s)))
}
names: &[&str],
f: |&mut Decoder, uint| -> DecodeResult<T>)
-> DecodeResult<T> {
- debug!("read_enum_variant(names={:?})", names);
+ debug!("read_enum_variant(names={})", names);
let name = match self.pop() {
String(s) => s,
Object(mut o) => {
- let n = match o.pop(&"variant".to_strbuf()) {
+ let n = match o.pop(&"variant".to_string()) {
Some(String(s)) => s,
Some(val) => {
- return Err(ExpectedError("String".to_strbuf(),
+ return Err(ExpectedError("String".to_string(),
format_strbuf!("{}", val)))
}
None => {
- return Err(MissingFieldError("variant".to_strbuf()))
+ return Err(MissingFieldError("variant".to_string()))
}
};
- match o.pop(&"fields".to_strbuf()) {
+ match o.pop(&"fields".to_string()) {
Some(List(l)) => {
for field in l.move_iter().rev() {
self.stack.push(field.clone());
}
},
Some(val) => {
- return Err(ExpectedError("List".to_strbuf(),
+ return Err(ExpectedError("List".to_string(),
format_strbuf!("{}", val)))
}
None => {
- return Err(MissingFieldError("fields".to_strbuf()))
+ return Err(MissingFieldError("fields".to_string()))
}
}
n
}
json => {
- return Err(ExpectedError("String or Object".to_strbuf(),
+ return Err(ExpectedError("String or Object".to_string(),
format_strbuf!("{}", json)))
}
};
names: &[&str],
f: |&mut Decoder, uint| -> DecodeResult<T>)
-> DecodeResult<T> {
- debug!("read_enum_struct_variant(names={:?})", names);
+ debug!("read_enum_struct_variant(names={})", names);
self.read_enum_variant(names, f)
}
debug!("read_struct_field(name={}, idx={})", name, idx);
let mut obj = try!(expect!(self.pop(), Object));
- let value = match obj.pop(&name.to_strbuf()) {
- None => return Err(MissingFieldError(name.to_strbuf())),
+ let value = match obj.pop(&name.to_string()) {
+ None => return Err(MissingFieldError(name.to_string())),
Some(json) => {
self.stack.push(json);
try!(f(self))
#[test]
fn test_write_null() {
- assert_eq!(Null.to_str().into_strbuf(), "null".to_strbuf());
- assert_eq!(Null.to_pretty_str().into_strbuf(), "null".to_strbuf());
+ assert_eq!(Null.to_str().into_string(), "null".to_string());
+ assert_eq!(Null.to_pretty_str().into_string(), "null".to_string());
}
#[test]
fn test_write_number() {
- assert_eq!(Number(3.0).to_str().into_strbuf(), "3".to_strbuf());
- assert_eq!(Number(3.0).to_pretty_str().into_strbuf(), "3".to_strbuf());
+ assert_eq!(Number(3.0).to_str().into_string(), "3".to_string());
+ assert_eq!(Number(3.0).to_pretty_str().into_string(), "3".to_string());
- assert_eq!(Number(3.1).to_str().into_strbuf(), "3.1".to_strbuf());
- assert_eq!(Number(3.1).to_pretty_str().into_strbuf(), "3.1".to_strbuf());
+ assert_eq!(Number(3.1).to_str().into_string(), "3.1".to_string());
+ assert_eq!(Number(3.1).to_pretty_str().into_string(), "3.1".to_string());
- assert_eq!(Number(-1.5).to_str().into_strbuf(), "-1.5".to_strbuf());
- assert_eq!(Number(-1.5).to_pretty_str().into_strbuf(), "-1.5".to_strbuf());
+ assert_eq!(Number(-1.5).to_str().into_string(), "-1.5".to_string());
+ assert_eq!(Number(-1.5).to_pretty_str().into_string(), "-1.5".to_string());
- assert_eq!(Number(0.5).to_str().into_strbuf(), "0.5".to_strbuf());
- assert_eq!(Number(0.5).to_pretty_str().into_strbuf(), "0.5".to_strbuf());
+ assert_eq!(Number(0.5).to_str().into_string(), "0.5".to_string());
+ assert_eq!(Number(0.5).to_pretty_str().into_string(), "0.5".to_string());
}
#[test]
fn test_write_str() {
- assert_eq!(String("".to_strbuf()).to_str().into_strbuf(), "\"\"".to_strbuf());
- assert_eq!(String("".to_strbuf()).to_pretty_str().into_strbuf(), "\"\"".to_strbuf());
+ assert_eq!(String("".to_string()).to_str().into_string(), "\"\"".to_string());
+ assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"".to_string());
- assert_eq!(String("foo".to_strbuf()).to_str().into_strbuf(), "\"foo\"".to_strbuf());
- assert_eq!(String("foo".to_strbuf()).to_pretty_str().into_strbuf(), "\"foo\"".to_strbuf());
+ assert_eq!(String("foo".to_string()).to_str().into_string(), "\"foo\"".to_string());
+ assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"".to_string());
}
#[test]
fn test_write_bool() {
- assert_eq!(Boolean(true).to_str().into_strbuf(), "true".to_strbuf());
- assert_eq!(Boolean(true).to_pretty_str().into_strbuf(), "true".to_strbuf());
+ assert_eq!(Boolean(true).to_str().into_string(), "true".to_string());
+ assert_eq!(Boolean(true).to_pretty_str().into_string(), "true".to_string());
- assert_eq!(Boolean(false).to_str().into_strbuf(), "false".to_strbuf());
- assert_eq!(Boolean(false).to_pretty_str().into_strbuf(), "false".to_strbuf());
+ assert_eq!(Boolean(false).to_str().into_string(), "false".to_string());
+ assert_eq!(Boolean(false).to_pretty_str().into_string(), "false".to_string());
}
#[test]
fn test_write_list() {
- assert_eq!(List(vec![]).to_str().into_strbuf(), "[]".to_strbuf());
- assert_eq!(List(vec![]).to_pretty_str().into_strbuf(), "[]".to_strbuf());
+ assert_eq!(List(vec![]).to_str().into_string(), "[]".to_string());
+ assert_eq!(List(vec![]).to_pretty_str().into_string(), "[]".to_string());
- assert_eq!(List(vec![Boolean(true)]).to_str().into_strbuf(), "[true]".to_strbuf());
+ assert_eq!(List(vec![Boolean(true)]).to_str().into_string(), "[true]".to_string());
assert_eq!(
- List(vec![Boolean(true)]).to_pretty_str().into_strbuf(),
+ List(vec![Boolean(true)]).to_pretty_str().into_string(),
"\
[\n \
true\n\
- ]".to_strbuf()
+ ]".to_string()
);
let long_test_list = List(vec![
Boolean(false),
Null,
- List(vec![String("foo\nbar".to_strbuf()), Number(3.5)])]);
+ List(vec![String("foo\nbar".to_string()), Number(3.5)])]);
- assert_eq!(long_test_list.to_str().into_strbuf(),
- "[false,null,[\"foo\\nbar\",3.5]]".to_strbuf());
+ assert_eq!(long_test_list.to_str().into_string(),
+ "[false,null,[\"foo\\nbar\",3.5]]".to_string());
assert_eq!(
- long_test_list.to_pretty_str().into_strbuf(),
+ long_test_list.to_pretty_str().into_string(),
"\
[\n \
false,\n \
\"foo\\nbar\",\n \
3.5\n \
]\n\
- ]".to_strbuf()
+ ]".to_string()
);
}
#[test]
fn test_write_object() {
- assert_eq!(mk_object([]).to_str().into_strbuf(), "{}".to_strbuf());
- assert_eq!(mk_object([]).to_pretty_str().into_strbuf(), "{}".to_strbuf());
+ assert_eq!(mk_object([]).to_str().into_string(), "{}".to_string());
+ assert_eq!(mk_object([]).to_pretty_str().into_string(), "{}".to_string());
assert_eq!(
mk_object([
- ("a".to_strbuf(), Boolean(true))
- ]).to_str().into_strbuf(),
- "{\"a\":true}".to_strbuf()
+ ("a".to_string(), Boolean(true))
+ ]).to_str().into_string(),
+ "{\"a\":true}".to_string()
);
assert_eq!(
- mk_object([("a".to_strbuf(), Boolean(true))]).to_pretty_str(),
+ mk_object([("a".to_string(), Boolean(true))]).to_pretty_str(),
"\
{\n \
\"a\": true\n\
- }".to_strbuf()
+ }".to_string()
);
let complex_obj = mk_object([
- ("b".to_strbuf(), List(vec![
- mk_object([("c".to_strbuf(), String("\x0c\r".to_strbuf()))]),
- mk_object([("d".to_strbuf(), String("".to_strbuf()))])
+ ("b".to_string(), List(vec![
+ mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
+ mk_object([("d".to_string(), String("".to_string()))])
]))
]);
assert_eq!(
- complex_obj.to_str().into_strbuf(),
+ complex_obj.to_str().into_string(),
"{\
\"b\":[\
{\"c\":\"\\f\\r\"},\
{\"d\":\"\"}\
]\
- }".to_strbuf()
+ }".to_string()
);
assert_eq!(
- complex_obj.to_pretty_str().into_strbuf(),
+ complex_obj.to_pretty_str().into_string(),
"\
{\n \
\"b\": [\n \
\"d\": \"\"\n \
}\n \
]\n\
- }".to_strbuf()
+ }".to_string()
);
let a = mk_object([
- ("a".to_strbuf(), Boolean(true)),
- ("b".to_strbuf(), List(vec![
- mk_object([("c".to_strbuf(), String("\x0c\r".to_strbuf()))]),
- mk_object([("d".to_strbuf(), String("".to_strbuf()))])
+ ("a".to_string(), Boolean(true)),
+ ("b".to_string(), List(vec![
+ mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
+ mk_object([("d".to_string(), String("".to_string()))])
]))
]);
let mut m = MemWriter::new();
f(&mut m as &mut io::Writer);
- str::from_utf8(m.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(m.unwrap().as_slice()).unwrap().to_string()
}
#[test]
let mut encoder = Encoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- "\"Dog\"".to_strbuf()
+ "\"Dog\"".to_string()
);
assert_eq!(
with_str_writer(|wr| {
let mut encoder = PrettyEncoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- "\"Dog\"".to_strbuf()
+ "\"Dog\"".to_string()
);
- let animal = Frog("Henry".to_strbuf(), 349);
+ let animal = Frog("Henry".to_string(), 349);
assert_eq!(
with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
animal.encode(&mut encoder).unwrap();
}),
- "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_strbuf()
+ "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_string()
);
assert_eq!(
with_str_writer(|wr| {
\"Frog\",\n \
\"Henry\",\n \
349\n\
- ]".to_strbuf()
+ ]".to_string()
);
}
#[test]
fn test_write_some() {
- let value = Some("jodhpurs".to_strbuf());
+ let value = Some("jodhpurs".to_string());
let s = with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, "\"jodhpurs\"".to_strbuf());
+ assert_eq!(s, "\"jodhpurs\"".to_string());
- let value = Some("jodhpurs".to_strbuf());
+ let value = Some("jodhpurs".to_string());
let s = with_str_writer(|wr| {
let mut encoder = PrettyEncoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, "\"jodhpurs\"".to_strbuf());
+ assert_eq!(s, "\"jodhpurs\"".to_string());
}
#[test]
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, "null".to_strbuf());
+ assert_eq!(s, "null".to_string());
let s = with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
});
- assert_eq!(s, "null".to_strbuf());
+ assert_eq!(s, "null".to_string());
}
#[test]
assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
- assert_eq!(from_str("\"\""), Ok(String("".to_strbuf())));
- assert_eq!(from_str("\"foo\""), Ok(String("foo".to_strbuf())));
- assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_strbuf())));
- assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_strbuf())));
- assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_strbuf())));
- assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_strbuf())));
- assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_strbuf())));
- assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_strbuf())));
- assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_strbuf())));
- assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_strbuf())));
+ assert_eq!(from_str("\"\""), Ok(String("".to_string())));
+ assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
+ assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
+ assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
+ assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
+ assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
+ assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
+ assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
+ assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
+ assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
}
#[test]
let mut decoder = Decoder::new(from_str(i).unwrap());
let v: String = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(v, o.to_strbuf());
+ assert_eq!(v, o.to_string());
}
}
assert_eq!(from_str("{}").unwrap(), mk_object([]));
assert_eq!(from_str("{\"a\": 3}").unwrap(),
- mk_object([("a".to_strbuf(), Number(3.0))]));
+ mk_object([("a".to_string(), Number(3.0))]));
assert_eq!(from_str(
"{ \"a\": null, \"b\" : true }").unwrap(),
mk_object([
- ("a".to_strbuf(), Null),
- ("b".to_strbuf(), Boolean(true))]));
+ ("a".to_string(), Null),
+ ("b".to_string(), Boolean(true))]));
assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
mk_object([
- ("a".to_strbuf(), Null),
- ("b".to_strbuf(), Boolean(true))]));
+ ("a".to_string(), Null),
+ ("b".to_string(), Boolean(true))]));
assert_eq!(from_str(
"{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
mk_object([
- ("a".to_strbuf(), Number(1.0)),
- ("b".to_strbuf(), List(vec![Boolean(true)]))
+ ("a".to_string(), Number(1.0)),
+ ("b".to_string(), List(vec![Boolean(true)]))
]));
assert_eq!(from_str(
"{\
]\
}").unwrap(),
mk_object([
- ("a".to_strbuf(), Number(1.0)),
- ("b".to_strbuf(), List(vec![
+ ("a".to_string(), Number(1.0)),
+ ("b".to_string(), List(vec![
Boolean(true),
- String("foo\nbar".to_strbuf()),
+ String("foo\nbar".to_string()),
mk_object([
- ("c".to_strbuf(), mk_object([("d".to_strbuf(), Null)]))
+ ("c".to_string(), mk_object([("d".to_string(), Null)]))
])
]))
]));
v,
Outer {
inner: vec![
- Inner { a: (), b: 2, c: vec!["abc".to_strbuf(), "xyz".to_strbuf()] }
+ Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
]
}
);
let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
let value: Option<String> = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(value, Some("jodhpurs".to_strbuf()));
+ assert_eq!(value, Some("jodhpurs".to_string()));
}
#[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".to_strbuf(), 349));
+ assert_eq!(value, Frog("Henry".to_string(), 349));
}
#[test]
let mut decoder = Decoder::new(from_str(s).unwrap());
let mut map: TreeMap<String, Animal> = Decodable::decode(&mut decoder).unwrap();
- assert_eq!(map.pop(&"a".to_strbuf()), Some(Dog));
- assert_eq!(map.pop(&"b".to_strbuf()), Some(Frog("Henry".to_strbuf(), 349)));
+ assert_eq!(map.pop(&"a".to_string()), Some(Dog));
+ assert_eq!(map.pop(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
}
#[test]
}
#[test]
fn test_decode_errors_struct() {
- check_err::<DecodeStruct>("[]", ExpectedError("Object".to_strbuf(), "[]".to_strbuf()));
+ check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
- ExpectedError("Number".to_strbuf(), "true".to_strbuf()));
+ ExpectedError("Number".to_string(), "true".to_string()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
- ExpectedError("Boolean".to_strbuf(), "[]".to_strbuf()));
+ ExpectedError("Boolean".to_string(), "[]".to_string()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
- ExpectedError("String".to_strbuf(), "{}".to_strbuf()));
+ ExpectedError("String".to_string(), "{}".to_string()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
- ExpectedError("List".to_strbuf(), "null".to_strbuf()));
+ ExpectedError("List".to_string(), "null".to_string()));
check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
- MissingFieldError("w".to_strbuf()));
+ MissingFieldError("w".to_string()));
}
#[test]
fn test_decode_errors_enum() {
check_err::<DecodeEnum>("{}",
- MissingFieldError("variant".to_strbuf()));
+ MissingFieldError("variant".to_string()));
check_err::<DecodeEnum>("{\"variant\": 1}",
- ExpectedError("String".to_strbuf(), "1".to_strbuf()));
+ ExpectedError("String".to_string(), "1".to_string()));
check_err::<DecodeEnum>("{\"variant\": \"A\"}",
- MissingFieldError("fields".to_strbuf()));
+ MissingFieldError("fields".to_string()));
check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
- ExpectedError("List".to_strbuf(), "null".to_strbuf()));
+ ExpectedError("List".to_string(), "null".to_string()));
check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
- UnknownVariantError("C".to_strbuf()));
+ UnknownVariantError("C".to_string()));
}
#[test]
fn test_find(){
let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
- let found_str = json_value.find(&"dog".to_strbuf());
+ let found_str = json_value.find(&"dog".to_string());
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".to_strbuf(),
- &"cat".to_strbuf(), &"mouse".to_strbuf()]);
+ let found_str = json_value.find_path(&[&"dog".to_string(),
+ &"cat".to_string(), &"mouse".to_string()]);
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".to_strbuf()).and_then(|j| j.as_string());
+ let found_str = json_value.search(&"mouse".to_string()).and_then(|j| j.as_string());
assert!(found_str.is_some());
assert!(found_str.unwrap() == "cheese");
}
let bytes = mem_buf.unwrap();
let json_str = from_utf8(bytes.as_slice()).unwrap();
match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
+ Err(_) => fail!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
}
}
let bytes = mem_buf.unwrap();
let json_str = from_utf8(bytes.as_slice()).unwrap();
match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
+ Err(_) => fail!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
}
}
use Decodable;
let json_str = "{\"1\":true}";
let json_obj = match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
+ Err(_) => fail!("Unable to parse json_str: {}", json_str),
Ok(o) => o
};
let mut decoder = Decoder::new(json_obj);
r#"{ "foo":"bar", "array" : [0, 1, 2,3 ,4,5], "idents":[null,true,false]}"#,
~[
(ObjectStart, ~[]),
- (StringValue("bar".to_strbuf()), ~[Key("foo")]),
+ (StringValue("bar".to_string()), ~[Key("foo")]),
(ListStart, ~[Key("array")]),
(NumberValue(0.0), ~[Key("array"), Index(0)]),
(NumberValue(1.0), ~[Key("array"), Index(1)]),
(NumberValue(1.0), ~[Key("a")]),
(ListStart, ~[Key("b")]),
(BooleanValue(true), ~[Key("b"), Index(0)]),
- (StringValue("foo\nbar".to_strbuf()), ~[Key("b"), Index(1)]),
+ (StringValue("foo\nbar".to_string()), ~[Key("b"), Index(1)]),
(ObjectStart, ~[Key("b"), Index(2)]),
(ObjectStart, ~[Key("b"), Index(2), Key("c")]),
(NullValue, ~[Key("b"), Index(2), Key("c"), Key("d")]),
assert!(stack.last_is_index());
assert!(stack.get(0) == Index(1));
- stack.push_key("foo".to_strbuf());
+ stack.push_key("foo".to_string());
assert!(stack.len() == 2);
assert!(stack.is_equal_to([Index(1), Key("foo")]));
assert!(stack.get(0) == Index(1));
assert!(stack.get(1) == Key("foo"));
- stack.push_key("bar".to_strbuf());
+ stack.push_key("bar".to_string());
assert!(stack.len() == 3);
assert!(stack.is_equal_to([Index(1), Key("foo"), Key("bar")]));
}
fn big_json() -> String {
- let mut src = "[\n".to_strbuf();
+ let mut src = "[\n".to_string();
for _ in range(0, 500) {
src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
[1,2,3]},"#);
fn into_str(self) -> String {
unsafe {
let s: &str = mem::transmute(self.as_slice());
- s.to_strbuf()
+ s.to_string()
}
}
}
*b = map[*b as uint];
}
- str::from_utf8(bytes.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(bytes.as_slice()).unwrap().to_string()
}
#[inline]
unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> String {
- let mut s = string.to_strbuf();
+ let mut s = string.to_string();
for b in s.as_mut_bytes().mut_iter() {
*b = map[*b as uint];
}
- s.into_strbuf()
+ s.into_string()
}
static ASCII_LOWER_MAP: &'static [u8] = &[
assert_eq!("( ;".to_ascii(), v2ascii!([40, 32, 59]));
let v = box [40u8, 32u8, 59u8];
assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
- assert_eq!("( ;".to_strbuf().as_slice().to_ascii(), v2ascii!([40, 32, 59]));
+ assert_eq!("( ;".to_string().as_slice().to_ascii(), v2ascii!([40, 32, 59]));
- assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_strbuf());
- assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_strbuf());
+ assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_string());
+ assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_string());
- assert_eq!("".to_ascii().to_lower().into_str(), "".to_strbuf());
- assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_strbuf());
- assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_strbuf());
+ assert_eq!("".to_ascii().to_lower().into_str(), "".to_string());
+ assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_string());
+ assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_string());
assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii()));
#[test]
fn test_ascii_vec_ng() {
- assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_strbuf());
- assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_strbuf());
- assert_eq!("".to_ascii().to_lower().into_str(), "".to_strbuf());
- assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_strbuf());
- assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_strbuf());
+ assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_string());
+ assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_string());
+ assert_eq!("".to_ascii().to_lower().into_str(), "".to_string());
+ assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_string());
+ assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_string());
}
#[test]
fn test_owned_ascii_vec() {
- assert_eq!(("( ;".to_strbuf()).into_ascii(), vec2ascii![40, 32, 59]);
+ assert_eq!(("( ;".to_string()).into_ascii(), vec2ascii![40, 32, 59]);
assert_eq!((box [40u8, 32u8, 59u8]).into_ascii(), vec2ascii![40, 32, 59]);
}
#[test]
fn test_ascii_into_str() {
- assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_strbuf());
- assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_strbuf());
+ assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_string());
+ assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_string());
}
#[test]
assert_eq!((vec![40u8, 32u8, 59u8]).into_ascii_opt(), Some(vec2ascii![40, 32, 59]));
assert_eq!((vec![127u8, 128u8, 255u8]).into_ascii_opt(), None);
- assert_eq!(("( ;".to_strbuf()).into_ascii_opt(), Some(vec2ascii![40, 32, 59]));
- assert_eq!(("zoä华".to_strbuf()).into_ascii_opt(), None);
+ assert_eq!(("( ;".to_string()).into_ascii_opt(), Some(vec2ascii![40, 32, 59]));
+ assert_eq!(("zoä华".to_string()).into_ascii_opt(), None);
}
#[test]
fn test_to_ascii_upper() {
- assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), "URL()URL()URL()üRL".to_strbuf());
- assert_eq!("hıKß".to_ascii_upper(), "HıKß".to_strbuf());
+ assert_eq!("url()URL()uRl()ürl".to_ascii_upper(), "URL()URL()URL()üRL".to_string());
+ assert_eq!("hıKß".to_ascii_upper(), "HıKß".to_string());
let mut i = 0;
while i <= 500 {
let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 }
else { i };
assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_upper(),
- from_char(from_u32(upper).unwrap()).to_strbuf())
+ from_char(from_u32(upper).unwrap()).to_string())
i += 1;
}
}
#[test]
fn test_to_ascii_lower() {
- assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), "url()url()url()Ürl".to_strbuf());
+ assert_eq!("url()URL()uRl()Ürl".to_ascii_lower(), "url()url()url()Ürl".to_string());
// Dotted capital I, Kelvin sign, Sharp S.
- assert_eq!("HİKß".to_ascii_lower(), "hİKß".to_strbuf());
+ assert_eq!("HİKß".to_ascii_lower(), "hİKß".to_string());
let mut i = 0;
while i <= 500 {
let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 }
else { i };
assert_eq!(from_char(from_u32(i).unwrap()).as_slice().to_ascii_lower(),
- from_char(from_u32(lower).unwrap()).to_strbuf())
+ from_char(from_u32(lower).unwrap()).to_string())
i += 1;
}
}
#[test]
fn test_into_ascii_upper() {
- assert_eq!(("url()URL()uRl()ürl".to_strbuf()).into_ascii_upper(),
- "URL()URL()URL()üRL".to_strbuf());
- assert_eq!(("hıKß".to_strbuf()).into_ascii_upper(), "HıKß".to_strbuf());
+ assert_eq!(("url()URL()uRl()ürl".to_string()).into_ascii_upper(),
+ "URL()URL()URL()üRL".to_string());
+ assert_eq!(("hıKß".to_string()).into_ascii_upper(), "HıKß".to_string());
let mut i = 0;
while i <= 500 {
let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 }
else { i };
- assert_eq!(from_char(from_u32(i).unwrap()).to_strbuf().into_ascii_upper(),
- from_char(from_u32(upper).unwrap()).to_strbuf())
+ assert_eq!(from_char(from_u32(i).unwrap()).to_string().into_ascii_upper(),
+ from_char(from_u32(upper).unwrap()).to_string())
i += 1;
}
}
#[test]
fn test_into_ascii_lower() {
- assert_eq!(("url()URL()uRl()Ürl".to_strbuf()).into_ascii_lower(),
- "url()url()url()Ürl".to_strbuf());
+ assert_eq!(("url()URL()uRl()Ürl".to_string()).into_ascii_lower(),
+ "url()url()url()Ürl".to_string());
// Dotted capital I, Kelvin sign, Sharp S.
- assert_eq!(("HİKß".to_strbuf()).into_ascii_lower(), "hİKß".to_strbuf());
+ assert_eq!(("HİKß".to_string()).into_ascii_lower(), "hİKß".to_string());
let mut i = 0;
while i <= 500 {
let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 }
else { i };
- assert_eq!(from_char(from_u32(i).unwrap()).to_strbuf().into_ascii_lower(),
- from_char(from_u32(lower).unwrap()).to_strbuf())
+ assert_eq!(from_char(from_u32(i).unwrap()).to_string().into_ascii_lower(),
+ from_char(from_u32(lower).unwrap()).to_string())
i += 1;
}
}
#[test]
fn test_to_str() {
let s = Ascii{ chr: 't' as u8 }.to_str();
- assert_eq!(s, "t".to_strbuf());
+ assert_eq!(s, "t".to_string());
}
#[test]
fn test_show() {
let c = Ascii { chr: 't' as u8 };
- assert_eq!(format_strbuf!("{}", c), "t".to_strbuf());
+ assert_eq!(format_strbuf!("{}", c), "t".to_string());
}
}
#[test]
fn test_clone_noleak() {
fn foo(f: |c: &CString|) {
- let s = "test".to_owned();
+ let s = "test".to_string();
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) } );
Some examples of the `format!` extension are:
```rust
-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()
+# extern crate debug;
+# fn main() {
+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"
+# }
```
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".to_owned()
+format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
```
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".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()
+# extern crate debug;
+# fn main() {
+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 ()"
+# }
```
It is illegal to put positional parameters (those without names) after arguments
### Argument types
Each argument's type is dictated by the format string. It is a requirement that
-every argument is only ever referred to by one type. When specifying the format
-of an argument, however, a string like `{}` indicates no type. This is allowed,
-and if all references to one argument do not provide a type, then the format `?`
-is used (the type's rust-representation is printed). For example, this is an
+every argument is only ever referred to by one type. For example, this is an
invalid format string:
```notrust
{0:d} {0:s}
```
-Because the first argument is both referred to as an integer as well as a
-string.
+This is invalid because the first argument is both referred to as an integer as
+well as a string.
Because formatting is done via traits, there is no requirement that the
`d` format actually takes an `int`, but rather it simply requires a type which
multiple actual types to be formatted via `{:d}` (like `i8` as well as `int`).
The current mapping of types to traits is:
-* `?` ⇒ `Poly`
+* *nothing* ⇒ `Show`
* `d` ⇒ `Signed`
* `i` ⇒ `Signed`
* `u` ⇒ `Unsigned`
* `f` ⇒ `Float`
* `e` ⇒ `LowerExp`
* `E` ⇒ `UpperExp`
-* *nothing* ⇒ `Show`
+* `?` ⇒ `Poly`
+
+> **Note**: The `Poly` formatting trait is provided by [libdebug](../../debug/)
+> and is an experimental implementation that should not be relied upon. In order
+> to use the `?` modifier, the libdebug crate must be linked against.
What this means is that any type of argument which implements the
`std::fmt::Binary` trait can then be formatted with `{:t}`. Implementations are
example:
```rust
-format!("{0, select, other{#}}", "hello"); // => "hello".to_owned()
+format!("{0, select, other{#}}", "hello"); // => "hello"
```
This example is the equivalent of `{0:s}` essentially.
use io::Writer;
use io;
+#[cfg(stage0)]
use option::None;
+#[cfg(stage0)]
use repr;
use result::{Ok, Err};
use str::{Str, StrAllocating};
pub use core::fmt::{secret_pointer};
#[doc(hidden)]
+#[cfg(stage0)]
pub fn secret_poly<T: Poly>(x: &T, fmt: &mut Formatter) -> Result {
// FIXME #11938 - UFCS would make us able call the this method
// directly Poly::fmt(x, fmt).
}
/// Format trait for the `?` character
+#[cfg(stage0)]
pub trait Poly {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
/// use std::fmt;
///
/// let s = format_args!(fmt::format, "Hello, {}!", "world");
-/// assert_eq!(s, "Hello, world!".to_owned());
+/// assert_eq!(s, "Hello, world!".to_string());
/// ```
pub fn format(args: &Arguments) -> string::String{
let mut output = io::MemWriter::new();
let _ = write!(&mut output, "{}", args);
- str::from_utf8(output.unwrap().as_slice()).unwrap().into_strbuf()
+ str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
}
/// Temporary transition utility
pub fn format_strbuf(args: &Arguments) -> string::String {
let mut output = io::MemWriter::new();
let _ = write!(&mut output, "{}", args);
- str::from_utf8(output.unwrap().as_slice()).unwrap().into_strbuf()
+ str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
}
+#[cfg(stage0)]
impl<T> Poly for T {
fn fmt(&self, f: &mut Formatter) -> Result {
match (f.width, f.precision) {
* phone: u64,
* }
*
- * 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 };
+ * let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
+ * let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
*
* assert!(hash::hash(&person1) != hash::hash(&person2));
* ```
* }
* }
*
- * 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 };
+ * let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
+ * let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
*
* assert!(hash::hash(&person1) == hash::hash(&person2));
* ```
fn test_read_line() {
let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc")));
let mut reader = BufferedReader::with_capacity(2, in_buf);
- assert_eq!(reader.read_line(), Ok("a\n".to_strbuf()));
- assert_eq!(reader.read_line(), Ok("b\n".to_strbuf()));
- assert_eq!(reader.read_line(), Ok("c".to_strbuf()));
+ assert_eq!(reader.read_line(), Ok("a\n".to_string()));
+ assert_eq!(reader.read_line(), Ok("b\n".to_string()));
+ assert_eq!(reader.read_line(), Ok("c".to_string()));
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".to_strbuf())));
- assert_eq!(it.next(), Some(Ok("b\n".to_strbuf())));
- assert_eq!(it.next(), Some(Ok("c".to_strbuf())));
+ assert_eq!(it.next(), Some(Ok("a\n".to_string())));
+ assert_eq!(it.next(), Some(Ok("b\n".to_string())));
+ assert_eq!(it.next(), Some(Ok("c".to_string())));
assert_eq!(it.next(), None);
}
writer.write_line("testing").unwrap();
writer.write_str("testing").unwrap();
let mut r = BufReader::new(writer.get_ref());
- assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_strbuf());
+ assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_string());
}
#[test]
writer.write_char('\n').unwrap();
writer.write_char('ệ').unwrap();
let mut r = BufReader::new(writer.get_ref());
- assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_strbuf());
+ assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_string());
}
#[test]
fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
if min > buf.len() {
return Err(IoError {
- detail: Some("the buffer is too short".to_strbuf()),
+ detail: Some("the buffer is too short".to_string()),
..standard_error(InvalidInput)
});
}
fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
if min > len {
return Err(IoError {
- detail: Some("the buffer is too short".to_strbuf()),
+ detail: Some("the buffer is too short".to_string()),
..standard_error(InvalidInput)
});
}
fn read_to_str(&mut self) -> IoResult<String> {
self.read_to_end().and_then(|s| {
match str::from_utf8(s.as_slice()) {
- Some(s) => Ok(s.to_strbuf()),
+ Some(s) => Ok(s.to_string()),
None => Err(standard_error(InvalidInput)),
}
})
/// use std::io;
///
/// let mut reader = io::stdin();
- /// let input = reader.read_line().ok().unwrap_or("nothing".to_owned());
+ /// let input = reader.read_line().ok().unwrap_or("nothing".to_string());
/// ```
///
/// # Error
fn read_line(&mut self) -> IoResult<String> {
self.read_until('\n' as u8).and_then(|line|
match str::from_utf8(line.as_slice()) {
- Some(s) => Ok(s.to_strbuf()),
+ Some(s) => Ok(s.to_string()),
None => Err(standard_error(InvalidInput)),
}
)
#[test]
fn ipv6_addr_to_str() {
let a1 = Ipv6Addr(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
- assert!(a1.to_str() == "::ffff:192.0.2.128".to_strbuf() ||
- a1.to_str() == "::FFFF:192.0.2.128".to_strbuf());
- assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_strbuf());
+ assert!(a1.to_str() == "::ffff:192.0.2.128".to_string() ||
+ a1.to_str() == "::FFFF:192.0.2.128".to_string());
+ assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_string());
}
}
iotest!(fn stdout_works() {
let mut cmd = Command::new("echo");
cmd.arg("foobar").stdout(CreatePipe(false, true));
- assert_eq!(run_output(cmd), "foobar\n".to_strbuf());
+ assert_eq!(run_output(cmd), "foobar\n".to_string());
})
#[cfg(unix, not(target_os="android"))]
cmd.arg("-c").arg("pwd")
.cwd(&Path::new("/"))
.stdout(CreatePipe(false, true));
- assert_eq!(run_output(cmd), "/\n".to_strbuf());
+ assert_eq!(run_output(cmd), "/\n".to_string());
})
#[cfg(unix, not(target_os="android"))]
drop(p.stdin.take());
let out = read_all(p.stdout.get_mut_ref() as &mut Reader);
assert!(p.wait().unwrap().success());
- assert_eq!(out, "foobar\n".to_strbuf());
+ assert_eq!(out, "foobar\n".to_string());
})
#[cfg(not(target_os="android"))]
let output_str = str::from_utf8(output.as_slice()).unwrap();
assert!(status.success());
- assert_eq!(output_str.trim().to_strbuf(), "hello".to_strbuf());
+ assert_eq!(output_str.trim().to_string(), "hello".to_string());
// FIXME #7224
if !running_on_valgrind() {
assert_eq!(error, Vec::new());
let output_str = str::from_utf8(output.as_slice()).unwrap();
assert!(status.success());
- assert_eq!(output_str.trim().to_strbuf(), "hello".to_strbuf());
+ assert_eq!(output_str.trim().to_string(), "hello".to_string());
// FIXME #7224
if !running_on_valgrind() {
assert_eq!(error, Vec::new());
let prog = pwd_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
- .output.as_slice()).unwrap().to_strbuf();
+ .output.as_slice()).unwrap().to_string();
let parent_dir = os::getcwd();
let child_dir = Path::new(output.as_slice().trim());
let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
- .output.as_slice()).unwrap().to_strbuf();
- let child_dir = Path::new(output.as_slice().trim().into_strbuf());
+ .output.as_slice()).unwrap().to_string();
+ let child_dir = Path::new(output.as_slice().trim().into_string());
let parent_stat = parent_dir.stat().unwrap();
let child_stat = child_dir.stat().unwrap();
let prog = env_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
- .output.as_slice()).unwrap().to_strbuf();
+ .output.as_slice()).unwrap().to_string();
let r = os::env();
for &(ref k, ref v) in r.iter() {
let mut prog = env_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output()
.unwrap().output.as_slice())
- .unwrap().to_strbuf();
+ .unwrap().to_string();
let r = os::env();
for &(ref k, ref v) in r.iter() {
// don't check android RANDOM variables
- if *k != "RANDOM".to_strbuf() {
+ if *k != "RANDOM".to_string() {
assert!(output.as_slice()
.contains(format!("{}={}",
*k,
let new_env = box [("RUN_TEST_NEW_ENV", "123")];
let prog = env_cmd().env(new_env).spawn().unwrap();
let result = prog.wait_with_output().unwrap();
- let output = str::from_utf8_lossy(result.output.as_slice()).into_strbuf();
+ let output = str::from_utf8_lossy(result.output.as_slice()).into_string();
assert!(output.as_slice().contains("RUN_TEST_NEW_ENV=123"),
"didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
set_stdout(box w);
println!("hello!");
});
- assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_strbuf());
+ assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_string());
})
iotest!(fn capture_stderr() {
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
-//! use the `String` type defined in [`strbuf`](strbuf/index.html)
+//! use the `String` type defined in [`string`](string/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
#[cfg(test)] extern crate rustuv;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate green;
+#[cfg(test)] extern crate debug;
#[cfg(test)] #[phase(syntax, link)] extern crate log;
// Make and rand accessible for benchmarking/testcases
#[test]
fn test_tls_multitask() {
static my_key: Key<String> = &Key;
- my_key.replace(Some("parent data".to_strbuf()));
+ my_key.replace(Some("parent data".to_string()));
task::spawn(proc() {
// TLS shouldn't carry over.
assert!(my_key.get().is_none());
- my_key.replace(Some("child data".to_strbuf()));
+ my_key.replace(Some("child data".to_string()));
assert!(my_key.get().get_ref().as_slice() == "child data");
// should be cleaned up for us
});
#[test]
fn test_tls_overwrite() {
static my_key: Key<String> = &Key;
- my_key.replace(Some("first data".to_strbuf()));
- my_key.replace(Some("next data".to_strbuf())); // Shouldn't leak.
+ my_key.replace(Some("first data".to_string()));
+ my_key.replace(Some("next data".to_string())); // Shouldn't leak.
assert!(my_key.get().unwrap().as_slice() == "next data");
}
#[test]
fn test_tls_pop() {
static my_key: Key<String> = &Key;
- my_key.replace(Some("weasel".to_strbuf()));
- assert!(my_key.replace(None).unwrap() == "weasel".to_strbuf());
+ my_key.replace(Some("weasel".to_string()));
+ assert!(my_key.replace(None).unwrap() == "weasel".to_string());
// Pop must remove the data from the map.
assert!(my_key.replace(None).is_none());
}
// a stack smaller than 1 MB.
static my_key: Key<String> = &Key;
task::spawn(proc() {
- my_key.replace(Some("hax".to_strbuf()));
+ my_key.replace(Some("hax".to_string()));
});
}
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
- str_key.replace(Some("string data".to_strbuf()));
+ str_key.replace(Some("string data".to_string()));
box_key.replace(Some(@()));
int_key.replace(Some(42));
});
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
- str_key.replace(Some("string data".to_strbuf()));
- str_key.replace(Some("string data 2".to_strbuf()));
+ str_key.replace(Some("string data".to_string()));
+ str_key.replace(Some("string data 2".to_string()));
box_key.replace(Some(@()));
box_key.replace(Some(@()));
int_key.replace(Some(42));
static str_key: Key<String> = &Key;
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
- str_key.replace(Some("parent data".to_strbuf()));
+ str_key.replace(Some("parent data".to_string()));
box_key.replace(Some(@()));
task::spawn(proc() {
- str_key.replace(Some("string data".to_strbuf()));
+ str_key.replace(Some("string data".to_string()));
box_key.replace(Some(@()));
int_key.replace(Some(42));
fail!();
)
-/// A macro to select an event from a number of ports.
+/// A macro to select an event from a number of receivers.
///
/// This macro is used to wait for the first event to occur on a number of
-/// ports. It places no restrictions on the types of ports given to this macro,
-/// this can be viewed as a heterogeneous select.
+/// receivers. It places no restrictions on the types of receivers given to
+/// this macro, this can be viewed as a heterogeneous select.
///
/// # Example
///
#[test]
fn test_to_str() {
- assert_eq!((0 as $T).to_str_radix(10u), "0".to_strbuf());
- assert_eq!((1 as $T).to_str_radix(10u), "1".to_strbuf());
- assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_strbuf());
- assert_eq!((127 as $T).to_str_radix(16u), "7f".to_strbuf());
- assert_eq!((100 as $T).to_str_radix(10u), "100".to_strbuf());
+ assert_eq!((0 as $T).to_str_radix(10u), "0".to_string());
+ assert_eq!((1 as $T).to_str_radix(10u), "1".to_string());
+ assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_string());
+ assert_eq!((127 as $T).to_str_radix(16u), "7f".to_string());
+ assert_eq!((100 as $T).to_str_radix(10u), "100".to_string());
}
#[test]
fn test_int_to_str_overflow() {
let mut i8_val: i8 = 127_i8;
- assert_eq!(i8_val.to_str(), "127".to_strbuf());
+ assert_eq!(i8_val.to_str(), "127".to_string());
i8_val += 1 as i8;
- assert_eq!(i8_val.to_str(), "-128".to_strbuf());
+ assert_eq!(i8_val.to_str(), "-128".to_string());
let mut i16_val: i16 = 32_767_i16;
- assert_eq!(i16_val.to_str(), "32767".to_strbuf());
+ assert_eq!(i16_val.to_str(), "32767".to_string());
i16_val += 1 as i16;
- assert_eq!(i16_val.to_str(), "-32768".to_strbuf());
+ assert_eq!(i16_val.to_str(), "-32768".to_string());
let mut i32_val: i32 = 2_147_483_647_i32;
- assert_eq!(i32_val.to_str(), "2147483647".to_strbuf());
+ assert_eq!(i32_val.to_str(), "2147483647".to_string());
i32_val += 1 as i32;
- assert_eq!(i32_val.to_str(), "-2147483648".to_strbuf());
+ assert_eq!(i32_val.to_str(), "-2147483648".to_string());
let mut i64_val: i64 = 9_223_372_036_854_775_807_i64;
- assert_eq!(i64_val.to_str(), "9223372036854775807".to_strbuf());
+ assert_eq!(i64_val.to_str(), "9223372036854775807".to_string());
i64_val += 1 as i64;
- assert_eq!(i64_val.to_str(), "-9223372036854775808".to_strbuf());
+ assert_eq!(i64_val.to_str(), "-9223372036854775808".to_string());
}
#[test]
#[test]
pub fn test_to_str() {
- assert_eq!((0 as $T).to_str_radix(10u), "0".to_strbuf());
- assert_eq!((1 as $T).to_str_radix(10u), "1".to_strbuf());
- assert_eq!((2 as $T).to_str_radix(10u), "2".to_strbuf());
- assert_eq!((11 as $T).to_str_radix(10u), "11".to_strbuf());
- assert_eq!((11 as $T).to_str_radix(16u), "b".to_strbuf());
- assert_eq!((255 as $T).to_str_radix(16u), "ff".to_strbuf());
- assert_eq!((0xff as $T).to_str_radix(10u), "255".to_strbuf());
+ assert_eq!((0 as $T).to_str_radix(10u), "0".to_string());
+ assert_eq!((1 as $T).to_str_radix(10u), "1".to_string());
+ assert_eq!((2 as $T).to_str_radix(10u), "2".to_string());
+ assert_eq!((11 as $T).to_str_radix(10u), "11".to_string());
+ assert_eq!((11 as $T).to_str_radix(16u), "b".to_string());
+ assert_eq!((255 as $T).to_str_radix(16u), "ff".to_string());
+ assert_eq!((0xff as $T).to_str_radix(10u), "255".to_string());
}
#[test]
#[test]
fn test_uint_to_str_overflow() {
let mut u8_val: u8 = 255_u8;
- assert_eq!(u8_val.to_str(), "255".to_strbuf());
+ assert_eq!(u8_val.to_str(), "255".to_string());
u8_val += 1 as u8;
- assert_eq!(u8_val.to_str(), "0".to_strbuf());
+ assert_eq!(u8_val.to_str(), "0".to_string());
let mut u16_val: u16 = 65_535_u16;
- assert_eq!(u16_val.to_str(), "65535".to_strbuf());
+ assert_eq!(u16_val.to_str(), "65535".to_string());
u16_val += 1 as u16;
- assert_eq!(u16_val.to_str(), "0".to_strbuf());
+ assert_eq!(u16_val.to_str(), "0".to_string());
let mut u32_val: u32 = 4_294_967_295_u32;
- assert_eq!(u32_val.to_str(), "4294967295".to_strbuf());
+ assert_eq!(u32_val.to_str(), "4294967295".to_string());
u32_val += 1 as u32;
- assert_eq!(u32_val.to_str(), "0".to_strbuf());
+ assert_eq!(u32_val.to_str(), "0".to_string());
let mut u64_val: u64 = 18_446_744_073_709_551_615_u64;
- assert_eq!(u64_val.to_str(), "18446744073709551615".to_strbuf());
+ assert_eq!(u64_val.to_str(), "18446744073709551615".to_string());
u64_val += 1 as u64;
- assert_eq!(u64_val.to_str(), "0".to_strbuf());
+ assert_eq!(u64_val.to_str(), "0".to_string());
}
#[test]
/// for details.
pub fn env() -> Vec<(String,String)> {
env_as_bytes().move_iter().map(|(k,v)| {
- let k = str::from_utf8_lossy(k.as_slice()).to_strbuf();
- let v = str::from_utf8_lossy(v.as_slice()).to_strbuf();
+ let k = str::from_utf8_lossy(k.as_slice()).to_string();
+ let v = str::from_utf8_lossy(v.as_slice()).to_string();
(k,v)
}).collect()
}
///
/// Fails if `n` has any interior NULs.
pub fn getenv(n: &str) -> Option<String> {
- getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_strbuf())
+ getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string())
}
#[cfg(unix)]
use os::win32::fill_utf16_buf_and_decode;
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
- }).map(|s| s.into_strbuf().into_bytes())
+ }).map(|s| s.into_string().into_bytes())
}
}
fail!("strerror_r failure");
}
- str::raw::from_c_str(p as *c_char).into_strbuf()
+ str::raw::from_c_str(p as *c_char).into_string()
}
}
fn real_args() -> Vec<String> {
real_args_as_bytes().move_iter()
.map(|v| {
- str::from_utf8_lossy(v.as_slice()).into_strbuf()
+ str::from_utf8_lossy(v.as_slice()).into_string()
}).collect()
}
fn test_setenv() {
let n = make_rand_name();
setenv(n.as_slice(), "VALUE");
- assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_strbuf()));
+ assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string()));
}
#[test]
let n = make_rand_name();
setenv(n.as_slice(), "1");
setenv(n.as_slice(), "2");
- assert_eq!(getenv(n.as_slice()), option::Some("2".to_strbuf()));
+ assert_eq!(getenv(n.as_slice()), option::Some("2".to_string()));
setenv(n.as_slice(), "");
- assert_eq!(getenv(n.as_slice()), option::Some("".to_strbuf()));
+ assert_eq!(getenv(n.as_slice()), option::Some("".to_string()));
}
// Windows GetEnvironmentVariable requires some extra work to make sure
#[test]
#[ignore]
fn test_getenv_big() {
- let mut s = "".to_strbuf();
+ let mut s = "".to_string();
let mut i = 0;
while i < 100 {
s.push_str("aaaaaaaaaa");
#[test]
fn test_env_set_get_huge() {
let n = make_rand_name();
- let s = "x".repeat(10000).to_strbuf();
+ let s = "x".repeat(10000).to_string();
setenv(n.as_slice(), s.as_slice());
assert_eq!(getenv(n.as_slice()), Some(s));
unsetenv(n.as_slice());
let mut e = env();
setenv(n.as_slice(), "VALUE");
- assert!(!e.contains(&(n.clone(), "VALUE".to_strbuf())));
+ assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
e = env();
- assert!(e.contains(&(n, "VALUE".to_strbuf())));
+ assert!(e.contains(&(n, "VALUE".to_string())));
}
#[test]
t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
t!(s: "a/b/c", ["d", "/e"], "/e");
t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
- t!(s: "a/b/c", ["d".to_strbuf(), "e".to_strbuf()], "a/b/c/d/e");
+ t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "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".to_strbuf(), "e".to_strbuf()], "a/b/c/d/e");
+ t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "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"));
}
}
}
}
- Some(Path::new(comps.connect("\\").into_strbuf()))
+ Some(Path::new(comps.connect("\\").into_string()))
}
}
(prefix, path)
};
(prefix, match val {
- None => s.into_strbuf(),
+ None => s.into_string(),
Some(val) => val
})
}
#[test]
fn test_display_str() {
let path = Path::new("foo");
- assert_eq!(path.display().to_str(), "foo".to_strbuf());
+ assert_eq!(path.display().to_str(), "foo".to_string());
let path = Path::new(b!("\\"));
- assert_eq!(path.filename_display().to_str(), "".to_strbuf());
+ assert_eq!(path.filename_display().to_str(), "".to_string());
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".to_strbuf(), "e".to_strbuf()], "a\\b\\c\\d\\e");
+ t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "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".to_strbuf(), "e".to_strbuf()], "a\\b\\c\\d\\e");
+ t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "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"));
let mut result = io::MemWriter::new();
write_repr(&mut result as &mut io::Writer, t).unwrap();
- str::from_utf8(result.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(result.unwrap().as_slice()).unwrap().to_string()
}
#[cfg(test)]
#[test]
fn tls() {
local_data_key!(key: @String)
- key.replace(Some(@"data".to_strbuf()));
+ key.replace(Some(@"data".to_string()));
assert_eq!(key.get().unwrap().as_slice(), "data");
local_data_key!(key2: @String)
- key2.replace(Some(@"data".to_strbuf()));
+ key2.replace(Some(@"data".to_string()));
assert_eq!(key2.get().unwrap().as_slice(), "data");
}
/// # Examples
///
/// ```rust
- /// let v = ~["a".to_owned(), "b".to_owned()];
+ /// let v = ~["a".to_string(), "b".to_string()];
/// for s in v.move_iter() {
/// // s has type ~str, not &~str
/// println!("{}", s);
assert_eq!(it.next(), None);
}
{
- let v = ["Hello".to_owned()];
+ let v = ["Hello".to_string()];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 1);
})
)
let empty: ~[int] = box [];
- test_show_vec!(empty, "[]".to_strbuf());
- test_show_vec!(box [1], "[1]".to_strbuf());
- test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_strbuf());
+ test_show_vec!(empty, "[]".to_string());
+ test_show_vec!(box [1], "[1]".to_string());
+ test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(box [box [], box [1u], box [1u, 1u]],
- "[[], [1], [1, 1]]".to_strbuf());
+ "[[], [1], [1, 1]]".to_string());
let empty_mut: &mut [int] = &mut[];
- test_show_vec!(empty_mut, "[]".to_strbuf());
- test_show_vec!(&mut[1], "[1]".to_strbuf());
- test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_strbuf());
+ test_show_vec!(empty_mut, "[]".to_string());
+ test_show_vec!(&mut[1], "[1]".to_string());
+ test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
- "[[], [1], [1, 1]]".to_strbuf());
+ "[[], [1], [1, 1]]".to_string());
}
#[test]
Rust's string type is one of the core primitive types of the language. While
represented by the name `str`, the name `str` is not actually a valid type in
-Rust. Each string must also be decorated with its ownership. This means that
-there is one common kind of string in Rust:
+Rust. Each string must also be decorated with a pointer. `String` is used
+for an owned string, so there is only one commonly-used `str` type in Rust:
+`&str`.
-* `&str` - This is the borrowed string type. This type of string can only be
- created from the other kind of string. As the name "borrowed"
- implies, this type of string is owned elsewhere, and this string
- cannot be moved out of.
+`&str` is the borrowed string type. This type of string can only be created
+from other strings, unless it is a static string (see below). As the word
+"borrowed" implies, this type of string is owned elsewhere, and this string
+cannot be moved out of.
-As an example, here's the one kind of string.
+As an example, here's some code that uses a string.
```rust
fn main() {
}
```
-From the example above, you can see that Rust has 1 different kind of string
-literal. The "borrowed literal" is akin to C's concept of a static string.
+From the example above, you can see that Rust's string literals have the
+`'static` lifetime. This is akin to C's concept of a static string.
String literals are allocated statically in the rodata of the
executable/library. The string then has the type `&'static str` meaning that
pub use core::str::{from_utf8, CharEq, Chars, CharOffsets};
pub use core::str::{Bytes, CharSplits};
pub use core::str::{CharSplitsN, Words, AnyLines, MatchIndices, StrSplits};
-pub use core::str::{eq_slice, is_utf8, is_utf16, UTF16Items};
-pub use core::str::{UTF16Item, ScalarValue, LoneSurrogate, utf16_items};
+pub use core::str::{eq_slice, is_utf8, is_utf16, Utf16Items};
+pub use core::str::{Utf16Item, ScalarValue, LoneSurrogate, utf16_items};
pub use core::str::{truncate_utf16_at_nul, utf8_char_width, CharRange};
pub use core::str::{Str, StrSlice};
/// // 𝄞music
/// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
-/// assert_eq!(str::from_utf16(v), Some("𝄞music".to_owned()));
+/// assert_eq!(str::from_utf16(v), Some("𝄞music".to_string()));
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
/// 0xD834];
///
/// assert_eq!(str::from_utf16_lossy(v),
-/// "𝄞mus\uFFFDic\uFFFD".to_owned());
+/// "𝄞mus\uFFFDic\uFFFD".to_string());
/// ```
pub fn from_utf16_lossy(v: &[u16]) -> String {
utf16_items(v).map(|c| c.to_char_lossy()).collect()
Section: MaybeOwned
*/
-/// A MaybeOwned is a string that can hold either a String or a &str.
+/// A `MaybeOwned` is a string that can hold either a `String` or a `&str`.
/// This can be useful as an optimization when an allocation is sometimes
/// needed but not always.
pub enum MaybeOwned<'a> {
Owned(String)
}
-/// SendStr is a specialization of `MaybeOwned` to be sendable
+/// `SendStr` is a specialization of `MaybeOwned` to be sendable
pub type SendStr = MaybeOwned<'static>;
impl<'a> MaybeOwned<'a> {
#[inline]
fn into_owned(self) -> String {
match self {
- Slice(s) => s.to_owned(),
+ Slice(s) => s.to_string(),
Owned(s) => s
}
}
fn clone(&self) -> MaybeOwned<'a> {
match *self {
Slice(s) => Slice(s),
- Owned(ref s) => Owned(s.to_owned())
+ Owned(ref s) => Owned(s.to_string())
}
}
}
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".to_owned());
+ assert_eq!(c, "AAA".to_string());
}
}
}
/// Convert `self` into a `String`.
#[inline]
- fn to_strbuf(&self) -> String {
+ fn to_string(&self) -> String {
String::from_str(self.as_slice())
}
/// Convert `self` into a `String`, not making a copy if possible.
#[inline]
- fn into_strbuf(self) -> String {
+ fn into_string(self) -> String {
self.into_owned()
}
///
/// ```rust
/// let s = "Do you know the muffin man,
- /// The muffin man, the muffin man, ...".to_owned();
+ /// The muffin man, the muffin man, ...".to_string();
///
/// assert_eq!(s.replace("muffin man", "little lamb"),
/// "Do you know the little lamb,
- /// The little lamb, the little lamb, ...".to_owned());
+ /// The little lamb, the little lamb, ...".to_string());
///
/// // not found, so no change.
/// assert_eq!(s.replace("cookie monster", "little lamb"), s);
result
}
- /// Copy a slice into a new `String`.
+ #[allow(missing_doc)]
+ #[deprecated = "obsolete, use `to_string`"]
#[inline]
fn to_owned(&self) -> String {
use slice::Vector;
impl<'a> StrAllocating for &'a str {
#[inline]
fn into_owned(self) -> String {
- self.to_owned()
+ self.to_string()
}
}
}
#[inline]
- fn append(self, rhs: &str) -> String {
- let mut new_str = String::from_owned_str(self);
- new_str.push_str(rhs);
- new_str
+ fn append(mut self, rhs: &str) -> String {
+ self.push_str(rhs);
+ self
}
}
#[test]
fn test_collect() {
- let empty = "".to_owned();
+ let empty = "".to_string();
let s: String = empty.as_slice().chars().collect();
assert_eq!(empty, s);
- let data = "ประเทศไทย中".to_owned();
+ let data = "ประเทศไทย中".to_string();
let s: String = data.as_slice().chars().collect();
assert_eq!(data, s);
}
#[test]
fn test_into_bytes() {
- let data = "asdf".to_owned();
+ let data = "asdf".to_string();
let buf = data.into_bytes();
assert_eq!(bytes!("asdf"), buf.as_slice());
}
assert!(data.slice(2u, 4u).find_str("ab").is_none());
let string = "ประเทศไทย中华Việt Nam";
- let mut data = string.to_strbuf();
+ let mut data = string.to_string();
data.push_str(string);
assert!(data.as_slice().find_str("ไท华").is_none());
assert_eq!(data.as_slice().slice(0u, 43u).find_str(""), Some(0u));
fn t(v: &[String], s: &str) {
assert_eq!(v.concat(), s.to_str().into_owned());
}
- t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(),
- "no".to_owned(), "good".to_owned()], "youknowI'mnogood");
+ t(["you".to_string(), "know".to_string(), "I'm".to_string(),
+ "no".to_string(), "good".to_string()], "youknowI'mnogood");
let v: &[String] = [];
t(v, "");
- t(["hi".to_owned()], "hi");
+ t(["hi".to_string()], "hi");
}
#[test]
fn t(v: &[String], sep: &str, s: &str) {
assert_eq!(v.connect(sep), s.to_str().into_owned());
}
- t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(),
- "no".to_owned(), "good".to_owned()],
+ t(["you".to_string(), "know".to_string(), "I'm".to_string(),
+ "no".to_string(), "good".to_string()],
" ", "you know I'm no good");
let v: &[String] = [];
t(v, " ", "");
- t(["hi".to_owned()], " ", "hi");
+ t(["hi".to_string()], " ", "hi");
}
#[test]
#[test]
fn test_repeat() {
- 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());
+ assert_eq!("x".repeat(4), "xxxx".to_string());
+ assert_eq!("hi".repeat(4), "hihihihi".to_string());
+ assert_eq!("ไท华".repeat(3), "ไท华ไท华ไท华".to_string());
+ assert_eq!("".repeat(4), "".to_string());
+ assert_eq!("hi".repeat(0), "".to_string());
}
#[test]
#[test]
fn test_replace() {
let a = "a";
- 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());
+ assert_eq!("".replace(a, "b"), "".to_string());
+ assert_eq!("a".replace(a, "b"), "b".to_string());
+ assert_eq!("ab".replace(a, "b"), "bb".to_string());
let test = "test";
assert!(" test test ".replace(test, "toast") ==
- " toast toast ".to_owned());
- assert_eq!(" test test ".replace(test, ""), " ".to_owned());
+ " toast toast ".to_string());
+ assert_eq!(" test test ".replace(test, ""), " ".to_string());
}
#[test]
let a = box [65, 65, 65, 65, 65, 65, 65, 0];
let b = a.as_ptr();
let c = raw::from_c_str(b);
- assert_eq!(c, "AAAAAAA".to_owned());
+ assert_eq!(c, "AAAAAAA".to_string());
}
}
fn test_as_bytes_fail() {
// Don't double free. (I'm not sure if this exercises the
// original problem code path anymore.)
- let s = "".to_owned();
+ let s = "".to_string();
let _bytes = s.as_bytes();
fail!();
}
#[test]
fn vec_str_conversions() {
- let s1: String = "All mimsy were the borogoves".to_strbuf();
+ let s1: String = "All mimsy were the borogoves".to_string();
let v: Vec<u8> = Vec::from_slice(s1.as_bytes());
- let s2: String = from_utf8(v.as_slice()).unwrap().to_strbuf();
+ let s2: String = from_utf8(v.as_slice()).unwrap().to_string();
let mut i: uint = 0u;
let n1: uint = s1.len();
let n2: uint = v.len();
#[test]
fn test_utf16() {
let pairs =
- [("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n".to_owned(),
+ [("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n".to_string(),
vec![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".to_owned(),
+ ("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n".to_string(),
vec![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".to_owned(),
+ ("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n".to_string(),
vec![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".to_owned(),
+ ("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n".to_string(),
vec![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".to_owned(),
+ ("\U00020000".to_string(),
vec![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".to_owned());
+ assert_eq!(from_utf16_lossy([0xD800]), "\uFFFD".to_string());
// lead + lead
- assert_eq!(from_utf16_lossy([0xD800, 0xD800]), "\uFFFD\uFFFD".to_owned());
+ assert_eq!(from_utf16_lossy([0xD800, 0xD800]), "\uFFFD\uFFFD".to_string());
// isolated trail
- assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), "a\uFFFD".to_owned());
+ assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), "a\uFFFD".to_string());
// general
- assert_eq!(from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]), "\uFFFD𐒋\uFFFD".to_owned());
+ assert_eq!(from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
+ "\uFFFD𐒋\uFFFD".to_string());
}
#[test]
#[test]
fn test_escape_unicode() {
- 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());
+ assert_eq!("abc".escape_unicode(), "\\x61\\x62\\x63".to_string());
+ assert_eq!("a c".escape_unicode(), "\\x61\\x20\\x63".to_string());
+ assert_eq!("\r\n\t".escape_unicode(), "\\x0d\\x0a\\x09".to_string());
+ assert_eq!("'\"\\".escape_unicode(), "\\x27\\x22\\x5c".to_string());
+ assert_eq!("\x00\x01\xfe\xff".escape_unicode(), "\\x00\\x01\\xfe\\xff".to_string());
+ assert_eq!("\u0100\uffff".escape_unicode(), "\\u0100\\uffff".to_string());
+ assert_eq!("\U00010000\U0010ffff".escape_unicode(), "\\U00010000\\U0010ffff".to_string());
+ assert_eq!("ab\ufb00".escape_unicode(), "\\x61\\x62\\ufb00".to_string());
+ assert_eq!("\U0001d4ea\r".escape_unicode(), "\\U0001d4ea\\x0d".to_string());
}
#[test]
fn test_escape_default() {
- 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());
+ assert_eq!("abc".escape_default(), "abc".to_string());
+ assert_eq!("a c".escape_default(), "a c".to_string());
+ assert_eq!("\r\n\t".escape_default(), "\\r\\n\\t".to_string());
+ assert_eq!("'\"\\".escape_default(), "\\'\\\"\\\\".to_string());
+ assert_eq!("\u0100\uffff".escape_default(), "\\u0100\\uffff".to_string());
+ assert_eq!("\U00010000\U0010ffff".escape_default(), "\\U00010000\\U0010ffff".to_string());
+ assert_eq!("ab\ufb00".escape_default(), "ab\\ufb00".to_string());
+ assert_eq!("\U0001d4ea\r".escape_default(), "\\U0001d4ea\\r".to_string());
}
#[test]
#[test]
fn test_nfd_chars() {
- assert_eq!("abc".nfd_chars().collect::<String>(), "abc".to_strbuf());
- assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<String>(), "d\u0307\u01c4".to_strbuf());
- assert_eq!("\u2026".nfd_chars().collect::<String>(), "\u2026".to_strbuf());
- assert_eq!("\u2126".nfd_chars().collect::<String>(), "\u03a9".to_strbuf());
- assert_eq!("\u1e0b\u0323".nfd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("\u1e0d\u0307".nfd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("a\u0301".nfd_chars().collect::<String>(), "a\u0301".to_strbuf());
- assert_eq!("\u0301a".nfd_chars().collect::<String>(), "\u0301a".to_strbuf());
- assert_eq!("\ud4db".nfd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_strbuf());
- assert_eq!("\uac1c".nfd_chars().collect::<String>(), "\u1100\u1162".to_strbuf());
+ assert_eq!("abc".nfd_chars().collect::<String>(), "abc".to_string());
+ assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<String>(), "d\u0307\u01c4".to_string());
+ assert_eq!("\u2026".nfd_chars().collect::<String>(), "\u2026".to_string());
+ assert_eq!("\u2126".nfd_chars().collect::<String>(), "\u03a9".to_string());
+ assert_eq!("\u1e0b\u0323".nfd_chars().collect::<String>(), "d\u0323\u0307".to_string());
+ assert_eq!("\u1e0d\u0307".nfd_chars().collect::<String>(), "d\u0323\u0307".to_string());
+ assert_eq!("a\u0301".nfd_chars().collect::<String>(), "a\u0301".to_string());
+ assert_eq!("\u0301a".nfd_chars().collect::<String>(), "\u0301a".to_string());
+ assert_eq!("\ud4db".nfd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_string());
+ assert_eq!("\uac1c".nfd_chars().collect::<String>(), "\u1100\u1162".to_string());
}
#[test]
fn test_nfkd_chars() {
- assert_eq!("abc".nfkd_chars().collect::<String>(), "abc".to_strbuf());
- assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<String>(), "d\u0307DZ\u030c".to_strbuf());
- assert_eq!("\u2026".nfkd_chars().collect::<String>(), "...".to_strbuf());
- assert_eq!("\u2126".nfkd_chars().collect::<String>(), "\u03a9".to_strbuf());
- assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("a\u0301".nfkd_chars().collect::<String>(), "a\u0301".to_strbuf());
- assert_eq!("\u0301a".nfkd_chars().collect::<String>(), "\u0301a".to_strbuf());
- assert_eq!("\ud4db".nfkd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_strbuf());
- assert_eq!("\uac1c".nfkd_chars().collect::<String>(), "\u1100\u1162".to_strbuf());
+ assert_eq!("abc".nfkd_chars().collect::<String>(), "abc".to_string());
+ assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<String>(), "d\u0307DZ\u030c".to_string());
+ assert_eq!("\u2026".nfkd_chars().collect::<String>(), "...".to_string());
+ assert_eq!("\u2126".nfkd_chars().collect::<String>(), "\u03a9".to_string());
+ assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_string());
+ assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_string());
+ assert_eq!("a\u0301".nfkd_chars().collect::<String>(), "a\u0301".to_string());
+ assert_eq!("\u0301a".nfkd_chars().collect::<String>(), "\u0301a".to_string());
+ assert_eq!("\ud4db".nfkd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_string());
+ assert_eq!("\uac1c".nfkd_chars().collect::<String>(), "\u1100\u1162".to_string());
}
#[test]
v.iter().map(|x| x.len()).sum()
}
- let s = "01234".to_owned();
+ let s = "01234".to_string();
assert_eq!(5, sum_len(["012", "", "34"]));
- assert_eq!(5, sum_len(["01".to_owned(), "2".to_owned(), "34".to_owned(), "".to_owned()]));
+ assert_eq!(5, sum_len(["01".to_string(), "2".to_string(),
+ "34".to_string(), "".to_string()]));
assert_eq!(5, sum_len([s.as_slice()]));
}
#[test]
fn test_str_from_utf8_owned() {
let xs = Vec::from_slice(bytes!("hello"));
- assert_eq!(from_utf8_owned(xs), Ok("hello".to_owned()));
+ assert_eq!(from_utf8_owned(xs), Ok("hello".to_string()));
let xs = Vec::from_slice(bytes!("ศไทย中华Việt Nam"));
- assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_owned()));
+ assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_string()));
let xs = Vec::from_slice(bytes!("hello", 0xff));
assert_eq!(from_utf8_owned(xs),
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".to_owned()));
+ assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD There\uFFFD Goodbye".to_string()));
let xs = bytes!("Hello", 0xC0, 0x80, " There", 0xE6, 0x83, " Goodbye");
- assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD\uFFFD There\uFFFD Goodbye".to_owned()));
+ assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD\uFFFD There\uFFFD Goodbye".to_string()));
let xs = bytes!(0xF5, "foo", 0xF5, 0x80, "bar");
- assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFD\uFFFDbar".to_owned()));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFD\uFFFDbar".to_string()));
let xs = bytes!(0xF1, "foo", 0xF1, 0x80, "bar", 0xF1, 0x80, 0x80, "baz");
- assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFDbaz".to_owned()));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFDbaz".to_string()));
let xs = bytes!(0xF4, "foo", 0xF4, 0x80, "bar", 0xF4, 0xBF, "baz");
- assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz".to_owned()));
+ assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz".to_string()));
let xs = bytes!(0xF0, 0x80, 0x80, 0x80, "foo", 0xF0, 0x90, 0x80, 0x80, "bar");
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFD\uFFFD\
- foo\U00010000bar".to_owned()));
+ foo\U00010000bar".to_string()));
// 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".to_owned()));
+ \uFFFD\uFFFD\uFFFDbar".to_string()));
}
#[test]
fn test_from_str() {
let owned: Option<String> = from_str("string");
- assert_eq!(owned, Some("string".to_strbuf()));
+ assert_eq!(owned, Some("string".to_string()));
}
#[test]
let s = Slice("abcde");
assert_eq!(s.len(), 5);
assert_eq!(s.as_slice(), "abcde");
- assert_eq!(s.to_str(), "abcde".to_strbuf());
- assert_eq!(format_strbuf!("{}", s), "abcde".to_strbuf());
- assert!(s.lt(&Owned("bcdef".to_owned())));
+ assert_eq!(s.to_str(), "abcde".to_string());
+ assert_eq!(format_strbuf!("{}", s), "abcde".to_string());
+ assert!(s.lt(&Owned("bcdef".to_string())));
assert_eq!(Slice(""), Default::default());
- let o = Owned("abcde".to_owned());
+ let o = Owned("abcde".to_string());
assert_eq!(o.len(), 5);
assert_eq!(o.as_slice(), "abcde");
- assert_eq!(o.to_str(), "abcde".to_strbuf());
- assert_eq!(format_strbuf!("{}", o), "abcde".to_strbuf());
+ assert_eq!(o.to_str(), "abcde".to_string());
+ assert_eq!(format_strbuf!("{}", o), "abcde".to_string());
assert!(o.lt(&Slice("bcdef")));
- assert_eq!(Owned("".to_owned()), Default::default());
+ assert_eq!(Owned("".to_string()), Default::default());
assert!(s.cmp(&o) == Equal);
assert!(s.equiv(&o));
assert!(s.is_slice());
assert!(!s.is_owned());
- let o = Owned("abcde".to_owned());
+ let o = Owned("abcde".to_string());
assert!(!o.is_slice());
assert!(o.is_owned());
}
#[test]
fn test_maybe_owned_clone() {
- assert_eq!(Owned("abcde".to_owned()), Slice("abcde").clone());
- assert_eq!(Owned("abcde".to_owned()), Owned("abcde".to_owned()).clone());
+ assert_eq!(Owned("abcde".to_string()), Slice("abcde").clone());
+ assert_eq!(Owned("abcde".to_string()), Owned("abcde".to_string()).clone());
assert_eq!(Slice("abcde"), Slice("abcde").clone());
- assert_eq!(Slice("abcde"), Owned("abcde".to_owned()).clone());
+ assert_eq!(Slice("abcde"), Owned("abcde".to_string()).clone());
}
#[test]
fn test_maybe_owned_into_owned() {
- assert_eq!(Slice("abcde").into_owned(), "abcde".to_owned());
- assert_eq!(Owned("abcde".to_owned()).into_owned(), "abcde".to_owned());
+ assert_eq!(Slice("abcde").into_owned(), "abcde".to_string());
+ assert_eq!(Owned("abcde".to_string()).into_owned(), "abcde".to_string());
}
#[test]
fn test_into_maybe_owned() {
assert_eq!("abcde".into_maybe_owned(), Slice("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()));
+ assert_eq!(("abcde".to_string()).into_maybe_owned(), Slice("abcde"));
+ assert_eq!("abcde".into_maybe_owned(), Owned("abcde".to_string()));
+ assert_eq!(("abcde".to_string()).into_maybe_owned(), Owned("abcde".to_string()));
}
}
}
}
- /// Creates a new string buffer from the given owned string, taking care not to copy it.
+ #[allow(missing_doc)]
+ #[deprecated = "obsoleted by the removal of ~str"]
#[inline]
pub fn from_owned_str(string: String) -> String {
string
}
#[inline]
- fn into_strbuf(self) -> String {
+ fn into_string(self) -> String {
self
}
}
impl FromStr for String {
#[inline]
fn from_str(s: &str) -> Option<String> {
- Some(s.to_strbuf())
+ Some(s.to_string())
}
}
#[test]
fn test_owned_named_task() {
- TaskBuilder::new().named("ada lovelace".to_owned()).spawn(proc() {
+ TaskBuilder::new().named("ada lovelace".to_string()).spawn(proc() {
with_task_name(|name| {
assert!(name.unwrap() == "ada lovelace");
})
#[test]
fn test_try_success() {
match try(proc() {
- "Success!".to_owned()
+ "Success!".to_string()
}).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".to_strbuf());
+ fail!("owned string".to_string());
}) {
Err(e) => {
type T = String;
assert!(e.is::<T>());
- assert_eq!(*e.move::<T>().unwrap(), "owned string".to_strbuf());
+ assert_eq!(*e.move::<T>().unwrap(), "owned string".to_string());
}
Ok(()) => fail!()
}
#[test]
fn test_simple_types() {
- assert_eq!(1i.to_str(), "1".to_strbuf());
- assert_eq!((-1i).to_str(), "-1".to_strbuf());
- assert_eq!(200u.to_str(), "200".to_strbuf());
- assert_eq!(2u8.to_str(), "2".to_strbuf());
- assert_eq!(true.to_str(), "true".to_strbuf());
- assert_eq!(false.to_str(), "false".to_strbuf());
- assert_eq!(().to_str(), "()".to_strbuf());
- assert_eq!(("hi".to_strbuf()).to_str(), "hi".to_strbuf());
+ assert_eq!(1i.to_str(), "1".to_string());
+ assert_eq!((-1i).to_str(), "-1".to_string());
+ assert_eq!(200u.to_str(), "200".to_string());
+ assert_eq!(2u8.to_str(), "2".to_string());
+ assert_eq!(true.to_str(), "true".to_string());
+ assert_eq!(false.to_str(), "false".to_string());
+ assert_eq!(().to_str(), "()".to_string());
+ assert_eq!(("hi".to_string()).to_str(), "hi".to_string());
}
#[test]
fn test_vectors() {
let x: ~[int] = box [];
- assert_eq!(x.to_str(), "[]".to_strbuf());
- assert_eq!((box [1]).to_str(), "[1]".to_strbuf());
- assert_eq!((box [1, 2, 3]).to_str(), "[1, 2, 3]".to_strbuf());
+ assert_eq!(x.to_str(), "[]".to_string());
+ assert_eq!((box [1]).to_str(), "[1]".to_string());
+ assert_eq!((box [1, 2, 3]).to_str(), "[1, 2, 3]".to_string());
assert!((box [box [], box [1], box [1, 1]]).to_str() ==
- "[[], [1], [1, 1]]".to_strbuf());
+ "[[], [1], [1, 1]]".to_string());
}
}
} else {
Err(CString::new(last_error, false).as_str()
.unwrap()
- .to_strbuf())
+ .to_string())
};
ret
/// # Example
///
/// ```rust
- /// let v = vec!("a".to_owned(), "b".to_owned());
+ /// let v = vec!("a".to_string(), "b".to_string());
/// for s in v.move_iter() {
/// // s has type String, not &String
/// println!("{}", s);
///
/// # Example
/// ```rust
- /// let mut v = vec!("foo".to_owned(), "bar".to_owned(), "baz".to_owned(), "qux".to_owned());
+ /// let mut v = vec!("foo".to_string(), "bar".to_string(),
+ /// "baz".to_string(), "qux".to_string());
///
- /// 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(1), Some("bar".to_string()));
+ /// assert_eq!(v, vec!("foo".to_string(), "qux".to_string(), "baz".to_string()));
///
- /// 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(0), Some("foo".to_string()));
+ /// assert_eq!(v, vec!("baz".to_string(), "qux".to_string()));
///
/// assert_eq!(v.swap_remove(2), None);
/// ```
let b: ~[u8] = FromVec::from_vec(a);
assert_eq!(b.as_slice(), &[]);
- let a = vec!["one".to_strbuf(), "two".to_strbuf()];
+ let a = vec!["one".to_string(), "two".to_string()];
let b: ~[String] = FromVec::from_vec(a);
- assert_eq!(b.as_slice(), &["one".to_strbuf(), "two".to_strbuf()]);
+ assert_eq!(b.as_slice(), &["one".to_string(), "two".to_string()]);
struct Foo {
x: uint,
pub fn DuplexStream1() {
let (left, right) = duplex();
- left.send("abc".to_owned());
+ left.send("abc".to_string());
right.send(123);
assert!(left.recv() == 123);
- assert!(right.recv() == "abc".to_owned());
+ assert!(right.recv() == "abc".to_string());
}
}
#[test]
fn test_from_value() {
- let mut f = Future::from_value("snail".to_owned());
- assert_eq!(f.get(), "snail".to_owned());
+ let mut f = Future::from_value("snail".to_string());
+ assert_eq!(f.get(), "snail".to_string());
}
#[test]
fn test_from_receiver() {
let (tx, rx) = channel();
- tx.send("whale".to_owned());
+ tx.send("whale".to_string());
let mut f = Future::from_receiver(rx);
- assert_eq!(f.get(), "whale".to_owned());
+ assert_eq!(f.get(), "whale".to_string());
}
#[test]
fn test_from_fn() {
- let mut f = Future::from_fn(proc() "brail".to_owned());
- assert_eq!(f.get(), "brail".to_owned());
+ let mut f = Future::from_fn(proc() "brail".to_string());
+ assert_eq!(f.get(), "brail".to_string());
}
#[test]
fn test_interface_get() {
- let mut f = Future::from_value("fail".to_owned());
- assert_eq!(f.get(), "fail".to_owned());
+ let mut f = Future::from_value("fail".to_string());
+ assert_eq!(f.get(), "fail".to_string());
}
#[test]
fn test_interface_unwrap() {
- let f = Future::from_value("fail".to_owned());
- assert_eq!(f.unwrap(), "fail".to_owned());
+ let f = Future::from_value("fail".to_string());
+ assert_eq!(f.unwrap(), "fail".to_string());
}
#[test]
#[test]
fn test_spawn() {
- let mut f = Future::spawn(proc() "bale".to_owned());
- assert_eq!(f.get(), "bale".to_owned());
+ let mut f = Future::spawn(proc() "bale".to_string());
+ assert_eq!(f.get(), "bale".to_string());
}
#[test]
PatRange(@Expr, @Expr),
// [a, b, ..i, y, z] is represented as
// PatVec(~[a, b], Some(i), ~[y, z])
- PatVec(Vec<@Pat> , Option<@Pat>, Vec<@Pat> )
+ PatVec(Vec<@Pat> , Option<@Pat>, Vec<@Pat> ),
+ PatMac(Mac),
}
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash, Show)]
StmtMac(Mac, bool),
}
+/// Where a local declaration came from: either a true `let ... =
+/// ...;`, or one desugared from the pattern of a for loop.
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
+pub enum LocalSource {
+ LocalLet,
+ LocalFor,
+}
+
// FIXME (pending discussion of #1697, #2178...): local should really be
// a refinement on pat.
/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
pub init: Option<@Expr>,
pub id: NodeId,
pub span: Span,
+ pub source: LocalSource,
}
pub type Decl = Spanned<Decl_>;
}
s.push_str(e.as_slice());
s
- }).to_strbuf()
+ }).to_string()
}
#[deriving(Clone)]
ItemImpl(..) => "impl",
ItemMac(..) => "macro"
};
- (format!("{} {} (id={})", item_str, path_str, id)).to_strbuf()
+ (format!("{} {} (id={})", item_str, path_str, id)).to_string()
}
Some(NodeForeignItem(item)) => {
let path_str = map.path_to_str_with_ident(id, item.ident);
- (format!("foreign item {} (id={})", path_str, id)).to_strbuf()
+ (format!("foreign item {} (id={})", path_str, id)).to_string()
}
Some(NodeMethod(m)) => {
(format!("method {} in {} (id={})",
token::get_ident(m.ident),
- map.path_to_str(id), id)).to_strbuf()
+ map.path_to_str(id), id)).to_string()
}
Some(NodeTraitMethod(ref tm)) => {
let m = ast_util::trait_method_to_ty_method(&**tm);
(format!("method {} in {} (id={})",
token::get_ident(m.ident),
- map.path_to_str(id), id)).to_strbuf()
+ map.path_to_str(id), id)).to_string()
}
Some(NodeVariant(ref variant)) => {
(format!("variant {} in {} (id={})",
token::get_ident(variant.node.name),
- map.path_to_str(id), id)).to_strbuf()
+ map.path_to_str(id), id)).to_string()
}
Some(NodeExpr(expr)) => {
(format!("expr {} (id={})",
- pprust::expr_to_str(expr), id)).to_strbuf()
+ pprust::expr_to_str(expr), id)).to_string()
}
Some(NodeStmt(stmt)) => {
(format!("stmt {} (id={})",
- pprust::stmt_to_str(stmt), id)).to_strbuf()
+ pprust::stmt_to_str(stmt), id)).to_string()
}
Some(NodeArg(pat)) => {
(format!("arg {} (id={})",
- pprust::pat_to_str(pat), id)).to_strbuf()
+ pprust::pat_to_str(pat), id)).to_string()
}
Some(NodeLocal(pat)) => {
(format!("local {} (id={})",
- pprust::pat_to_str(pat), id)).to_strbuf()
+ pprust::pat_to_str(pat), id)).to_string()
}
Some(NodePat(pat)) => {
- (format!("pat {} (id={})", pprust::pat_to_str(pat), id)).to_strbuf()
+ (format!("pat {} (id={})", pprust::pat_to_str(pat), id)).to_string()
}
Some(NodeBlock(block)) => {
(format!("block {} (id={})",
- pprust::block_to_str(block), id)).to_strbuf()
+ pprust::block_to_str(block), id)).to_string()
}
Some(NodeStructCtor(_)) => {
(format!("struct_ctor {} (id={})",
- map.path_to_str(id), id)).to_strbuf()
+ map.path_to_str(id), id)).to_string()
}
Some(NodeLifetime(ref l)) => {
(format!("lifetime {} (id={})",
- pprust::lifetime_to_str(*l), id)).to_strbuf()
+ pprust::lifetime_to_str(*l), id)).to_string()
}
None => {
- (format!("unknown node (id={})", id)).to_strbuf()
+ (format!("unknown node (id={})", id)).to_string()
}
}
}
pub fn path_name_i(idents: &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
- token::get_ident(*i).get().to_strbuf()
- }).collect::<Vec<String>>().connect("::").to_strbuf()
+ token::get_ident(*i).get().to_string()
+ }).collect::<Vec<String>>().connect("::").to_string()
}
// totally scary function: ignores all but the last element, should have
// cast to a u64 so we can correctly print INT64_MIN. All integral types
// are parsed as u64, so we wouldn't want to print an extra negative
// sign.
- Some(n) => format!("{}{}", n as u64, s).to_strbuf(),
- None => s.to_strbuf()
+ Some(n) => format!("{}{}", n as u64, s).to_string(),
+ None => s.to_string()
}
}
};
match val {
- Some(n) => format!("{}{}", n, s).to_strbuf(),
- None => s.to_strbuf()
+ Some(n) => format!("{}{}", n, s).to_string(),
+ None => s.to_string()
}
}
pub fn float_ty_to_str(t: FloatTy) -> String {
match t {
- TyF32 => "f32".to_strbuf(),
- TyF64 => "f64".to_strbuf(),
- TyF128 => "f128".to_strbuf(),
+ TyF32 => "f32".to_string(),
+ TyF64 => "f64".to_string(),
+ TyF128 => "f128".to_string(),
}
}
slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
after.iter().advance(|&p| walk_pat(p, |p| it(p)))
}
+ PatMac(_) => fail!("attempted to analyze unexpanded pattern"),
PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) => {
true
let begin = begin.to_uint();
let slice = self.src.as_slice().slice_from(begin);
match slice.find('\n') {
- Some(e) => slice.slice_to(e).to_strbuf(),
- None => slice.to_strbuf()
+ Some(e) => slice.slice_to(e).to_string(),
+ None => slice.to_string()
}
}
let filemap = Rc::new(FileMap {
name: filename,
- src: src.to_strbuf(),
+ src: src.to_string(),
start_pos: Pos::from_uint(start_pos),
lines: RefCell::new(Vec::new()),
multibyte_chars: RefCell::new(Vec::new()),
(format!("<{}:{}:{}>",
pos.file.name,
pos.line,
- pos.col.to_uint() + 1)).to_strbuf()
+ pos.col.to_uint() + 1)).to_string()
}
/// Lookup source information about a BytePos
pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
let loc = self.lookup_char_pos(pos);
LocWithOpt {
- filename: loc.file.name.to_strbuf(),
+ filename: loc.file.name.to_string(),
line: loc.line,
col: loc.col,
file: Some(loc.file)
pub fn span_to_str(&self, sp: Span) -> String {
if self.files.borrow().len() == 0 && sp == DUMMY_SP {
- return "no-location".to_strbuf();
+ return "no-location".to_string();
}
let lo = self.lookup_char_pos_adj(sp.lo);
lo.line,
lo.col.to_uint() + 1,
hi.line,
- hi.col.to_uint() + 1)).to_strbuf()
+ hi.col.to_uint() + 1)).to_string()
}
pub fn span_to_filename(&self, sp: Span) -> FileName {
- self.lookup_char_pos(sp.lo).file.name.to_strbuf()
+ self.lookup_char_pos(sp.lo).file.name.to_string()
}
pub fn span_to_lines(&self, sp: Span) -> FileLines {
None
} else {
Some(begin.fm.src.as_slice().slice(begin.pos.to_uint(),
- end.pos.to_uint()).to_strbuf())
+ end.pos.to_uint()).to_string())
}
}
#[test]
fn t1 () {
let cm = CodeMap::new();
- let fm = cm.new_filemap("blork.rs".to_strbuf(),
- "first line.\nsecond line".to_strbuf());
+ let fm = cm.new_filemap("blork.rs".to_string(),
+ "first line.\nsecond line".to_string());
fm.next_line(BytePos(0));
- assert_eq!(&fm.get_line(0),&"first line.".to_strbuf());
+ assert_eq!(&fm.get_line(0),&"first line.".to_string());
// TESTING BROKEN BEHAVIOR:
fm.next_line(BytePos(10));
- assert_eq!(&fm.get_line(1), &".".to_strbuf());
+ assert_eq!(&fm.get_line(1), &".".to_string());
}
#[test]
#[should_fail]
fn t2 () {
let cm = CodeMap::new();
- let fm = cm.new_filemap("blork.rs".to_strbuf(),
- "first line.\nsecond line".to_strbuf());
+ let fm = cm.new_filemap("blork.rs".to_string(),
+ "first line.\nsecond line".to_string());
// 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".to_strbuf(),
- "first line.\nsecond line".to_strbuf());
- let fm2 = cm.new_filemap("empty.rs".to_strbuf(),
- "".to_strbuf());
- let fm3 = cm.new_filemap("blork2.rs".to_strbuf(),
- "first line.\nsecond line".to_strbuf());
+ let fm1 = cm.new_filemap("blork.rs".to_string(),
+ "first line.\nsecond line".to_string());
+ let fm2 = cm.new_filemap("empty.rs".to_string(),
+ "".to_string());
+ let fm3 = cm.new_filemap("blork2.rs".to_string(),
+ "first line.\nsecond line".to_string());
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".to_strbuf());
+ assert_eq!(fmabp1.fm.name, "blork.rs".to_string());
assert_eq!(fmabp1.pos, BytePos(22));
let fmabp2 = cm.lookup_byte_offset(BytePos(24));
- assert_eq!(fmabp2.fm.name, "blork2.rs".to_strbuf());
+ assert_eq!(fmabp2.fm.name, "blork2.rs".to_string());
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".to_strbuf());
+ assert_eq!(loc1.file.name, "blork.rs".to_string());
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".to_strbuf());
+ assert_eq!(loc2.file.name, "blork2.rs".to_string());
assert_eq!(loc2.line, 1);
assert_eq!(loc2.col, CharPos(0));
}
let cm = CodeMap::new();
// € is a three byte utf8 char.
let fm1 =
- cm.new_filemap("blork.rs".to_strbuf(),
- "fir€st €€€€ line.\nsecond line".to_strbuf());
- let fm2 = cm.new_filemap("blork2.rs".to_strbuf(),
- "first line€€.\n€ second line".to_strbuf());
+ cm.new_filemap("blork.rs".to_string(),
+ "fir€st €€€€ line.\nsecond line".to_string());
+ let fm2 = cm.new_filemap("blork2.rs".to_string(),
+ "first line€€.\n€ second line".to_string());
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".to_strbuf());
+ assert_eq!(file_lines.file.name, "blork.rs".to_string());
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".to_strbuf()));
+ assert_eq!(snippet, Some("second line".to_string()));
}
#[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".to_strbuf());
+ assert_eq!(sstr, "blork.rs:2:1: 2:12".to_string());
}
}
impl FromStr for CrateId {
fn from_str(s: &str) -> Option<CrateId> {
let pieces: Vec<&str> = s.splitn('#', 1).collect();
- let path = pieces.get(0).to_owned();
+ let path = pieces.get(0).to_string();
if path.as_slice().starts_with("/") || path.as_slice().ends_with("/") ||
path.as_slice().starts_with(".") || path.is_empty() {
let inferred_name = *path_pieces.get(0);
let (name, version) = if pieces.len() == 1 {
- (inferred_name.to_strbuf(), None)
+ (inferred_name.to_string(), None)
} else {
let hash_pieces: Vec<&str> = pieces.get(1)
.splitn(':', 1)
};
let name = if !hash_name.is_empty() {
- hash_name.to_strbuf()
+ hash_name.to_string()
} else {
- inferred_name.to_strbuf()
+ inferred_name.to_string()
};
let version = if !hash_version.is_empty() {
if hash_version == "0.0" {
None
} else {
- Some(hash_version.to_strbuf())
+ Some(hash_version.to_string())
}
} else {
None
};
Some(CrateId {
- path: path.to_strbuf(),
+ path: path.to_string(),
name: name,
version: version,
})
}
pub fn short_name_with_version(&self) -> String {
- (format!("{}-{}", self.name, self.version_or_default())).to_strbuf()
+ (format!("{}-{}", self.name, self.version_or_default())).to_string()
}
pub fn matches(&self, other: &CrateId) -> bool {
#[test]
fn bare_name() {
let crateid: CrateId = from_str("foo").expect("valid crateid");
- assert_eq!(crateid.name, "foo".to_strbuf());
+ assert_eq!(crateid.name, "foo".to_string());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, "foo".to_strbuf());
+ assert_eq!(crateid.path, "foo".to_string());
}
#[test]
fn bare_name_single_char() {
let crateid: CrateId = from_str("f").expect("valid crateid");
- assert_eq!(crateid.name, "f".to_strbuf());
+ assert_eq!(crateid.name, "f".to_string());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, "f".to_strbuf());
+ assert_eq!(crateid.path, "f".to_string());
}
#[test]
#[test]
fn simple_path() {
let crateid: CrateId = from_str("example.com/foo/bar").expect("valid crateid");
- assert_eq!(crateid.name, "bar".to_strbuf());
+ assert_eq!(crateid.name, "bar".to_string());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, "example.com/foo/bar".to_strbuf());
+ assert_eq!(crateid.path, "example.com/foo/bar".to_string());
}
#[test]
fn simple_version() {
let crateid: CrateId = from_str("foo#1.0").expect("valid crateid");
- assert_eq!(crateid.name, "foo".to_strbuf());
- assert_eq!(crateid.version, Some("1.0".to_strbuf()));
- assert_eq!(crateid.path, "foo".to_strbuf());
+ assert_eq!(crateid.name, "foo".to_string());
+ assert_eq!(crateid.version, Some("1.0".to_string()));
+ assert_eq!(crateid.path, "foo".to_string());
}
#[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".to_strbuf());
- assert_eq!(crateid.version, Some("1.0".to_strbuf()));
- assert_eq!(crateid.path, "example.com/foo/bar".to_strbuf());
+ assert_eq!(crateid.name, "bar".to_string());
+ assert_eq!(crateid.version, Some("1.0".to_string()));
+ assert_eq!(crateid.path, "example.com/foo/bar".to_string());
}
#[test]
fn single_chars() {
let crateid: CrateId = from_str("a/b#1").expect("valid crateid");
- assert_eq!(crateid.name, "b".to_strbuf());
- assert_eq!(crateid.version, Some("1".to_strbuf()));
- assert_eq!(crateid.path, "a/b".to_strbuf());
+ assert_eq!(crateid.name, "b".to_string());
+ assert_eq!(crateid.version, Some("1".to_string()));
+ assert_eq!(crateid.path, "a/b".to_string());
}
#[test]
fn missing_version() {
let crateid: CrateId = from_str("foo#").expect("valid crateid");
- assert_eq!(crateid.name, "foo".to_strbuf());
+ assert_eq!(crateid.name, "foo".to_string());
assert_eq!(crateid.version, None);
- assert_eq!(crateid.path, "foo".to_strbuf());
+ assert_eq!(crateid.path, "foo".to_string());
}
#[test]
fn path_and_name() {
let crateid: CrateId = from_str("foo/rust-bar#bar:1.0").expect("valid crateid");
- assert_eq!(crateid.name, "bar".to_strbuf());
- assert_eq!(crateid.version, Some("1.0".to_strbuf()));
- assert_eq!(crateid.path, "foo/rust-bar".to_strbuf());
+ assert_eq!(crateid.name, "bar".to_string());
+ assert_eq!(crateid.version, Some("1.0".to_string()));
+ assert_eq!(crateid.path, "foo/rust-bar".to_string());
}
#[test]
fn empty_name() {
let crateid: CrateId = from_str("foo/bar#:1.0").expect("valid crateid");
- assert_eq!(crateid.name, "bar".to_strbuf());
- assert_eq!(crateid.version, Some("1.0".to_strbuf()));
- assert_eq!(crateid.path, "foo/bar".to_strbuf());
+ assert_eq!(crateid.name, "bar".to_string());
+ assert_eq!(crateid.version, Some("1.0".to_string()));
+ assert_eq!(crateid.path, "foo/bar".to_string());
}
let s;
match self.err_count.get() {
0u => return,
- 1u => s = "aborting due to previous error".to_strbuf(),
+ 1u => s = "aborting due to previous error".to_string(),
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
let ss = ei.callee
.span
.as_ref()
- .map_or("".to_strbuf(), |span| cm.span_to_str(*span));
+ .map_or("".to_string(), |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 = "".to_owned();
+ let mut cons = "".to_string();
let mut volatile = false;
let mut alignstack = false;
let mut dialect = ast::AsmAtt;
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
None
}
+ /// Create a pattern.
+ fn make_pat(&self) -> Option<@ast::Pat> {
+ None
+ }
/// Create a statement.
///
Some(self.e)
}
}
+/// A convenience type for macros that return a single pattern.
+pub struct MacPat {
+ p: @ast::Pat
+}
+impl MacPat {
+ pub fn new(p: @ast::Pat) -> Box<MacResult> {
+ box MacPat { p: p } as Box<MacResult>
+ }
+}
+impl MacResult for MacPat {
+ fn make_pat(&self) -> Option<@ast::Pat> {
+ Some(self.p)
+ }
+}
/// A convenience type for macros that return a single item.
pub struct MacItem {
i: @ast::Item
span: sp,
}
}
+
+ /// A plain dummy pattern.
+ pub fn raw_pat(sp: Span) -> @ast::Pat {
+ @ast::Pat {
+ id: ast::DUMMY_NODE_ID,
+ node: ast::PatWild,
+ span: sp,
+ }
+ }
}
impl MacResult for DummyResult {
fn make_expr(&self) -> Option<@ast::Expr> {
Some(DummyResult::raw_expr(self.span))
}
+ fn make_pat(&self) -> Option<@ast::Pat> {
+ Some(DummyResult::raw_pat(self.span))
+ }
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
if self.expr_only {
None
match tts[0] {
ast::TTTok(_, token::LIT_STR(ident))
| ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
- return Some(token::get_ident(ident).get().to_strbuf())
+ return Some(token::get_ident(ident).get().to_string())
}
_ => {
cx.span_err(sp,
init: Some(ex),
id: ast::DUMMY_NODE_ID,
span: sp,
+ source: ast::LocalLet,
};
let decl = respan(sp, ast::DeclLocal(local));
@respan(sp, ast::StmtDecl(@decl, ast::DUMMY_NODE_ID))
init: Some(ex),
id: ast::DUMMY_NODE_ID,
span: sp,
+ source: ast::LocalLet,
};
let decl = respan(sp, ast::DeclLocal(local));
@respan(sp, ast::StmtDecl(@decl, ast::DUMMY_NODE_ID))
fn decode(d: &D) -> Node {
d.read_struct("Node", 1, || {
Node {
- id: d.read_field("x".to_owned(), 0, || decode(d))
+ id: d.read_field("x".to_string(), 0, || decode(d))
}
})
}
fn decode(d: &D) -> spanned<T> {
d.read_rec(|| {
{
- node: d.read_field("node".to_owned(), 0, || decode(d)),
- span: d.read_field("span".to_owned(), 1, || decode(d)),
+ node: d.read_field("node".to_string(), 0, || decode(d)),
+ span: d.read_field("span".to_string(), 1, || decode(d)),
}
})
}
} else { // there are still matches to create
let current_match_str = if match_count == 0 {
- "__self".to_strbuf()
+ "__self".to_string()
} else {
format!("__arg_{}", match_count)
};
to_set.expn_info = Some(@codemap::ExpnInfo {
call_site: to_set,
callee: codemap::NameAndSpan {
- name: format!("deriving({})", trait_name).to_strbuf(),
+ name: format!("deriving({})", trait_name).to_string(),
format: codemap::MacroAttribute,
span: Some(self.span)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use ast::{P, Block, Crate, DeclLocal, ExprMac};
+use ast::{P, Block, Crate, DeclLocal, ExprMac, PatMac};
use ast::{Local, Ident, MacInvocTT};
use ast::{ItemMac, Mrk, Stmt, StmtDecl, StmtMac, StmtExpr, StmtSemi};
use ast::TokenTree;
fld.cx.bt_push(ExpnInfo {
call_site: e.span,
callee: NameAndSpan {
- name: extnamestr.get().to_strbuf(),
+ name: extnamestr.get().to_string(),
format: MacroBang,
span: exp_span,
},
None => {
fld.cx.span_err(
pth.span,
- format!("non-expr macro in expr pos: \
- {}",
+ format!("non-expression macro in expression position: {}",
extnamestr.get().as_slice()
).as_slice());
return DummyResult::raw_expr(e.span);
// ['<ident>:] loop {
// match i.next() {
// None => break,
- // Some(<src_pat>) => <src_loop_block>
+ // Some(mut value) => {
+ // let <src_pat> = value;
+ // <src_loop_block>
+ // }
// }
// }
// }
// }
+ //
+ // (The use of the `let` is to give better error messages
+ // when the pattern is refutable.)
let local_ident = token::gensym_ident("__i"); // FIXME #13573
let next_ident = fld.cx.ident_of("next");
fld.cx.arm(span, vec!(none_pat), break_expr)
};
- // `Some(<src_pat>) => <src_loop_block>`
+ // let <src_pat> = value;
+ let value_ident = token::gensym_ident("__value");
+ // this is careful to use src_pat.span so that error
+ // messages point exact at that.
+ let local = @ast::Local {
+ ty: fld.cx.ty_infer(src_pat.span),
+ pat: src_pat,
+ init: Some(fld.cx.expr_ident(src_pat.span, value_ident)),
+ id: ast::DUMMY_NODE_ID,
+ span: src_pat.span,
+ source: ast::LocalFor
+ };
+ let local = codemap::respan(src_pat.span, ast::DeclLocal(local));
+ let local = @codemap::respan(span, ast::StmtDecl(@local, ast::DUMMY_NODE_ID));
+
+ // { let ...; <src_loop_block> }
+ let block = fld.cx.block(span, vec![local],
+ Some(fld.cx.expr_block(src_loop_block)));
+
+ // `Some(mut value) => { ... }`
+ // Note the _'s in the name will stop any unused mutability warnings.
+ let value_pat = fld.cx.pat_ident_binding_mode(span, value_ident,
+ ast::BindByValue(ast::MutMutable));
let some_arm =
fld.cx.arm(span,
- vec!(fld.cx.pat_enum(span, some_path, vec!(src_pat))),
- fld.cx.expr_block(src_loop_block));
+ vec!(fld.cx.pat_enum(span, some_path, vec!(value_pat))),
+ fld.cx.expr_block(block));
// `match i.next() { ... }`
let match_expr = {
fld.cx.bt_push(ExpnInfo {
call_site: attr.span,
callee: NameAndSpan {
- name: mname.get().to_strbuf(),
+ name: mname.get().to_string(),
format: MacroAttribute,
span: None
}
fld.cx.bt_push(ExpnInfo {
call_site: attr.span,
callee: NameAndSpan {
- name: mname.get().to_strbuf(),
+ name: mname.get().to_string(),
format: MacroAttribute,
span: None,
}
fld.cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
- name: extnamestr.get().to_strbuf(),
+ name: extnamestr.get().to_string(),
format: MacroBang,
span: span
}
fld.cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
- name: extnamestr.get().to_strbuf(),
+ name: extnamestr.get().to_string(),
format: MacroBang,
span: span
}
}
None => {
fld.cx.span_err(pth.span,
- format!("expr macro in item position: {}",
+ format!("non-item macro in item position: {}",
extnamestr.get()).as_slice());
return SmallVector::zero();
}
_ => unreachable!()
};
let name = format!("<{} macros>", token::get_ident(crate_name));
- let name = name.to_strbuf();
+ let name = name.to_string();
for source in macros.iter() {
let item = parse::parse_item_from_source_str(name.clone(),
fld.cx.bt_push(ExpnInfo {
call_site: s.span,
callee: NameAndSpan {
- name: extnamestr.get().to_strbuf(),
+ name: extnamestr.get().to_string(),
format: MacroBang,
span: exp_span,
}
Some(stmt) => stmt,
None => {
fld.cx.span_err(pth.span,
- format!("non-stmt macro in stmt pos: {}",
+ format!("non-statement macro in statement position: {}",
extnamestr).as_slice());
return SmallVector::zero();
}
pat: pat,
init: init,
id: id,
- span: span
+ span: span,
+ source: source,
} = **local;
// expand the pat (it might contain exprs... #:(o)>
let expanded_pat = fld.fold_pat(pat);
init: new_init_opt,
id: id,
span: span,
+ source: source
};
SmallVector::one(@Spanned {
node: StmtDecl(@Spanned {
})
}
+pub fn expand_pat(p: @ast::Pat, fld: &mut MacroExpander) -> @ast::Pat {
+ let (pth, tts) = match p.node {
+ PatMac(ref mac) => {
+ match mac.node {
+ MacInvocTT(ref pth, ref tts, _) => {
+ (pth, (*tts).clone())
+ }
+ }
+ }
+ _ => return noop_fold_pat(p, fld),
+ };
+ if pth.segments.len() > 1u {
+ fld.cx.span_err(pth.span, "expected macro name without module separators");
+ return DummyResult::raw_pat(p.span);
+ }
+ let extname = pth.segments.get(0).identifier;
+ let extnamestr = token::get_ident(extname);
+ let marked_after = match fld.extsbox.find(&extname.name) {
+ None => {
+ fld.cx.span_err(pth.span,
+ format!("macro undefined: '{}!'",
+ extnamestr).as_slice());
+ // let compilation continue
+ return DummyResult::raw_pat(p.span);
+ }
+
+ Some(&NormalTT(ref expander, span)) => {
+ fld.cx.bt_push(ExpnInfo {
+ call_site: p.span,
+ callee: NameAndSpan {
+ name: extnamestr.get().to_string(),
+ format: MacroBang,
+ span: span
+ }
+ });
+
+ let fm = fresh_mark();
+ let marked_before = mark_tts(tts.as_slice(), fm);
+ let mac_span = original_span(fld.cx);
+ let expanded = match expander.expand(fld.cx,
+ mac_span.call_site,
+ marked_before.as_slice()).make_pat() {
+ Some(e) => e,
+ None => {
+ fld.cx.span_err(
+ pth.span,
+ format!(
+ "non-pattern macro in pattern position: {}",
+ extnamestr.get()
+ ).as_slice()
+ );
+ return DummyResult::raw_pat(p.span);
+ }
+ };
+
+ // mark after:
+ mark_pat(expanded,fm)
+ }
+ _ => {
+ fld.cx.span_err(p.span,
+ format!("{}! is not legal in pattern position",
+ extnamestr.get()).as_slice());
+ return DummyResult::raw_pat(p.span);
+ }
+ };
+
+ let fully_expanded =
+ fld.fold_pat(marked_after).node.clone();
+ fld.cx.bt_pop();
+
+ @ast::Pat {
+ id: ast::DUMMY_NODE_ID,
+ node: fully_expanded,
+ span: p.span,
+ }
+}
+
pub struct IdentRenamer<'a> {
renames: &'a mut RenameList,
}
expand_expr(expr, self)
}
+ fn fold_pat(&mut self, pat: @ast::Pat) -> @ast::Pat {
+ expand_pat(pat, self)
+ }
+
fn fold_item(&mut self, item: @ast::Item) -> SmallVector<@ast::Item> {
expand_item(item, self)
}
new_mark_folder(m).fold_expr(expr)
}
+// apply a given mark to the given pattern. Used following the expansion of a macro.
+fn mark_pat(pat: @ast::Pat, m: Mrk) -> @ast::Pat {
+ new_mark_folder(m).fold_pat(pat)
+}
+
// apply a given mark to the given stmt. Used following the expansion of a macro.
fn mark_stmt(expr: &ast::Stmt, m: Mrk) -> @ast::Stmt {
new_mark_folder(m).fold_stmt(expr)
#[should_fail]
#[test] fn macros_cant_escape_fns_test () {
let src = "fn bogus() {macro_rules! z (() => (3+4))}\
- fn inty() -> int { z!() }".to_strbuf();
+ fn inty() -> int { z!() }".to_string();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- "<test>".to_strbuf(),
+ "<test>".to_string(),
src,
Vec::new(), &sess);
// should fail:
#[should_fail]
#[test] fn macros_cant_escape_mods_test () {
let src = "mod foo {macro_rules! z (() => (3+4))}\
- fn inty() -> int { z!() }".to_strbuf();
+ fn inty() -> int { z!() }".to_string();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- "<test>".to_strbuf(),
+ "<test>".to_string(),
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!() }".to_strbuf();
+ fn inty() -> int { z!() }".to_string();
let sess = parse::new_parse_sess();
let crate_ast = parse::parse_crate_from_source_str(
- "<test>".to_strbuf(),
+ "<test>".to_string(),
src,
Vec::new(), &sess);
// should fail:
#[test] fn macro_tokens_should_match(){
expand_crate_str(
- "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_strbuf());
+ "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_string());
}
// renaming tests expand a crate and then check that the bindings match
let (teststr, bound_connections, bound_ident_check) = match *t {
(ref str,ref conns, bic) => (str.to_owned(), conns.clone(), bic)
};
- let cr = expand_crate_str(teststr.to_strbuf());
+ let cr = expand_crate_str(teststr.to_string());
// find the bindings:
let mut name_finder = new_name_finder(Vec::new());
visit::walk_crate(&mut name_finder,&cr,());
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_strbuf();
+".to_string();
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)})".to_strbuf());
+ "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
let mut pat_idents = new_name_finder(Vec::new());
pat_idents.visit_pat(pat, ());
assert_eq!(pat_idents.ident_accumulator,
continue
}
}
- order.push(name.to_strbuf());
- names.insert(name.to_strbuf(), e);
+ order.push(name.to_string());
+ names.insert(name.to_string(), e);
} else {
args.push(p.parse_expr());
}
Exact(i)
}
parse::ArgumentIs(i) => Exact(i),
- parse::ArgumentNamed(s) => Named(s.to_strbuf()),
+ parse::ArgumentNamed(s) => Named(s.to_string()),
};
// and finally the method being applied
match arg.method {
None => {
- let ty = Known(arg.format.ty.to_strbuf());
+ let ty = Known(arg.format.ty.to_string());
self.verify_arg_type(pos, ty);
}
Some(ref method) => { self.verify_method(pos, *method); }
self.verify_arg_type(Exact(i), Unsigned);
}
parse::CountIsName(s) => {
- self.verify_arg_type(Named(s.to_strbuf()), Unsigned);
+ self.verify_arg_type(Named(s.to_string()), Unsigned);
}
parse::CountIsNextParam => {
if self.check_positional_ok() {
Named(ref s) => self.name_types.get(s)
};
- let fmt_fn = match *ty {
+ let (krate, fmt_fn) = match *ty {
Known(ref tyname) => {
match tyname.as_slice() {
- "" => "secret_show",
- "?" => "secret_poly",
- "b" => "secret_bool",
- "c" => "secret_char",
- "d" | "i" => "secret_signed",
- "e" => "secret_lower_exp",
- "E" => "secret_upper_exp",
- "f" => "secret_float",
- "o" => "secret_octal",
- "p" => "secret_pointer",
- "s" => "secret_string",
- "t" => "secret_binary",
- "u" => "secret_unsigned",
- "x" => "secret_lower_hex",
- "X" => "secret_upper_hex",
+ "" => ("std", "secret_show"),
+ "?" => ("debug", "secret_poly"),
+ "b" => ("std", "secret_bool"),
+ "c" => ("std", "secret_char"),
+ "d" | "i" => ("std", "secret_signed"),
+ "e" => ("std", "secret_lower_exp"),
+ "E" => ("std", "secret_upper_exp"),
+ "f" => ("std", "secret_float"),
+ "o" => ("std", "secret_octal"),
+ "p" => ("std", "secret_pointer"),
+ "s" => ("std", "secret_string"),
+ "t" => ("std", "secret_binary"),
+ "u" => ("std", "secret_unsigned"),
+ "x" => ("std", "secret_lower_hex"),
+ "X" => ("std", "secret_upper_hex"),
_ => {
self.ecx
.span_err(sp,
format!("unknown format trait `{}`",
*tyname).as_slice());
- "dummy"
+ ("std", "dummy")
}
}
}
};
let format_fn = self.ecx.path_global(sp, vec!(
- self.ecx.ident_of("std"),
+ self.ecx.ident_of(krate),
self.ecx.ident_of("fmt"),
self.ecx.ident_of(fmt_fn)));
self.ecx.expr_call_global(sp, vec!(
impl ToSource for ast::Ident {
fn to_source(&self) -> String {
- get_ident(*self).get().to_strbuf()
+ get_ident(*self).get().to_string()
}
}
.map(|i| i.to_source())
.collect::<Vec<String>>()
.connect("\n\n")
- .to_strbuf()
+ .to_string()
}
}
.map(|i| i.to_source())
.collect::<Vec<String>>()
.connect(", ")
- .to_strbuf()
+ .to_string()
}
}
impl ToSource for () {
fn to_source(&self) -> String {
- "()".to_strbuf()
+ "()".to_string()
}
}
fn parse_item(&self, s: String) -> @ast::Item {
let res = parse::parse_item_from_source_str(
- "<quote expansion>".to_strbuf(),
+ "<quote expansion>".to_string(),
s,
self.cfg(),
self.parse_sess());
}
fn parse_stmt(&self, s: String) -> @ast::Stmt {
- parse::parse_stmt_from_source_str("<quote expansion>".to_strbuf(),
+ parse::parse_stmt_from_source_str("<quote expansion>".to_string(),
s,
self.cfg(),
Vec::new(),
}
fn parse_expr(&self, s: String) -> @ast::Expr {
- parse::parse_expr_from_source_str("<quote expansion>".to_strbuf(),
+ parse::parse_expr_from_source_str("<quote expansion>".to_string(),
s,
self.cfg(),
self.parse_sess())
}
fn parse_tts(&self, s: String) -> Vec<ast::TokenTree> {
- parse::parse_tts_from_source_str("<quote expansion>".to_strbuf(),
+ parse::parse_tts_from_source_str("<quote expansion>".to_string(),
s,
self.cfg(),
self.parse_sess())
LIT_INT(i, ity) => {
let s_ity = match ity {
- 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()
+ ast::TyI => "TyI".to_string(),
+ ast::TyI8 => "TyI8".to_string(),
+ ast::TyI16 => "TyI16".to_string(),
+ ast::TyI32 => "TyI32".to_string(),
+ ast::TyI64 => "TyI64".to_string()
};
let e_ity = cx.expr_ident(sp, id_ext(s_ity.as_slice()));
LIT_UINT(u, uty) => {
let s_uty = match uty {
- 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()
+ ast::TyU => "TyU".to_string(),
+ ast::TyU8 => "TyU8".to_string(),
+ ast::TyU16 => "TyU16".to_string(),
+ ast::TyU32 => "TyU32".to_string(),
+ ast::TyU64 => "TyU64".to_string()
};
let e_uty = cx.expr_ident(sp, id_ext(s_uty.as_slice()));
LIT_FLOAT(fident, fty) => {
let s_fty = match fty {
- ast::TyF32 => "TyF32".to_owned(),
- ast::TyF64 => "TyF64".to_owned(),
- ast::TyF128 => "TyF128".to_owned()
+ ast::TyF32 => "TyF32".to_string(),
+ ast::TyF64 => "TyF64".to_string(),
+ ast::TyF128 => "TyF128".to_string()
};
let e_fty = cx.expr_ident(sp, id_ext(s_fty.as_slice()));
cx_expr: @ast::Expr,
expr: @ast::Expr) -> @ast::Expr {
let uses = vec![ cx.view_use_glob(sp, ast::Inherited,
- ids_ext(vec!["syntax".to_strbuf(),
- "ext".to_strbuf(),
- "quote".to_strbuf(),
- "rt".to_strbuf()])) ];
+ ids_ext(vec!["syntax".to_string(),
+ "ext".to_string(),
+ "quote".to_string(),
+ "rt".to_string()])) ];
let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr);
base::check_zero_tts(cx, sp, tts, "module_path!");
let string = cx.mod_path()
.iter()
- .map(|x| token::get_ident(*x).get().to_strbuf())
+ .map(|x| token::get_ident(*x).get().to_string())
.collect::<Vec<String>>()
.connect("::");
base::MacExpr::new(cx.expr_str(
Some(src) => {
// Add this input file to the code map to make it available as
// dependency information
- let filename = file.display().to_str().to_strbuf();
+ let filename = file.display().to_str().to_string();
let interned = token::intern_and_get_ident(src);
- cx.codemap().new_filemap(filename, src.to_strbuf());
+ cx.codemap().new_filemap(filename, src.to_string());
base::MacExpr::new(cx.expr_str(sp, interned))
}
}
return Success(nameize(sess, ms, v.as_slice()));
} else if eof_eis.len() > 1u {
- return Error(sp, "ambiguity: multiple successful parses".to_strbuf());
+ return Error(sp, "ambiguity: multiple successful parses".to_string());
} else {
- return Failure(sp, "unexpected end of macro invocation".to_strbuf());
+ return Failure(sp, "unexpected end of macro invocation".to_string());
}
} else {
if (bb_eis.len() > 0u && next_eis.len() > 0u)
MatchNonterminal(bind, name, _) => {
(format!("{} ('{}')",
token::get_ident(name),
- token::get_ident(bind))).to_strbuf()
+ token::get_ident(bind))).to_string()
}
_ => fail!()
} }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
built-in NTs {} or {} other options.",
- nts, next_eis.len()).to_strbuf());
+ nts, next_eis.len()).to_string());
} else if bb_eis.len() == 0u && next_eis.len() == 0u {
return Failure(sp, format!("no rules expected the token `{}`",
- token::to_str(&tok)).to_strbuf());
+ token::to_str(&tok)).to_string());
} else if next_eis.len() > 0u {
/* Now process the next token */
while next_eis.len() > 0u {
self.ensure_complete_parse(true);
Some(ret)
}
+ fn make_pat(&self) -> Option<@ast::Pat> {
+ let ret = self.parser.borrow_mut().parse_pat();
+ self.ensure_complete_parse(false);
+ Some(ret)
+ }
fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
let mut ret = SmallVector::zero();
loop {
// 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".to_strbuf();
+ let mut best_fail_msg = "internal error: ran no matchers".to_string();
for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
match **lhs {
box MacroRulesDefiner {
def: RefCell::new(Some(MacroDef {
- name: token::get_ident(name).to_str().to_strbuf(),
+ name: token::get_ident(name).to_str().to_string(),
ext: NormalTT(exp, Some(sp))
}))
} as Box<MacResult>
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{}' has {} items, but '{}' has {}",
- l_n, l_len, r_n, r_len).to_strbuf())
+ l_n, l_len, r_n, r_len).to_string())
}
}
}
pat: self.fold_pat(l.pat),
init: l.init.map(|e| self.fold_expr(e)),
span: self.new_span(l.span),
+ source: l.source,
}
}
slice.map(|x| folder.fold_pat(x)),
after.iter().map(|x| folder.fold_pat(*x)).collect())
}
+ PatMac(ref mac) => PatMac(folder.fold_mac(mac)),
};
@Pat {
#[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}}".to_strbuf());
+ "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
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}}".to_strbuf());
+ "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
}
// even inside macro 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)+))} ".to_strbuf());
+ (g $(d $d $e)+))} ".to_string());
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)+)))".to_strbuf());
+ "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))".to_string());
}
}
#[phase(syntax, link)]
extern crate log;
extern crate fmt_macros;
+extern crate debug;
pub mod util {
pub mod interner;
if can_trim {
lines.iter().map(|line| {
- line.as_slice().slice(i + 1, line.len()).to_strbuf()
+ line.as_slice().slice(i + 1, line.len()).to_string()
}).collect()
} else {
lines
static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
for prefix in ONLINERS.iter() {
if comment.starts_with(*prefix) {
- return comment.slice_from(prefix.len()).to_strbuf();
+ return comment.slice_from(prefix.len()).to_string();
}
}
if comment.starts_with("/*") {
let lines = comment.slice(3u, comment.len() - 2u)
.lines_any()
- .map(|s| s.to_strbuf())
+ .map(|s| s.to_string())
.collect::<Vec<String> >();
let lines = vertical_trim(lines);
let lines = horizontal_trim(lines);
- return lines.connect("\n").to_strbuf();
+ return lines.connect("\n").to_string();
}
fail!("not a doc-comment: {}", comment);
let s1 = match all_whitespace(s.as_slice(), col) {
Some(col) => {
if col < len {
- s.as_slice().slice(col, len).to_strbuf()
+ s.as_slice().slice(col, len).to_string()
} else {
- "".to_strbuf()
+ "".to_string()
}
}
None => s,
srdr: &mut io::Reader)
-> (Vec<Comment>, Vec<Literal>) {
let src = srdr.read_to_end().unwrap();
- let src = str::from_utf8(src.as_slice()).unwrap().to_strbuf();
+ let src = str::from_utf8(src.as_slice()).unwrap().to_string();
let cm = CodeMap::new();
let filemap = cm.new_filemap(path, src);
let mut rdr = lexer::new_low_level_string_reader(span_diagnostic, filemap);
if token::is_lit(&tok) {
with_str_from(&rdr, bstart, |s| {
debug!("tok lit: {}", s);
- literals.push(Literal {lit: s.to_strbuf(), pos: sp.lo});
+ literals.push(Literal {lit: s.to_string(), pos: sp.lo});
})
} else {
debug!("tok: {}", token::to_str(&tok));
#[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".to_strbuf());
+ assert_eq!(stripped, " Test \n* Test\n Test".to_string());
}
#[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".to_strbuf());
+ assert_eq!(stripped, " Test\n Test".to_string());
}
#[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;".to_strbuf());
+ assert_eq!(stripped, " let a: *int;\n *a = 5;".to_string());
}
#[test] fn test_block_doc_comment_4() {
let comment = "/*******************\n test\n *********************/";
let stripped = strip_doc_comment_decoration(comment);
- assert_eq!(stripped, " test".to_strbuf());
+ assert_eq!(stripped, " test".to_string());
}
#[test] fn test_line_doc_comment() {
let stripped = strip_doc_comment_decoration("/// test");
- assert_eq!(stripped, " test".to_strbuf());
+ assert_eq!(stripped, " test".to_string());
let stripped = strip_doc_comment_decoration("///! test");
- assert_eq!(stripped, " test".to_strbuf());
+ assert_eq!(stripped, " test".to_string());
let stripped = strip_doc_comment_decoration("// test");
- assert_eq!(stripped, " test".to_strbuf());
+ assert_eq!(stripped, " test".to_string());
let stripped = strip_doc_comment_decoration("// test");
- assert_eq!(stripped, " test".to_strbuf());
+ assert_eq!(stripped, " test".to_string());
let stripped = strip_doc_comment_decoration("///test");
- assert_eq!(stripped, "test".to_strbuf());
+ assert_eq!(stripped, "test".to_string());
let stripped = strip_doc_comment_decoration("///!test");
- assert_eq!(stripped, "test".to_strbuf());
+ assert_eq!(stripped, "test".to_string());
let stripped = strip_doc_comment_decoration("//test");
- assert_eq!(stripped, "test".to_strbuf());
+ assert_eq!(stripped, "test".to_string());
}
}
fn fatal_span_char(rdr: &mut StringReader,
from_pos: BytePos, to_pos: BytePos,
m: &str, c: char) -> ! {
- let mut m = m.to_strbuf();
+ let mut m = m.to_string();
m.push_str(": ");
char::escape_default(c, |c| m.push_char(c));
fatal_span(rdr, from_pos, to_pos, m.as_slice());
}
fn err_span_char(rdr: &mut StringReader, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
- let mut m = m.to_strbuf();
+ let mut m = m.to_string();
m.push_str(": ");
char::escape_default(c, |c| m.push_char(c));
err_span(rdr, from_pos, to_pos, m.as_slice());
// report a lexical error spanning [`from_pos`, `to_pos`), appending the
// offending string to the error message
fn fatal_span_verbose(rdr: &mut StringReader, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
- let mut m = m.to_strbuf();
+ let mut m = m.to_string();
m.push_str(": ");
let from = byte_offset(rdr, from_pos).to_uint();
let to = byte_offset(rdr, to_pos).to_uint();
}
if num_str.len() == 0u {
err_span(rdr, start_bpos, rdr.last_pos, "no valid digits found for number");
- num_str = "1".to_strbuf();
+ num_str = "1".to_string();
}
let parsed = match from_str_radix::<u64>(num_str.as_slice(),
base as uint) {
} else {
if num_str.len() == 0u {
err_span(rdr, start_bpos, rdr.last_pos, "no valid digits found for number");
- num_str = "1".to_strbuf();
+ num_str = "1".to_string();
}
let parsed = match from_str_radix::<u64>(num_str.as_slice(),
base as uint) {
// open a string reader for the given string
fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
teststr: String) -> StringReader<'a> {
- let fm = span_handler.cm.new_filemap("zebra.rs".to_strbuf(), teststr);
+ let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
new_string_reader(span_handler, fm)
}
let span_handler = mk_sh();
let mut string_reader = setup(&span_handler,
"/* my source file */ \
- fn main() { println!(\"zebra\"); }\n".to_strbuf());
+ fn main() { println!(\"zebra\"); }\n".to_string());
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".to_strbuf()),
+ check_tokenization(setup(&mk_sh(), "a b".to_string()),
vec!(mk_ident("a",false),
mk_ident("b",false)));
}
#[test] fn dcparsing_2 () {
- check_tokenization(setup(&mk_sh(), "a::b".to_strbuf()),
+ check_tokenization(setup(&mk_sh(), "a::b".to_string()),
vec!(mk_ident("a",true),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn dcparsing_3 () {
- check_tokenization(setup(&mk_sh(), "a ::b".to_strbuf()),
+ check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
vec!(mk_ident("a",false),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn dcparsing_4 () {
- check_tokenization(setup(&mk_sh(), "a:: b".to_strbuf()),
+ check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
vec!(mk_ident("a",true),
token::MOD_SEP,
mk_ident("b",false)));
}
#[test] fn character_a() {
- assert_eq!(setup(&mk_sh(), "'a'".to_strbuf()).next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
token::LIT_CHAR('a'));
}
#[test] fn character_space() {
- assert_eq!(setup(&mk_sh(), "' '".to_strbuf()).next_token().tok,
+ assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
token::LIT_CHAR(' '));
}
#[test] fn character_escaped() {
- assert_eq!(setup(&mk_sh(), "'\\n'".to_strbuf()).next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
token::LIT_CHAR('\n'));
}
#[test] fn lifetime_name() {
- assert_eq!(setup(&mk_sh(), "'abc".to_strbuf()).next_token().tok,
+ assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
token::LIFETIME(token::str_to_ident("abc")));
}
#[test] fn raw_string() {
assert_eq!(setup(&mk_sh(),
- "r###\"\"#a\\b\x00c\"\"###".to_strbuf()).next_token()
+ "r###\"\"#a\\b\x00c\"\"###".to_string()).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'".to_strbuf()).next_token().tok,
+ "/* /* */ */'a'".to_string()).next_token().tok,
token::LIT_CHAR('a'));
}
};
match str::from_utf8(bytes.as_slice()) {
Some(s) => {
- return string_to_filemap(sess, s.to_strbuf(),
- path.as_str().unwrap().to_strbuf())
+ return string_to_filemap(sess, s.to_string(),
+ path.as_str().unwrap().to_string())
}
None => {
err(format!("{} is not UTF-8 encoded", path.display()).as_slice())
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
let _ = val.encode(&mut encoder);
- str::from_utf8(writer.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(writer.unwrap().as_slice()).unwrap().to_string()
}
// produce a codemap::span
}
#[test] fn path_exprs_1() {
- assert!(string_to_expr("a".to_strbuf()) ==
+ assert!(string_to_expr("a".to_string()) ==
@ast::Expr{
id: ast::DUMMY_NODE_ID,
node: ast::ExprPath(ast::Path {
}
#[test] fn path_exprs_2 () {
- assert!(string_to_expr("::a::b".to_strbuf()) ==
+ assert!(string_to_expr("::a::b".to_string()) ==
@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".to_strbuf());
+ string_to_expr("::abc::def::return".to_string());
}
// check the token-tree-ization of macros
#[test] fn string_to_tts_macro () {
- let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_strbuf());
+ let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
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; }".to_strbuf());
+ let tts = string_to_tts("fn a (b : int) { b; }".to_string());
assert_eq!(to_json_str(&tts),
"[\
{\
]\
]\
}\
-]".to_strbuf()
+]".to_string()
);
}
#[test] fn ret_expr() {
- assert!(string_to_expr("return d".to_strbuf()) ==
+ assert!(string_to_expr("return d".to_string()) ==
@ast::Expr{
id: ast::DUMMY_NODE_ID,
node:ast::ExprRet(Some(@ast::Expr{
}
#[test] fn parse_stmt_1 () {
- assert!(string_to_stmt("b;".to_strbuf()) ==
+ assert!(string_to_stmt("b;".to_string()) ==
@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".to_strbuf());
+ let mut parser = string_to_parser(&sess, "b".to_string());
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; }".to_strbuf()) ==
+ assert!(string_to_item("fn a (b : int) { b; }".to_string()) ==
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".to_strbuf());
- string_to_expr("a::z.froob(b,@(987+3))".to_strbuf());
+ string_to_expr("3 + 4".to_string());
+ string_to_expr("a::z.froob(b,@(987+3))".to_string());
}
#[test] fn attrs_fix_bug () {
fn wb() -> c_int { O_WRONLY as c_int }
let mut fflags: c_int = wb();
-}".to_strbuf());
+}".to_string());
}
}
use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
-use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local};
+use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local, LocalLet};
use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
let mut i = tokens.iter();
// This might be a sign we need a connect method on Iterator.
let b = i.next()
- .map_or("".to_strbuf(), |t| Parser::token_to_str(t));
+ .map_or("".to_string(), |t| Parser::token_to_str(t));
i.fold(b, |b,a| {
let mut b = b;
b.push_str("`, `");
pat = PatRange(start, end);
} else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
let name = self.parse_path(NoTypesAllowed).path;
- let sub;
- if self.eat(&token::AT) {
- // parse foo @ pat
- sub = Some(self.parse_pat());
+ if self.eat(&token::NOT) {
+ // macro invocation
+ let ket = token::close_delimiter_for(&self.token)
+ .unwrap_or_else(|| self.fatal("expected open delimiter"));
+ self.bump();
+
+ let tts = self.parse_seq_to_end(&ket,
+ seq_sep_none(),
+ |p| p.parse_token_tree());
+
+ let mac = MacInvocTT(name, tts, EMPTY_CTXT);
+ pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
} else {
- // or just foo
- sub = None;
+ let sub = if self.eat(&token::AT) {
+ // parse foo @ pat
+ Some(self.parse_pat())
+ } else {
+ // or just foo
+ None
+ };
+ pat = PatIdent(BindByValue(MutImmutable), name, sub);
}
- pat = PatIdent(BindByValue(MutImmutable), name, sub);
} else {
// parse an enum pat
let enum_path = self.parse_path(LifetimeAndTypesWithColons)
init: init,
id: ast::DUMMY_NODE_ID,
span: mk_sp(lo, self.last_span.hi),
+ source: LocalLet,
}
}
outer_attrs, "path") {
Some(d) => (dir_path.join(d), true),
None => {
- let mod_name = mod_string.get().to_owned();
+ let mod_name = mod_string.get().to_string();
let default_path_str = format!("{}.rs", mod_name);
let secondary_path_str = format!("{}/mod.rs", mod_name);
let default_path = dir_path.join(default_path_str.as_slice());
self.span_err(id_sp,
"cannot declare a new module at this location");
let this_module = match self.mod_path_stack.last() {
- Some(name) => name.get().to_strbuf(),
+ Some(name) => name.get().to_string(),
None => self.root_module_name.get_ref().clone(),
};
self.span_note(id_sp,
};
self.eval_src_mod_from_path(file_path, owns_directory,
- mod_string.get().to_strbuf(), id_sp)
+ mod_string.get().to_string(), id_sp)
}
fn eval_src_mod_from_path(&mut self,
pub fn binop_to_str(o: BinOp) -> String {
match o {
- PLUS => "+".to_strbuf(),
- MINUS => "-".to_strbuf(),
- STAR => "*".to_strbuf(),
- SLASH => "/".to_strbuf(),
- PERCENT => "%".to_strbuf(),
- CARET => "^".to_strbuf(),
- AND => "&".to_strbuf(),
- OR => "|".to_strbuf(),
- SHL => "<<".to_strbuf(),
- SHR => ">>".to_strbuf()
+ PLUS => "+".to_string(),
+ MINUS => "-".to_string(),
+ STAR => "*".to_string(),
+ SLASH => "/".to_string(),
+ PERCENT => "%".to_string(),
+ CARET => "^".to_string(),
+ AND => "&".to_string(),
+ OR => "|".to_string(),
+ SHL => "<<".to_string(),
+ SHR => ">>".to_string()
}
}
pub fn to_str(t: &Token) -> String {
match *t {
- EQ => "=".to_strbuf(),
- LT => "<".to_strbuf(),
- LE => "<=".to_strbuf(),
- EQEQ => "==".to_strbuf(),
- NE => "!=".to_strbuf(),
- GE => ">=".to_strbuf(),
- GT => ">".to_strbuf(),
- NOT => "!".to_strbuf(),
- TILDE => "~".to_strbuf(),
- OROR => "||".to_strbuf(),
- ANDAND => "&&".to_strbuf(),
+ EQ => "=".to_string(),
+ LT => "<".to_string(),
+ LE => "<=".to_string(),
+ EQEQ => "==".to_string(),
+ NE => "!=".to_string(),
+ GE => ">=".to_string(),
+ GT => ">".to_string(),
+ NOT => "!".to_string(),
+ TILDE => "~".to_string(),
+ OROR => "||".to_string(),
+ ANDAND => "&&".to_string(),
BINOP(op) => binop_to_str(op),
BINOPEQ(op) => {
let mut s = binop_to_str(op);
}
/* Structural symbols */
- AT => "@".to_strbuf(),
- DOT => ".".to_strbuf(),
- DOTDOT => "..".to_strbuf(),
- DOTDOTDOT => "...".to_strbuf(),
- COMMA => ",".to_strbuf(),
- SEMI => ";".to_strbuf(),
- COLON => ":".to_strbuf(),
- MOD_SEP => "::".to_strbuf(),
- RARROW => "->".to_strbuf(),
- LARROW => "<-".to_strbuf(),
- FAT_ARROW => "=>".to_strbuf(),
- LPAREN => "(".to_strbuf(),
- RPAREN => ")".to_strbuf(),
- LBRACKET => "[".to_strbuf(),
- RBRACKET => "]".to_strbuf(),
- LBRACE => "{".to_strbuf(),
- RBRACE => "}".to_strbuf(),
- POUND => "#".to_strbuf(),
- DOLLAR => "$".to_strbuf(),
+ AT => "@".to_string(),
+ DOT => ".".to_string(),
+ DOTDOT => "..".to_string(),
+ DOTDOTDOT => "...".to_string(),
+ COMMA => ",".to_string(),
+ SEMI => ";".to_string(),
+ COLON => ":".to_string(),
+ MOD_SEP => "::".to_string(),
+ RARROW => "->".to_string(),
+ LARROW => "<-".to_string(),
+ FAT_ARROW => "=>".to_string(),
+ LPAREN => "(".to_string(),
+ RPAREN => ")".to_string(),
+ LBRACKET => "[".to_string(),
+ RBRACKET => "]".to_string(),
+ LBRACE => "{".to_string(),
+ RBRACE => "}".to_string(),
+ POUND => "#".to_string(),
+ DOLLAR => "$".to_string(),
/* Literals */
LIT_CHAR(c) => {
ast_util::ForceSuffix),
LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u),
ast_util::ForceSuffix),
- LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str().to_strbuf() }
+ LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str().to_string() }
LIT_FLOAT(s, t) => {
let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body
}
LIT_STR(s) => {
- (format!("\"{}\"", get_ident(s).get().escape_default())).to_strbuf()
+ (format!("\"{}\"", get_ident(s).get().escape_default())).to_string()
}
LIT_STR_RAW(s, n) => {
(format!("r{delim}\"{string}\"{delim}",
- delim="#".repeat(n), string=get_ident(s))).to_strbuf()
+ delim="#".repeat(n), string=get_ident(s))).to_string()
}
/* Name components */
- IDENT(s, _) => get_ident(s).get().to_strbuf(),
+ IDENT(s, _) => get_ident(s).get().to_string(),
LIFETIME(s) => {
- (format!("'{}", get_ident(s))).to_strbuf()
+ (format!("'{}", get_ident(s))).to_string()
}
- UNDERSCORE => "_".to_strbuf(),
+ UNDERSCORE => "_".to_string(),
/* Other */
- DOC_COMMENT(s) => get_ident(s).get().to_strbuf(),
- EOF => "<eof>".to_strbuf(),
+ DOC_COMMENT(s) => get_ident(s).get().to_string(),
+ EOF => "<eof>".to_string(),
INTERPOLATED(ref nt) => {
match nt {
&NtExpr(e) => ::print::pprust::expr_to_str(e),
&NtMeta(e) => ::print::pprust::meta_item_to_str(e),
_ => {
- let mut s = "an interpolated ".to_strbuf();
+ let mut s = "an interpolated ".to_string();
match *nt {
NtItem(..) => s.push_str("item"),
NtBlock(..) => s.push_str("block"),
pub fn tok_str(t: Token) -> String {
match t {
- String(s, len) => return format!("STR({},{})", s, len).to_strbuf(),
- Break(_) => return "BREAK".to_strbuf(),
- Begin(_) => return "BEGIN".to_strbuf(),
- End => return "END".to_strbuf(),
- Eof => return "EOF".to_strbuf()
+ String(s, len) => return format!("STR({},{})", s, len).to_string(),
+ Break(_) => return "BREAK".to_string(),
+ Begin(_) => return "BEGIN".to_string(),
+ End => return "END".to_string(),
+ Eof => return "EOF".to_string()
}
}
i %= n;
}
s.push_char(']');
- return s.into_strbuf();
+ return s.into_string();
}
pub enum PrintStackBreak {
pub fn eof(p: &mut Printer) -> io::IoResult<()> { p.pretty_print(Eof) }
pub fn word(p: &mut Printer, wrd: &str) -> io::IoResult<()> {
- p.pretty_print(String(/* bad */ wrd.to_strbuf(), wrd.len() as int))
+ p.pretty_print(String(/* bad */ wrd.to_string(), wrd.len() as int))
}
pub fn huge_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> {
- p.pretty_print(String(/* bad */ wrd.to_strbuf(), SIZE_INFINITY))
+ p.pretty_print(String(/* bad */ wrd.to_string(), SIZE_INFINITY))
}
pub fn zero_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> {
- p.pretty_print(String(/* bad */ wrd.to_strbuf(), 0))
+ p.pretty_print(String(/* bad */ wrd.to_string(), 0))
}
pub fn spaces(p: &mut Printer, n: uint) -> io::IoResult<()> {
let result =
str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();
mem::forget(wr);
- result.to_strbuf()
+ result.to_string()
}
}
pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
match vis {
- ast::Public => format!("pub {}", s).to_strbuf(),
- ast::Inherited => s.to_strbuf()
+ ast::Public => format!("pub {}", s).to_string(),
+ ast::Inherited => s.to_string()
}
}
|s, &p| s.print_pat(p)));
try!(word(&mut self.s, "]"));
}
+ ast::PatMac(ref m) => try!(self.print_mac(m)),
}
self.ann.post(self, NodePat(pat))
}
let generics = ast_util::empty_generics();
assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
None, &generics),
- &"fn abba()".to_strbuf());
+ &"fn abba()".to_string());
}
#[test]
});
let varstr = variant_to_str(&var);
- assert_eq!(&varstr,&"pub principal_skinner".to_strbuf());
+ assert_eq!(&varstr,&"pub principal_skinner".to_string());
}
}
impl RcStr {
pub fn new(string: &str) -> RcStr {
RcStr {
- string: Rc::new(string.to_strbuf()),
+ string: Rc::new(string.to_string()),
}
}
}
pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> {
let ps = new_parse_sess();
filemap_to_tts(&ps,
- string_to_filemap(&ps, source_str, "bogofile".to_strbuf()))
+ string_to_filemap(&ps, source_str, "bogofile".to_string()))
}
// map string to parser (via tts)
pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
new_parser_from_source_str(ps,
Vec::new(),
- "bogofile".to_strbuf(),
+ "bogofile".to_string(),
source_str)
}
visitor.visit_pat(*postpattern, env.clone())
}
}
+ PatMac(ref macro) => visitor.visit_mac(macro, env),
}
}
cap = self.ti.strings.find_equiv(&("op"));
}
}
- let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_strbuf()), |op| {
+ let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |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".to_strbuf())
+ _ => return Err("a non-char was used with %c".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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".to_strbuf())
+ _ => return Err("a non-str was used with %l".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'+' => 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 +".to_strbuf())
+ _ => return Err("non-numbers on stack with +".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'-' => 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 -".to_strbuf())
+ _ => return Err("non-numbers on stack with -".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'*' => 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 *".to_strbuf())
+ _ => return Err("non-numbers on stack with *".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'/' => 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 /".to_strbuf())
+ _ => return Err("non-numbers on stack with /".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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 %".to_strbuf())
+ _ => return Err("non-numbers on stack with %".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'&' => 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 &".to_strbuf())
+ _ => return Err("non-numbers on stack with &".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'|' => 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 |".to_strbuf())
+ _ => return Err("non-numbers on stack with |".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'^' => 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 ^".to_strbuf())
+ _ => return Err("non-numbers on stack with ^".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'=' => 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 =".to_strbuf())
+ _ => return Err("non-numbers on stack with =".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'>' => 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 >".to_strbuf())
+ _ => return Err("non-numbers on stack with >".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'<' => 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 <".to_strbuf())
+ _ => return Err("non-numbers on stack with <".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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".to_strbuf())
+ _ => return Err("non-numbers on stack with logical and".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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".to_strbuf())
+ _ => return Err("non-numbers on stack with logical or".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'!' => 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".to_strbuf())
+ _ => return Err("non-number on stack with logical not".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'~' => if stack.len() > 0 {
match stack.pop().unwrap() {
Number(x) => stack.push(Number(!x)),
- _ => return Err("non-number on stack with %~".to_strbuf())
+ _ => return Err("non-number on stack with %~".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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".to_strbuf())
+ (_, _) => return Err("first two params not numbers with %i".to_string())
},
// 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".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
':'|'#'|' '|'.'|'0'..'9' => {
let mut flags = Flags::new();
let mut fstate = FormatStateFlags;
Number(0) => state = SeekIfElse(0),
Number(_) => (),
_ => return Err("non-number on stack \
- with conditional".to_strbuf())
+ with conditional".to_string())
}
- } else { return Err("stack is empty".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
'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".to_strbuf())
+ None => return Err("bad param number".to_string())
}].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".to_strbuf()) }
+ } else { return Err("stack is empty".to_string()) }
} 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".to_strbuf()) }
+ } else { return Err("stack is empty".to_string()) }
} else {
- return Err("bad variable name in %P".to_strbuf());
+ return Err("bad variable name in %P".to_string());
}
},
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".to_strbuf());
+ return Err("bad variable name in %g".to_string());
}
},
CharConstant => {
},
CharClose => {
if cur != '\'' {
- return Err("malformed character constant".to_strbuf());
+ return Err("malformed character constant".to_string());
}
},
IntConstant(i) => {
state = IntConstant(i*10 + (cur as int - '0' as int));
old_state = Nothing;
}
- _ => return Err("bad int constant".to_strbuf())
+ _ => return Err("bad int constant".to_string())
}
}
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".to_strbuf()) },
+ } else { return Err("stack is empty".to_string()) },
(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".to_strbuf()) }
+ if flags.width < old { return Err("format width overflow".to_string()) }
}
(FormatStateWidth,'.') => {
*fstate = FormatStatePrecision;
let old = flags.precision;
flags.precision = flags.precision * 10 + (cur as uint - '0' as uint);
if flags.precision < old {
- return Err("format precision overflow".to_strbuf())
+ return Err("format precision overflow".to_string())
}
}
- _ => return Err("invalid format specifier".to_strbuf())
+ _ => return Err("invalid format specifier".to_string())
}
}
SeekIfElse(level) => {
(FormatHex, _) => format!("{:x}", d).into_bytes(),
(FormatHEX, _) => format!("{:X}", d).into_bytes(),
(FormatString, _) => {
- return Err("non-number on stack with %s".to_strbuf())
+ return Err("non-number on stack with %s".to_string())
}
};
let mut s: Vec<u8> = s.move_iter().collect();
assert!(res.is_err(),
"Op {} succeeded incorrectly with 0 stack entries", *cap);
let p = if *cap == "%s" || *cap == "%l" {
- String("foo".to_strbuf())
+ String("foo".to_string())
} else {
Number(97)
};
let mut varstruct = Variables::new();
let vars = &mut varstruct;
assert_eq!(expand(bytes!("%p1%s%p2%2s%p3%2s%p4%.2s"),
- [String("foo".to_strbuf()),
- String("foo".to_strbuf()),
- String("f".to_strbuf()),
- String("foo".to_strbuf())], vars),
+ [String("foo".to_string()),
+ String("foo".to_string()),
+ String("f".to_string()),
+ String("foo".to_string())], vars),
Ok(bytes!("foofoo ffo").iter().map(|x| *x).collect()));
- assert_eq!(expand(bytes!("%p1%:-4.2s"), [String("foo".to_strbuf())], vars),
+ assert_eq!(expand(bytes!("%p1%:-4.2s"), [String("foo".to_string())], vars),
Ok(bytes!("fo ").iter().map(|x| *x).collect()));
assert_eq!(expand(bytes!("%p1%d%p1%.3d%p1%5d%p1%:+d"), [Number(1)], vars),
if (bools_bytes as uint) > boolnames.len() {
return Err("incompatible file: more booleans than \
- expected".to_strbuf());
+ expected".to_string());
}
if (numbers_count as uint) > numnames.len() {
return Err("incompatible file: more numbers than \
- expected".to_strbuf());
+ expected".to_string());
}
if (string_offsets_count as uint) > stringnames.len() {
return Err("incompatible file: more string offsets than \
- expected".to_strbuf());
+ expected".to_string());
}
// 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".to_strbuf()),
+ Some(s) => s.to_string(),
+ None => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.as_slice()
.split('|')
- .map(|s| s.to_strbuf())
+ .map(|s| s.to_string())
.collect();
try!(file.read_byte()); // consume NUL
for i in range(0, bools_bytes) {
let b = try!(file.read_byte());
if b == 1 {
- bools_map.insert(bnames[i as uint].to_strbuf(), true);
+ bools_map.insert(bnames[i as uint].to_string(), true);
}
}
}
for i in range(0, numbers_count) {
let n = try!(file.read_le_u16());
if n != 0xFFFF {
- numbers_map.insert(nnames[i as uint].to_strbuf(), n);
+ numbers_map.insert(nnames[i as uint].to_string(), n);
}
}
}
if string_table.len() != string_table_bytes as uint {
return Err("error: hit EOF before end of string \
- table".to_strbuf());
+ table".to_string());
}
for (i, v) in string_offsets.iter().enumerate() {
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
- string_map.insert(name.to_strbuf(), Vec::new());
+ string_map.insert(name.to_string(), Vec::new());
continue;
}
.iter().position(|&b| b == 0);
match nulpos {
Some(len) => {
- string_map.insert(name.to_strbuf(),
+ string_map.insert(name.to_string(),
Vec::from_slice(
string_table.slice(offset as uint,
offset as uint + len)))
},
None => {
return Err("invalid file: missing NUL in \
- string_table".to_strbuf());
+ string_table".to_string());
}
};
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
- strings.insert("sgr0".to_strbuf(), Vec::from_slice(bytes!("\x1b[0m")));
- strings.insert("bold".to_strbuf(), Vec::from_slice(bytes!("\x1b[1m")));
- strings.insert("setaf".to_strbuf(), Vec::from_slice(bytes!("\x1b[3%p1%dm")));
- strings.insert("setab".to_strbuf(), Vec::from_slice(bytes!("\x1b[4%p1%dm")));
+ strings.insert("sgr0".to_string(), Vec::from_slice(bytes!("\x1b[0m")));
+ strings.insert("bold".to_string(), Vec::from_slice(bytes!("\x1b[1m")));
+ strings.insert("setaf".to_string(), Vec::from_slice(bytes!("\x1b[3%p1%dm")));
+ strings.insert("setab".to_string(), Vec::from_slice(bytes!("\x1b[4%p1%dm")));
box TermInfo {
- names: vec!("cygwin".to_strbuf()), // msys is a fork of an older cygwin version
+ names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: HashMap::new(),
strings: strings
if i == "" {
dirs_to_search.push(Path::new("/usr/share/terminfo"));
} else {
- dirs_to_search.push(Path::new(i.to_strbuf()));
+ dirs_to_search.push(Path::new(i.to_string()));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
- p.as_str().unwrap().to_strbuf()
+ p.as_str().unwrap().to_string()
};
- assert!(x("screen") == "/usr/share/terminfo/s/screen".to_strbuf());
+ assert!(x("screen") == "/usr/share/terminfo/s/screen".to_string());
assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
- assert!(x("screen") == "/usr/share/terminfo/s/screen".to_strbuf());
+ assert!(x("screen") == "/usr/share/terminfo/s/screen".to_string());
unsetenv("TERMINFO_DIRS");
}
use std::num::Saturating;
let mut name = String::from_str(self.name.as_slice());
let fill = column_count.saturating_sub(name.len());
- let mut pad = String::from_owned_str(" ".repeat(fill));
+ let mut pad = " ".repeat(fill);
match align {
PadNone => name,
PadOnLeft => {
pub fn test_main_static_x(args: &[~str], tests: &[TestDescAndFn]) {
test_main_static(args.iter()
- .map(|x| x.to_strbuf())
+ .map(|x| x.to_string())
.collect::<Vec<_>>()
.as_slice(),
tests)
let matches =
match getopts::getopts(args_.as_slice(), optgroups().as_slice()) {
Ok(m) => m,
- Err(f) => return Some(Err(f.to_err_msg().to_strbuf()))
+ Err(f) => return Some(Err(f.to_err_msg().to_string()))
};
if matches.opt_present("h") { usage(args[0].as_slice()); return None; }
let save_metrics = save_metrics.map(|s| Path::new(s));
let test_shard = matches.opt_str("test-shard");
- let test_shard = opt_shard(test_shard.map(|x| x.to_strbuf()));
+ let test_shard = opt_shard(test_shard.map(|x| x.to_string()));
let mut nocapture = matches.opt_present("nocapture");
if !nocapture {
None => Ok(()),
Some(ref mut o) => {
let s = format!("{} {}\n", match *result {
- TrOk => "ok".to_strbuf(),
- TrFailed => "failed".to_strbuf(),
- TrIgnored => "ignored".to_strbuf(),
+ TrOk => "ok".to_string(),
+ TrFailed => "failed".to_string(),
+ TrIgnored => "ignored".to_string(),
TrMetrics(ref mm) => fmt_metrics(mm),
TrBench(ref bs) => fmt_bench_samples(bs)
}, test.name.as_slice());
v.value as f64,
v.noise as f64))
.collect();
- v.connect(", ").to_strbuf()
+ v.connect(", ").to_string()
}
pub fn fmt_bench_samples(bs: &BenchSamples) -> String {
let stdout = ChanWriter::new(tx.clone());
let stderr = ChanWriter::new(tx);
let mut task = TaskBuilder::new().named(match desc.name {
- DynTestName(ref name) => name.clone().to_owned(),
- StaticTestName(name) => name.to_owned(),
+ DynTestName(ref name) => name.clone().to_string(),
+ StaticTestName(name) => name.to_string(),
});
if nocapture {
drop((stdout, stderr));
impl ToJson for Metric {
fn to_json(&self) -> json::Json {
let mut map = box TreeMap::new();
- map.insert("value".to_strbuf(), json::Number(self.value));
- map.insert("noise".to_strbuf(), json::Number(self.noise));
+ map.insert("value".to_string(), json::Number(self.value));
+ map.insert("noise".to_string(), json::Number(self.noise));
json::Object(map)
}
}
// FIXME(pcwalton): Yuck.
let mut new_map = TreeMap::new();
for (ref key, ref value) in map.iter() {
- new_map.insert(key.to_strbuf(), (*value).clone());
+ new_map.insert(key.to_string(), (*value).clone());
}
new_map.to_json().to_pretty_writer(&mut file)
noise: noise
};
let MetricMap(ref mut map) = *self;
- map.insert(name.to_strbuf(), m);
+ map.insert(name.to_string(), m);
}
/// Attempt to "ratchet" an external metric file. This involves loading
#[test]
fn first_free_arg_should_be_a_filter() {
- let args = vec!("progname".to_strbuf(), "some_regex_filter".to_strbuf());
+ let args = vec!("progname".to_string(), "some_regex_filter".to_string());
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".to_strbuf(),
- "filter".to_strbuf(),
- "--ignored".to_strbuf());
+ let args = vec!("progname".to_string(),
+ "filter".to_string(),
+ "--ignored".to_string());
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().to_strbuf(),
- "1".to_strbuf());
+ assert_eq!(filtered.get(0).desc.name.to_str().to_string(),
+ "1".to_string());
assert!(filtered.get(0).desc.ignore == false);
}
opts.run_tests = true;
let names =
- vec!("sha1::test".to_strbuf(),
- "int::test_to_str".to_strbuf(),
- "int::test_pow".to_strbuf(),
- "test::do_not_run_ignored_tests".to_strbuf(),
- "test::ignored_tests_result_in_ignored".to_strbuf(),
- "test::first_free_arg_should_be_a_filter".to_strbuf(),
- "test::parse_ignored_flag".to_strbuf(),
- "test::filter_for_ignored_option".to_strbuf(),
- "test::sort_tests".to_strbuf());
+ vec!("sha1::test".to_string(),
+ "int::test_to_str".to_string(),
+ "int::test_pow".to_string(),
+ "test::do_not_run_ignored_tests".to_string(),
+ "test::ignored_tests_result_in_ignored".to_string(),
+ "test::first_free_arg_should_be_a_filter".to_string(),
+ "test::parse_ignored_flag".to_string(),
+ "test::filter_for_ignored_option".to_string(),
+ "test::sort_tests".to_string());
let tests =
{
fn testfn() { }
let filtered = filter_tests(&opts, tests);
let expected =
- vec!("int::test_pow".to_strbuf(),
- "int::test_to_str".to_strbuf(),
- "sha1::test".to_strbuf(),
- "test::do_not_run_ignored_tests".to_strbuf(),
- "test::filter_for_ignored_option".to_strbuf(),
- "test::first_free_arg_should_be_a_filter".to_strbuf(),
- "test::ignored_tests_result_in_ignored".to_strbuf(),
- "test::parse_ignored_flag".to_strbuf(),
- "test::sort_tests".to_strbuf());
+ vec!("int::test_pow".to_string(),
+ "int::test_to_str".to_string(),
+ "sha1::test".to_string(),
+ "test::do_not_run_ignored_tests".to_string(),
+ "test::filter_for_ignored_option".to_string(),
+ "test::first_free_arg_should_be_a_filter".to_string(),
+ "test::ignored_tests_result_in_ignored".to_string(),
+ "test::parse_ignored_flag".to_string(),
+ "test::sort_tests".to_string());
for (a, b) in expected.iter().zip(filtered.iter()) {
- assert!(*a == b.desc.name.to_str().to_strbuf());
+ assert!(*a == b.desc.name.to_str().to_string());
}
}
let tests = names.iter().map(|name| {
TestDescAndFn {
desc: TestDesc {
- name: DynTestName(name.to_strbuf()),
+ name: DynTestName(name.to_string()),
ignore: false,
should_fail: false
},
let diff1 = m2.compare_to_old(&m1, None);
- assert_eq!(*(diff1.find(&"in-both-noise".to_strbuf()).unwrap()), LikelyNoise);
- assert_eq!(*(diff1.find(&"in-first-noise".to_strbuf()).unwrap()), MetricRemoved);
- assert_eq!(*(diff1.find(&"in-second-noise".to_strbuf()).unwrap()), MetricAdded);
- assert_eq!(*(diff1.find(&"in-both-want-downwards-but-regressed".to_strbuf()).unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-noise".to_string()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff1.find(&"in-first-noise".to_string()).unwrap()), MetricRemoved);
+ assert_eq!(*(diff1.find(&"in-second-noise".to_string()).unwrap()), MetricAdded);
+ assert_eq!(*(diff1.find(&"in-both-want-downwards-but-regressed".to_string()).unwrap()),
Regression(100.0));
- assert_eq!(*(diff1.find(&"in-both-want-downwards-and-improved".to_strbuf()).unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-downwards-and-improved".to_string()).unwrap()),
Improvement(50.0));
- assert_eq!(*(diff1.find(&"in-both-want-upwards-but-regressed".to_strbuf()).unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-upwards-but-regressed".to_string()).unwrap()),
Regression(50.0));
- assert_eq!(*(diff1.find(&"in-both-want-upwards-and-improved".to_strbuf()).unwrap()),
+ assert_eq!(*(diff1.find(&"in-both-want-upwards-and-improved".to_string()).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".to_strbuf()).unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&"in-first-noise".to_strbuf()).unwrap()), MetricRemoved);
- assert_eq!(*(diff2.find(&"in-second-noise".to_strbuf()).unwrap()), MetricAdded);
- assert_eq!(*(diff2.find(&"in-both-want-downwards-but-regressed".to_strbuf()).unwrap()),
+ assert_eq!(*(diff2.find(&"in-both-noise".to_string()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"in-first-noise".to_string()).unwrap()), MetricRemoved);
+ assert_eq!(*(diff2.find(&"in-second-noise".to_string()).unwrap()), MetricAdded);
+ assert_eq!(*(diff2.find(&"in-both-want-downwards-but-regressed".to_string()).unwrap()),
LikelyNoise);
- assert_eq!(*(diff2.find(&"in-both-want-downwards-and-improved".to_strbuf()).unwrap()),
+ assert_eq!(*(diff2.find(&"in-both-want-downwards-and-improved".to_string()).unwrap()),
LikelyNoise);
- assert_eq!(*(diff2.find(&"in-both-want-upwards-but-regressed".to_strbuf()).unwrap()),
+ assert_eq!(*(diff2.find(&"in-both-want-upwards-but-regressed".to_string()).unwrap()),
LikelyNoise);
- assert_eq!(*(diff2.find(&"in-both-want-upwards-and-improved".to_strbuf()).unwrap()),
+ assert_eq!(*(diff2.find(&"in-both-want-upwards-and-improved".to_string()).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".to_strbuf()).unwrap()), Regression(10.0));
- assert_eq!(*(diff1.find(&"throughput".to_strbuf()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff1.find(&"runtime".to_string()).unwrap()), Regression(10.0));
+ assert_eq!(*(diff1.find(&"throughput".to_string()).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".to_strbuf()).unwrap()), Metric::new(1000.0, 2.0));
- assert_eq!(*(m3.find(&"throughput".to_strbuf()).unwrap()), Metric::new(50.0, 2.0));
+ assert_eq!(*(m3.find(&"runtime".to_string()).unwrap()), Metric::new(1000.0, 2.0));
+ assert_eq!(*(m3.find(&"throughput".to_string()).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".to_strbuf()).unwrap()), LikelyNoise);
- assert_eq!(*(diff2.find(&"throughput".to_strbuf()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"runtime".to_string()).unwrap()), LikelyNoise);
+ assert_eq!(*(diff2.find(&"throughput".to_string()).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".to_strbuf()).unwrap()), Metric::new(1100.0, 2.0));
- assert_eq!(*(m4.find(&"throughput".to_strbuf()).unwrap()), Metric::new(50.0, 2.0));
+ assert_eq!(*(m4.find(&"runtime".to_string()).unwrap()), Metric::new(1100.0, 2.0));
+ assert_eq!(*(m4.find(&"throughput".to_string()).unwrap()), Metric::new(50.0, 2.0));
}
}
use std::io::MemWriter;
let mut m = MemWriter::new();
write_boxplot(&mut m as &mut io::Writer, s, 30).unwrap();
- let out = str::from_utf8(m.unwrap().as_slice()).unwrap().to_strbuf();
+ let out = str::from_utf8(m.unwrap().as_slice()).unwrap().to_string();
assert_eq!(out, expected);
}
t(&Summary::new([-2.0, -1.0]),
- "-2 |[------******#*****---]| -1".to_strbuf());
+ "-2 |[------******#*****---]| -1".to_string());
t(&Summary::new([0.0, 2.0]),
- "0 |[-------*****#*******---]| 2".to_strbuf());
+ "0 |[-------*****#*******---]| 2".to_string());
t(&Summary::new([-2.0, 0.0]),
- "-2 |[------******#******---]| 0".to_strbuf());
+ "-2 |[------******#******---]| 0".to_string());
}
#[test]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
+#[cfg(test)] extern crate debug;
#[cfg(test)] #[phase(syntax, link)] extern crate log;
+
extern crate serialize;
extern crate libc;
#[cfg(target_os = "macos")]
-> Result<uint, String> {
match ch {
'A' => match match_strs(s, pos, [
- ("Sunday".to_strbuf(), 0_i32),
- ("Monday".to_strbuf(), 1_i32),
- ("Tuesday".to_strbuf(), 2_i32),
- ("Wednesday".to_strbuf(), 3_i32),
- ("Thursday".to_strbuf(), 4_i32),
- ("Friday".to_strbuf(), 5_i32),
- ("Saturday".to_strbuf(), 6_i32)
+ ("Sunday".to_string(), 0_i32),
+ ("Monday".to_string(), 1_i32),
+ ("Tuesday".to_string(), 2_i32),
+ ("Wednesday".to_string(), 3_i32),
+ ("Thursday".to_string(), 4_i32),
+ ("Friday".to_string(), 5_i32),
+ ("Saturday".to_string(), 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err("Invalid day".to_strbuf())
+ None => Err("Invalid day".to_string())
},
'a' => match match_strs(s, pos, [
- ("Sun".to_strbuf(), 0_i32),
- ("Mon".to_strbuf(), 1_i32),
- ("Tue".to_strbuf(), 2_i32),
- ("Wed".to_strbuf(), 3_i32),
- ("Thu".to_strbuf(), 4_i32),
- ("Fri".to_strbuf(), 5_i32),
- ("Sat".to_strbuf(), 6_i32)
+ ("Sun".to_string(), 0_i32),
+ ("Mon".to_string(), 1_i32),
+ ("Tue".to_string(), 2_i32),
+ ("Wed".to_string(), 3_i32),
+ ("Thu".to_string(), 4_i32),
+ ("Fri".to_string(), 5_i32),
+ ("Sat".to_string(), 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err("Invalid day".to_strbuf())
+ None => Err("Invalid day".to_string())
},
'B' => match match_strs(s, pos, [
- ("January".to_strbuf(), 0_i32),
- ("February".to_strbuf(), 1_i32),
- ("March".to_strbuf(), 2_i32),
- ("April".to_strbuf(), 3_i32),
- ("May".to_strbuf(), 4_i32),
- ("June".to_strbuf(), 5_i32),
- ("July".to_strbuf(), 6_i32),
- ("August".to_strbuf(), 7_i32),
- ("September".to_strbuf(), 8_i32),
- ("October".to_strbuf(), 9_i32),
- ("November".to_strbuf(), 10_i32),
- ("December".to_strbuf(), 11_i32)
+ ("January".to_string(), 0_i32),
+ ("February".to_string(), 1_i32),
+ ("March".to_string(), 2_i32),
+ ("April".to_string(), 3_i32),
+ ("May".to_string(), 4_i32),
+ ("June".to_string(), 5_i32),
+ ("July".to_string(), 6_i32),
+ ("August".to_string(), 7_i32),
+ ("September".to_string(), 8_i32),
+ ("October".to_string(), 9_i32),
+ ("November".to_string(), 10_i32),
+ ("December".to_string(), 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err("Invalid month".to_strbuf())
+ None => Err("Invalid month".to_string())
},
'b' | 'h' => match match_strs(s, pos, [
- ("Jan".to_strbuf(), 0_i32),
- ("Feb".to_strbuf(), 1_i32),
- ("Mar".to_strbuf(), 2_i32),
- ("Apr".to_strbuf(), 3_i32),
- ("May".to_strbuf(), 4_i32),
- ("Jun".to_strbuf(), 5_i32),
- ("Jul".to_strbuf(), 6_i32),
- ("Aug".to_strbuf(), 7_i32),
- ("Sep".to_strbuf(), 8_i32),
- ("Oct".to_strbuf(), 9_i32),
- ("Nov".to_strbuf(), 10_i32),
- ("Dec".to_strbuf(), 11_i32)
+ ("Jan".to_string(), 0_i32),
+ ("Feb".to_string(), 1_i32),
+ ("Mar".to_string(), 2_i32),
+ ("Apr".to_string(), 3_i32),
+ ("May".to_string(), 4_i32),
+ ("Jun".to_string(), 5_i32),
+ ("Jul".to_string(), 6_i32),
+ ("Aug".to_string(), 7_i32),
+ ("Sep".to_string(), 8_i32),
+ ("Oct".to_string(), 9_i32),
+ ("Nov".to_string(), 10_i32),
+ ("Dec".to_string(), 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err("Invalid month".to_strbuf())
+ None => Err("Invalid month".to_string())
},
'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".to_strbuf())
+ None => Err("Invalid year".to_string())
},
'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".to_strbuf())
+ None => Err("Invalid day of the month".to_string())
},
'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".to_strbuf())
+ None => Err("Invalid day of the month".to_string())
},
'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".to_strbuf())
+ None => Err("Invalid hour".to_string())
}
}
'I' => {
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
- None => Err("Invalid hour".to_strbuf())
+ None => Err("Invalid hour".to_string())
}
}
'j' => {
tm.tm_yday = v - 1_i32;
Ok(pos)
}
- None => Err("Invalid day of year".to_strbuf())
+ None => Err("Invalid day of year".to_string())
}
}
'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".to_strbuf())
+ None => Err("Invalid hour".to_string())
}
}
'l' => {
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
- None => Err("Invalid hour".to_strbuf())
+ None => Err("Invalid hour".to_string())
}
}
'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".to_strbuf())
+ None => Err("Invalid minute".to_string())
}
}
'm' => {
tm.tm_mon = v - 1_i32;
Ok(pos)
}
- None => Err("Invalid month".to_strbuf())
+ None => Err("Invalid month".to_string())
}
}
'n' => parse_char(s, pos, '\n'),
'P' => match match_strs(s, pos,
- [("am".to_strbuf(), 0_i32), ("pm".to_strbuf(), 12_i32)]) {
+ [("am".to_string(), 0_i32), ("pm".to_string(), 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err("Invalid hour".to_strbuf())
+ None => Err("Invalid hour".to_string())
},
'p' => match match_strs(s, pos,
- [("AM".to_strbuf(), 0_i32), ("PM".to_strbuf(), 12_i32)]) {
+ [("AM".to_string(), 0_i32), ("PM".to_string(), 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err("Invalid hour".to_strbuf())
+ None => Err("Invalid hour".to_string())
},
'R' => {
parse_type(s, pos, 'H', &mut *tm)
tm.tm_sec = v;
Ok(pos)
}
- None => Err("Invalid second".to_strbuf())
+ None => Err("Invalid second".to_string())
}
}
//'s' {}
tm.tm_wday = if v == 7 { 0 } else { v };
Ok(pos)
}
- None => Err("Invalid day of week".to_strbuf())
+ None => Err("Invalid day of week".to_string())
}
}
'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".to_strbuf())
+ None => Err("Invalid day of week".to_string())
}
}
'Y' => {
tm.tm_year = v - 1900_i32;
Ok(pos)
}
- None => Err("Invalid year".to_strbuf())
+ None => Err("Invalid year".to_string())
}
}
'y' => {
tm.tm_year = v;
Ok(pos)
}
- None => Err("Invalid year".to_strbuf())
+ None => Err("Invalid year".to_string())
}
}
'Z' => {
Ok(pos)
}
- None => Err("Invalid zone offset".to_strbuf())
+ None => Err("Invalid zone offset".to_string())
}
} else {
- Err("Invalid zone offset".to_strbuf())
+ Err("Invalid zone offset".to_string())
}
}
'%' => parse_char(s, pos, '%'),
};
let mut pos = 0u;
let len = s.len();
- let mut result = Err("Invalid time".to_strbuf());
+ let mut result = Err("Invalid time".to_string());
while pos < len {
let range = s.char_range_at(pos);
'G' => format_strbuf!("{}", year),
'g' => format_strbuf!("{:02d}", (year % 100 + 100) % 100),
'V' => format_strbuf!("{:02d}", days / 7 + 1),
- _ => "".to_strbuf()
+ _ => "".to_string()
}
}
};
match ch {
'A' => match tm.tm_wday as int {
- 0 => "Sunday".to_strbuf(),
- 1 => "Monday".to_strbuf(),
- 2 => "Tuesday".to_strbuf(),
- 3 => "Wednesday".to_strbuf(),
- 4 => "Thursday".to_strbuf(),
- 5 => "Friday".to_strbuf(),
- 6 => "Saturday".to_strbuf(),
+ 0 => "Sunday".to_string(),
+ 1 => "Monday".to_string(),
+ 2 => "Tuesday".to_string(),
+ 3 => "Wednesday".to_string(),
+ 4 => "Thursday".to_string(),
+ 5 => "Friday".to_string(),
+ 6 => "Saturday".to_string(),
_ => die()
},
'a' => match tm.tm_wday as int {
- 0 => "Sun".to_strbuf(),
- 1 => "Mon".to_strbuf(),
- 2 => "Tue".to_strbuf(),
- 3 => "Wed".to_strbuf(),
- 4 => "Thu".to_strbuf(),
- 5 => "Fri".to_strbuf(),
- 6 => "Sat".to_strbuf(),
+ 0 => "Sun".to_string(),
+ 1 => "Mon".to_string(),
+ 2 => "Tue".to_string(),
+ 3 => "Wed".to_string(),
+ 4 => "Thu".to_string(),
+ 5 => "Fri".to_string(),
+ 6 => "Sat".to_string(),
_ => die()
},
'B' => match tm.tm_mon as int {
- 0 => "January".to_strbuf(),
- 1 => "February".to_strbuf(),
- 2 => "March".to_strbuf(),
- 3 => "April".to_strbuf(),
- 4 => "May".to_strbuf(),
- 5 => "June".to_strbuf(),
- 6 => "July".to_strbuf(),
- 7 => "August".to_strbuf(),
- 8 => "September".to_strbuf(),
- 9 => "October".to_strbuf(),
- 10 => "November".to_strbuf(),
- 11 => "December".to_strbuf(),
+ 0 => "January".to_string(),
+ 1 => "February".to_string(),
+ 2 => "March".to_string(),
+ 3 => "April".to_string(),
+ 4 => "May".to_string(),
+ 5 => "June".to_string(),
+ 6 => "July".to_string(),
+ 7 => "August".to_string(),
+ 8 => "September".to_string(),
+ 9 => "October".to_string(),
+ 10 => "November".to_string(),
+ 11 => "December".to_string(),
_ => die()
},
'b' | 'h' => match tm.tm_mon as int {
- 0 => "Jan".to_strbuf(),
- 1 => "Feb".to_strbuf(),
- 2 => "Mar".to_strbuf(),
- 3 => "Apr".to_strbuf(),
- 4 => "May".to_strbuf(),
- 5 => "Jun".to_strbuf(),
- 6 => "Jul".to_strbuf(),
- 7 => "Aug".to_strbuf(),
- 8 => "Sep".to_strbuf(),
- 9 => "Oct".to_strbuf(),
- 10 => "Nov".to_strbuf(),
- 11 => "Dec".to_strbuf(),
+ 0 => "Jan".to_string(),
+ 1 => "Feb".to_string(),
+ 2 => "Mar".to_string(),
+ 3 => "Apr".to_string(),
+ 4 => "May".to_string(),
+ 5 => "Jun".to_string(),
+ 6 => "Jul".to_string(),
+ 7 => "Aug".to_string(),
+ 8 => "Sep".to_string(),
+ 9 => "Oct".to_string(),
+ 10 => "Nov".to_string(),
+ 11 => "Dec".to_string(),
_ => die()
},
'C' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) / 100),
}
'M' => format_strbuf!("{:02d}", tm.tm_min),
'm' => format_strbuf!("{:02d}", tm.tm_mon + 1),
- 'n' => "\n".to_strbuf(),
- 'P' => if (tm.tm_hour as int) < 12 { "am".to_strbuf() } else { "pm".to_strbuf() },
- 'p' => if (tm.tm_hour as int) < 12 { "AM".to_strbuf() } else { "PM".to_strbuf() },
+ 'n' => "\n".to_string(),
+ 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
+ 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
'R' => {
format_strbuf!("{}:{}",
parse_type('H', tm),
parse_type('M', tm),
parse_type('S', tm))
}
- 't' => "\t".to_strbuf(),
+ 't' => "\t".to_string(),
'U' => format_strbuf!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
'u' => {
let i = tm.tm_wday as int;
- (if i == 0 { 7 } else { i }).to_str().to_strbuf()
+ (if i == 0 { 7 } else { i }).to_str().to_string()
}
'V' => iso_week('V', tm),
'v' => {
format_strbuf!("{:02d}",
(tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
}
- 'w' => (tm.tm_wday as int).to_str().to_strbuf(),
- 'Y' => (tm.tm_year as int + 1900).to_str().to_strbuf(),
+ 'w' => (tm.tm_wday as int).to_str().to_string(),
+ 'Y' => (tm.tm_year as int + 1900).to_str().to_string(),
'y' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) % 100),
- 'Z' => "".to_strbuf(), // FIXME(pcwalton): Implement this.
+ 'Z' => "".to_string(), // FIXME(pcwalton): Implement this.
'z' => {
let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
format_strbuf!("{}{:02d}{:02d}", sign, h, m)
}
'+' => tm.rfc3339(),
- '%' => "%".to_strbuf(),
+ '%' => "%".to_string(),
_ => die()
}
}
}
}
- str::from_utf8(buf.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(buf.as_slice()).unwrap().to_string()
}
#[cfg(test)]
}
let format = "%a %b %e %T.%f %Y";
- assert_eq!(strptime("", format), Err("Invalid time".to_strbuf()));
+ assert_eq!(strptime("", format), Err("Invalid time".to_string()));
assert!(strptime("Fri Feb 13 15:31:30", format)
- == Err("Invalid time".to_strbuf()));
+ == Err("Invalid time".to_string()));
match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
Err(e) => fail!(e),
fn test(s: &str, format: &str) -> bool {
match strptime(s, format) {
- Ok(ref tm) => tm.strftime(format) == s.to_strbuf(),
+ Ok(ref tm) => tm.strftime(format) == s.to_string(),
Err(e) => fail!(e)
}
}
let days = [
- "Sunday".to_strbuf(),
- "Monday".to_strbuf(),
- "Tuesday".to_strbuf(),
- "Wednesday".to_strbuf(),
- "Thursday".to_strbuf(),
- "Friday".to_strbuf(),
- "Saturday".to_strbuf()
+ "Sunday".to_string(),
+ "Monday".to_string(),
+ "Tuesday".to_string(),
+ "Wednesday".to_string(),
+ "Thursday".to_string(),
+ "Friday".to_string(),
+ "Saturday".to_string()
];
for day in days.iter() {
assert!(test(day.as_slice(), "%A"));
}
let days = [
- "Sun".to_strbuf(),
- "Mon".to_strbuf(),
- "Tue".to_strbuf(),
- "Wed".to_strbuf(),
- "Thu".to_strbuf(),
- "Fri".to_strbuf(),
- "Sat".to_strbuf()
+ "Sun".to_string(),
+ "Mon".to_string(),
+ "Tue".to_string(),
+ "Wed".to_string(),
+ "Thu".to_string(),
+ "Fri".to_string(),
+ "Sat".to_string()
];
for day in days.iter() {
assert!(test(day.as_slice(), "%a"));
}
let months = [
- "January".to_strbuf(),
- "February".to_strbuf(),
- "March".to_strbuf(),
- "April".to_strbuf(),
- "May".to_strbuf(),
- "June".to_strbuf(),
- "July".to_strbuf(),
- "August".to_strbuf(),
- "September".to_strbuf(),
- "October".to_strbuf(),
- "November".to_strbuf(),
- "December".to_strbuf()
+ "January".to_string(),
+ "February".to_string(),
+ "March".to_string(),
+ "April".to_string(),
+ "May".to_string(),
+ "June".to_string(),
+ "July".to_string(),
+ "August".to_string(),
+ "September".to_string(),
+ "October".to_string(),
+ "November".to_string(),
+ "December".to_string()
];
for day in months.iter() {
assert!(test(day.as_slice(), "%B"));
}
let months = [
- "Jan".to_strbuf(),
- "Feb".to_strbuf(),
- "Mar".to_strbuf(),
- "Apr".to_strbuf(),
- "May".to_strbuf(),
- "Jun".to_strbuf(),
- "Jul".to_strbuf(),
- "Aug".to_strbuf(),
- "Sep".to_strbuf(),
- "Oct".to_strbuf(),
- "Nov".to_strbuf(),
- "Dec".to_strbuf()
+ "Jan".to_string(),
+ "Feb".to_string(),
+ "Mar".to_string(),
+ "Apr".to_string(),
+ "May".to_string(),
+ "Jun".to_string(),
+ "Jul".to_string(),
+ "Aug".to_string(),
+ "Sep".to_string(),
+ "Oct".to_string(),
+ "Nov".to_string(),
+ "Dec".to_string()
];
for day in months.iter() {
assert!(test(day.as_slice(), "%b"));
assert!(test("%", "%%"));
// Test for #7256
- assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_strbuf()))
+ assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
}
fn test_ctime() {
debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
- assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_strbuf());
- assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_strbuf());
+ assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
+ assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
}
fn test_strftime() {
let utc = at_utc(time);
let local = at(time);
- assert_eq!(local.strftime(""), "".to_strbuf());
- assert_eq!(local.strftime("%A"), "Friday".to_strbuf());
- assert_eq!(local.strftime("%a"), "Fri".to_strbuf());
- assert_eq!(local.strftime("%B"), "February".to_strbuf());
- assert_eq!(local.strftime("%b"), "Feb".to_strbuf());
- assert_eq!(local.strftime("%C"), "20".to_strbuf());
- assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_strbuf());
- assert_eq!(local.strftime("%D"), "02/13/09".to_strbuf());
- assert_eq!(local.strftime("%d"), "13".to_strbuf());
- assert_eq!(local.strftime("%e"), "13".to_strbuf());
- assert_eq!(local.strftime("%f"), "000054321".to_strbuf());
- assert_eq!(local.strftime("%F"), "2009-02-13".to_strbuf());
- assert_eq!(local.strftime("%G"), "2009".to_strbuf());
- assert_eq!(local.strftime("%g"), "09".to_strbuf());
- assert_eq!(local.strftime("%H"), "15".to_strbuf());
- assert_eq!(local.strftime("%I"), "03".to_strbuf());
- assert_eq!(local.strftime("%j"), "044".to_strbuf());
- assert_eq!(local.strftime("%k"), "15".to_strbuf());
- assert_eq!(local.strftime("%l"), " 3".to_strbuf());
- assert_eq!(local.strftime("%M"), "31".to_strbuf());
- assert_eq!(local.strftime("%m"), "02".to_strbuf());
- assert_eq!(local.strftime("%n"), "\n".to_strbuf());
- assert_eq!(local.strftime("%P"), "pm".to_strbuf());
- assert_eq!(local.strftime("%p"), "PM".to_strbuf());
- assert_eq!(local.strftime("%R"), "15:31".to_strbuf());
- assert_eq!(local.strftime("%r"), "03:31:30 PM".to_strbuf());
- assert_eq!(local.strftime("%S"), "30".to_strbuf());
- assert_eq!(local.strftime("%s"), "1234567890".to_strbuf());
- assert_eq!(local.strftime("%T"), "15:31:30".to_strbuf());
- assert_eq!(local.strftime("%t"), "\t".to_strbuf());
- assert_eq!(local.strftime("%U"), "06".to_strbuf());
- assert_eq!(local.strftime("%u"), "5".to_strbuf());
- assert_eq!(local.strftime("%V"), "07".to_strbuf());
- assert_eq!(local.strftime("%v"), "13-Feb-2009".to_strbuf());
- assert_eq!(local.strftime("%W"), "06".to_strbuf());
- assert_eq!(local.strftime("%w"), "5".to_strbuf());
- assert_eq!(local.strftime("%X"), "15:31:30".to_strbuf()); // FIXME (#2350): support locale
- assert_eq!(local.strftime("%x"), "02/13/09".to_strbuf()); // FIXME (#2350): support locale
- assert_eq!(local.strftime("%Y"), "2009".to_strbuf());
- assert_eq!(local.strftime("%y"), "09".to_strbuf());
- assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_strbuf());
- assert_eq!(local.strftime("%z"), "-0800".to_strbuf());
- assert_eq!(local.strftime("%%"), "%".to_strbuf());
-
- assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_strbuf());
- assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_strbuf());
- assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_strbuf());
-
- assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_strbuf());
- assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_strbuf());
- assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_strbuf());
- assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_strbuf());
+ assert_eq!(local.strftime(""), "".to_string());
+ assert_eq!(local.strftime("%A"), "Friday".to_string());
+ assert_eq!(local.strftime("%a"), "Fri".to_string());
+ assert_eq!(local.strftime("%B"), "February".to_string());
+ assert_eq!(local.strftime("%b"), "Feb".to_string());
+ assert_eq!(local.strftime("%C"), "20".to_string());
+ assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
+ assert_eq!(local.strftime("%D"), "02/13/09".to_string());
+ assert_eq!(local.strftime("%d"), "13".to_string());
+ assert_eq!(local.strftime("%e"), "13".to_string());
+ assert_eq!(local.strftime("%f"), "000054321".to_string());
+ assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
+ assert_eq!(local.strftime("%G"), "2009".to_string());
+ assert_eq!(local.strftime("%g"), "09".to_string());
+ assert_eq!(local.strftime("%H"), "15".to_string());
+ assert_eq!(local.strftime("%I"), "03".to_string());
+ assert_eq!(local.strftime("%j"), "044".to_string());
+ assert_eq!(local.strftime("%k"), "15".to_string());
+ assert_eq!(local.strftime("%l"), " 3".to_string());
+ assert_eq!(local.strftime("%M"), "31".to_string());
+ assert_eq!(local.strftime("%m"), "02".to_string());
+ assert_eq!(local.strftime("%n"), "\n".to_string());
+ assert_eq!(local.strftime("%P"), "pm".to_string());
+ assert_eq!(local.strftime("%p"), "PM".to_string());
+ assert_eq!(local.strftime("%R"), "15:31".to_string());
+ assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
+ assert_eq!(local.strftime("%S"), "30".to_string());
+ assert_eq!(local.strftime("%s"), "1234567890".to_string());
+ assert_eq!(local.strftime("%T"), "15:31:30".to_string());
+ assert_eq!(local.strftime("%t"), "\t".to_string());
+ assert_eq!(local.strftime("%U"), "06".to_string());
+ assert_eq!(local.strftime("%u"), "5".to_string());
+ assert_eq!(local.strftime("%V"), "07".to_string());
+ assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
+ assert_eq!(local.strftime("%W"), "06".to_string());
+ assert_eq!(local.strftime("%w"), "5".to_string());
+ assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
+ assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
+ assert_eq!(local.strftime("%Y"), "2009".to_string());
+ assert_eq!(local.strftime("%y"), "09".to_string());
+ assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
+ assert_eq!(local.strftime("%z"), "-0800".to_string());
+ assert_eq!(local.strftime("%%"), "%".to_string());
+
+ assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
+ assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
+ assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
+
+ assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
+ assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
+ assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
+ assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
}
fn test_timespec_eq_ord() {
/// ```rust
/// use url::{Url, UserInfo};
///
-/// let url = Url { scheme: "https".to_strbuf(),
-/// user: Some(UserInfo { user: "username".to_strbuf(), pass: None }),
-/// host: "example.com".to_strbuf(),
-/// port: Some("8080".to_strbuf()),
-/// path: "/foo/bar".to_strbuf(),
-/// query: vec!(("baz".to_strbuf(), "qux".to_strbuf())),
-/// fragment: Some("quz".to_strbuf()) };
+/// let url = Url { scheme: "https".to_string(),
+/// user: Some(UserInfo { user: "username".to_string(), pass: None }),
+/// host: "example.com".to_string(),
+/// port: Some("8080".to_string()),
+/// path: "/foo/bar".to_string(),
+/// query: vec!(("baz".to_string(), "qux".to_string())),
+/// fragment: Some("quz".to_string()) };
/// // https://username@example.com:8080/foo/bar?baz=qux#quz
/// ```
#[deriving(Clone, Eq, TotalEq)]
/// The path component of a URL, for example `/foo/bar`.
pub path: String,
/// The query component of a URL.
- /// `vec!(("baz".to_strbuf(), "qux".to_strbuf()))` represents the fragment
+ /// `vec!(("baz".to_string(), "qux".to_string()))` represents the fragment
/// `baz=qux` in the above example.
pub query: Query,
/// The fragment component, such as `quz`. Doesn't include the leading `#` character.
/// The path component of a URL, for example `/foo/bar`.
pub path: String,
/// The query component of a URL.
- /// `vec!(("baz".to_strbuf(), "qux".to_strbuf()))` represents the fragment
+ /// `vec!(("baz".to_string(), "qux".to_string()))` 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_strbuf(), "".to_strbuf());
+ return (s.slice(0, index).to_string(), "".to_string());
} else {
- return (s.slice(0, index).to_strbuf(),
- s.slice(index + mat, s.len()).to_strbuf());
+ return (s.slice(0, index).to_string(),
+ s.slice(index + mat, s.len()).to_string());
}
}
* # Example
*
* ```rust
- * let query = vec!(("title".to_strbuf(), "The Village".to_strbuf()),
- ("north".to_strbuf(), "52.91".to_strbuf()),
- ("west".to_strbuf(), "4.10".to_strbuf()));
+ * let query = vec!(("title".to_string(), "The Village".to_string()),
+ ("north".to_string(), "52.91".to_string()),
+ ("west".to_string(), "4.10".to_string()));
* println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10
* ```
*/
write!(&mut writer, "{}={}", encode_component(k.as_slice()),
encode_component(v.as_slice()));
}
- str::from_utf8_lossy(writer.unwrap().as_slice()).to_strbuf()
+ str::from_utf8_lossy(writer.unwrap().as_slice()).to_string()
}
/**
*
* let scheme = match get_scheme("https://example.com/") {
* Ok((sch, _)) => sch,
- * Err(_) => "(None)".to_strbuf(),
+ * Err(_) => "(None)".to_string(),
* };
* println!("Scheme in use: {}.", scheme); // Scheme in use: https.
* ```
'0' .. '9' | '+' | '-' | '.' => {
if i == 0 {
return Err("url: Scheme must begin with a \
- letter.".to_strbuf());
+ letter.".to_string());
}
continue;
}
':' => {
if i == 0 {
- return Err("url: Scheme cannot be empty.".to_strbuf());
+ return Err("url: Scheme cannot be empty.".to_string());
} else {
- return Ok((rawurl.slice(0,i).to_strbuf(),
- rawurl.slice(i+1,rawurl.len()).to_strbuf()));
+ return Ok((rawurl.slice(0,i).to_string(),
+ rawurl.slice(i+1,rawurl.len()).to_string()));
}
}
_ => {
- return Err("url: Invalid character in scheme.".to_strbuf());
+ return Err("url: Invalid character in scheme.".to_string());
}
}
};
- return Err("url: Scheme must be terminated with a colon.".to_strbuf());
+ return Err("url: Scheme must be terminated with a colon.".to_string());
}
#[deriving(Clone, Eq)]
Result<(Option<UserInfo>, String, Option<String>, String), String> {
if !rawurl.starts_with("//") {
// there is no authority.
- return Ok((None, "".to_strbuf(), None, rawurl.to_str().to_strbuf()));
+ return Ok((None, "".to_string(), None, rawurl.to_str().to_string()));
}
enum State {
let mut input = Digit; // most restricted, start here.
let mut userinfo = None;
- let mut host = "".to_strbuf();
+ let mut host = "".to_string();
let mut port = None;
let mut colon_count = 0;
// separators, don't change anything
}
_ => {
- return Err("Illegal character in authority".to_strbuf());
+ return Err("Illegal character in authority".to_string());
}
}
// multiple colons means ipv6 address.
if input == Unreserved {
return Err(
- "Illegal characters in IPv6 address.".to_strbuf());
+ "Illegal characters in IPv6 address.".to_string());
}
st = Ip6Host;
}
pos = i;
if input == Unreserved {
// must be port
- host = rawurl.slice(begin, i).to_strbuf();
+ host = rawurl.slice(begin, i).to_string();
st = InPort;
} else {
// can't be sure whether this is an ipv6 address or a port
Ip6Port => {
if input == Unreserved {
return Err("Illegal characters in \
- authority.".to_strbuf());
+ authority.".to_string());
}
st = Ip6Host;
}
Ip6Host => {
if colon_count > 7 {
- host = rawurl.slice(begin, i).to_strbuf();
+ host = rawurl.slice(begin, i).to_string();
pos = i;
st = InPort;
}
}
_ => {
- return Err("Invalid ':' in authority.".to_strbuf());
+ return Err("Invalid ':' in authority.".to_string());
}
}
input = Digit; // reset input class
colon_count = 0; // reset count
match st {
Start => {
- let user = rawurl.slice(begin, i).to_strbuf();
+ let user = rawurl.slice(begin, i).to_string();
userinfo = Some(UserInfo::new(user, None));
st = InHost;
}
PassHostPort => {
- let user = rawurl.slice(begin, pos).to_strbuf();
- let pass = rawurl.slice(pos+1, i).to_strbuf();
+ let user = rawurl.slice(begin, pos).to_string();
+ let pass = rawurl.slice(pos+1, i).to_string();
userinfo = Some(UserInfo::new(user, Some(pass)));
st = InHost;
}
_ => {
- return Err("Invalid '@' in authority.".to_strbuf());
+ return Err("Invalid '@' in authority.".to_string());
}
}
begin = i+1;
// finish up
match st {
Start => {
- host = rawurl.slice(begin, end).to_strbuf();
+ host = rawurl.slice(begin, end).to_string();
}
PassHostPort | Ip6Port => {
if input != Digit {
- return Err("Non-digit characters in port.".to_strbuf());
+ return Err("Non-digit characters in port.".to_string());
}
- host = rawurl.slice(begin, pos).to_strbuf();
- port = Some(rawurl.slice(pos+1, end).to_strbuf());
+ host = rawurl.slice(begin, pos).to_string();
+ port = Some(rawurl.slice(pos+1, end).to_string());
}
Ip6Host | InHost => {
- host = rawurl.slice(begin, end).to_strbuf();
+ host = rawurl.slice(begin, end).to_string();
}
InPort => {
if input != Digit {
- return Err("Non-digit characters in port.".to_strbuf());
+ return Err("Non-digit characters in port.".to_string());
}
- port = Some(rawurl.slice(pos+1, end).to_strbuf());
+ port = Some(rawurl.slice(pos+1, end).to_string());
}
}
- let rest = rawurl.slice(end, len).to_strbuf();
+ let rest = rawurl.slice(end, len).to_string();
return Ok((userinfo, host, port, rest));
}
end = i;
break;
}
- _ => return Err("Invalid character in path.".to_strbuf())
+ _ => return Err("Invalid character in path.".to_string())
}
}
if authority {
if end != 0 && !rawurl.starts_with("/") {
return Err("Non-empty path must begin with\
- '/' in presence of authority.".to_strbuf());
+ '/' in presence of authority.".to_string());
}
}
return Ok((decode_component(rawurl.slice(0, end)),
- rawurl.slice(end, len).to_strbuf()));
+ rawurl.slice(end, len).to_string()));
}
// returns the parsed query and the fragment, if present
#[test]
fn test_split_char_first() {
let (u,v) = split_char_first("hello, sweet world", ',');
- assert_eq!(u, "hello".to_strbuf());
- assert_eq!(v, " sweet world".to_strbuf());
+ assert_eq!(u, "hello".to_string());
+ assert_eq!(v, " sweet world".to_string());
let (u,v) = split_char_first("hello sweet world", ',');
- assert_eq!(u, "hello sweet world".to_strbuf());
- assert_eq!(v, "".to_strbuf());
+ assert_eq!(u, "hello sweet world".to_string());
+ assert_eq!(v, "".to_string());
}
#[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".to_strbuf(), Some("pass".to_strbuf()))));
- assert_eq!(h, "rust-lang.org".to_strbuf());
+ assert_eq!(u, Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
+ assert_eq!(h, "rust-lang.org".to_string());
assert!(p.is_none());
- assert_eq!(r, "/something".to_strbuf());
+ assert_eq!(r, "/something".to_string());
let (u, h, p, r) = get_authority(
"//rust-lang.org:8000?something").unwrap();
assert!(u.is_none());
- assert_eq!(h, "rust-lang.org".to_strbuf());
- assert_eq!(p, Some("8000".to_strbuf()));
- assert_eq!(r, "?something".to_strbuf());
+ assert_eq!(h, "rust-lang.org".to_string());
+ assert_eq!(p, Some("8000".to_string()));
+ assert_eq!(r, "?something".to_string());
let (u, h, p, r) = get_authority(
"//rust-lang.org#blah").unwrap();
assert!(u.is_none());
- assert_eq!(h, "rust-lang.org".to_strbuf());
+ assert_eq!(h, "rust-lang.org".to_string());
assert!(p.is_none());
- assert_eq!(r, "#blah".to_strbuf());
+ assert_eq!(r, "#blah".to_string());
// 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".to_strbuf());
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_string());
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".to_strbuf());
- assert_eq!(p, Some("8000".to_strbuf()));
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_string());
+ assert_eq!(p, Some("8000".to_string()));
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".to_strbuf(), Some("p".to_strbuf()))));
- assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_strbuf());
- assert_eq!(p, Some("8000".to_strbuf()));
+ assert_eq!(u, Some(UserInfo::new("us".to_string(), Some("p".to_string()))));
+ assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334".to_string());
+ assert_eq!(p, Some("8000".to_string()));
// 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, "".to_strbuf());
+ assert_eq!(h, "".to_string());
let (_, h, _, _) = get_authority("rust-lang.org").unwrap();
- assert_eq!(h, "".to_strbuf());
+ assert_eq!(h, "".to_string());
}
#[test]
fn test_get_path() {
let (p, r) = get_path("/something+%20orother", true).unwrap();
- assert_eq!(p, "/something+ orother".to_strbuf());
- assert_eq!(r, "".to_strbuf());
+ assert_eq!(p, "/something+ orother".to_string());
+ assert_eq!(r, "".to_string());
let (p, r) = get_path("test@email.com#fragment", false).unwrap();
- assert_eq!(p, "test@email.com".to_strbuf());
- assert_eq!(r, "#fragment".to_strbuf());
+ assert_eq!(p, "test@email.com".to_string());
+ assert_eq!(r, "#fragment".to_string());
let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap();
- assert_eq!(p, "/gen/:addr=".to_strbuf());
- assert_eq!(r, "?q=v".to_strbuf());
+ assert_eq!(p, "/gen/:addr=".to_string());
+ assert_eq!(r, "?q=v".to_string());
//failure cases
assert!(get_path("something?q", true).is_err());
let up = from_str(url);
let u = up.unwrap();
- assert_eq!(&u.scheme, &"http".to_strbuf());
- assert_eq!(&u.user, &Some(UserInfo::new("user".to_strbuf(), Some("pass".to_strbuf()))));
- assert_eq!(&u.host, &"rust-lang.org".to_strbuf());
- assert_eq!(&u.port, &Some("8080".to_strbuf()));
- assert_eq!(&u.path, &"/doc/~u".to_strbuf());
- assert_eq!(&u.query, &vec!(("s".to_strbuf(), "v".to_strbuf())));
- assert_eq!(&u.fragment, &Some("something".to_strbuf()));
+ assert_eq!(&u.scheme, &"http".to_string());
+ assert_eq!(&u.user, &Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
+ assert_eq!(&u.host, &"rust-lang.org".to_string());
+ assert_eq!(&u.port, &Some("8080".to_string()));
+ assert_eq!(&u.path, &"/doc/~u".to_string());
+ assert_eq!(&u.query, &vec!(("s".to_string(), "v".to_string())));
+ assert_eq!(&u.fragment, &Some("something".to_string()));
}
#[test]
let up = path_from_str(path);
let u = up.unwrap();
- assert_eq!(&u.path, &"/doc/~u".to_strbuf());
- assert_eq!(&u.query, &vec!(("s".to_strbuf(), "v".to_strbuf())));
- assert_eq!(&u.fragment, &Some("something".to_strbuf()));
+ assert_eq!(&u.path, &"/doc/~u".to_string());
+ assert_eq!(&u.query, &vec!(("s".to_string(), "v".to_string())));
+ assert_eq!(&u.fragment, &Some("something".to_string()));
}
#[test]
fn test_url_parse_host_slash() {
let urlstr = "http://0.42.42.42/";
let url = from_str(urlstr).unwrap();
- assert!(url.host == "0.42.42.42".to_strbuf());
- assert!(url.path == "/".to_strbuf());
+ assert!(url.host == "0.42.42.42".to_string());
+ assert!(url.path == "/".to_string());
}
#[test]
fn test_path_parse_host_slash() {
let pathstr = "/";
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == "/".to_strbuf());
+ assert!(path.path == "/".to_string());
}
#[test]
fn test_url_host_with_port() {
let urlstr = "scheme://host:1234";
let url = from_str(urlstr).unwrap();
- assert_eq!(&url.scheme, &"scheme".to_strbuf());
- assert_eq!(&url.host, &"host".to_strbuf());
- assert_eq!(&url.port, &Some("1234".to_strbuf()));
+ assert_eq!(&url.scheme, &"scheme".to_string());
+ assert_eq!(&url.host, &"host".to_string());
+ assert_eq!(&url.port, &Some("1234".to_string()));
// is empty path really correct? Other tests think so
- assert_eq!(&url.path, &"".to_strbuf());
+ assert_eq!(&url.path, &"".to_string());
let urlstr = "scheme://host:1234/";
let url = from_str(urlstr).unwrap();
- assert_eq!(&url.scheme, &"scheme".to_strbuf());
- assert_eq!(&url.host, &"host".to_strbuf());
- assert_eq!(&url.port, &Some("1234".to_strbuf()));
- assert_eq!(&url.path, &"/".to_strbuf());
+ assert_eq!(&url.scheme, &"scheme".to_string());
+ assert_eq!(&url.host, &"host".to_string());
+ assert_eq!(&url.port, &Some("1234".to_string()));
+ assert_eq!(&url.path, &"/".to_string());
}
#[test]
fn test_url_with_underscores() {
let urlstr = "http://dotcom.com/file_name.html";
let url = from_str(urlstr).unwrap();
- assert!(url.path == "/file_name.html".to_strbuf());
+ assert!(url.path == "/file_name.html".to_string());
}
#[test]
fn test_path_with_underscores() {
let pathstr = "/file_name.html";
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == "/file_name.html".to_strbuf());
+ assert!(path.path == "/file_name.html".to_string());
}
#[test]
fn test_url_with_dashes() {
let urlstr = "http://dotcom.com/file-name.html";
let url = from_str(urlstr).unwrap();
- assert!(url.path == "/file-name.html".to_strbuf());
+ assert!(url.path == "/file-name.html".to_string());
}
#[test]
fn test_path_with_dashes() {
let pathstr = "/file-name.html";
let path = path_from_str(pathstr).unwrap();
- assert!(path.path == "/file-name.html".to_strbuf());
+ assert!(path.path == "/file-name.html".to_string());
}
#[test]
fn test_url_component_encoding() {
let url = "http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B";
let u = from_str(url).unwrap();
- assert!(u.path == "/doc uments".to_strbuf());
- assert!(u.query == vec!(("ba%d ".to_strbuf(), "#&+".to_strbuf())));
+ assert!(u.path == "/doc uments".to_string());
+ assert!(u.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
}
#[test]
fn test_path_component_encoding() {
let path = "/doc%20uments?ba%25d%20=%23%26%2B";
let p = path_from_str(path).unwrap();
- assert!(p.path == "/doc uments".to_strbuf());
- assert!(p.query == vec!(("ba%d ".to_strbuf(), "#&+".to_strbuf())));
+ assert!(p.path == "/doc uments".to_string());
+ assert!(p.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
}
#[test]
#[test]
fn test_encode() {
- assert_eq!(encode(""), "".to_strbuf());
- assert_eq!(encode("http://example.com"), "http://example.com".to_strbuf());
- assert_eq!(encode("foo bar% baz"), "foo%20bar%25%20baz".to_strbuf());
- assert_eq!(encode(" "), "%20".to_strbuf());
- assert_eq!(encode("!"), "!".to_strbuf());
- assert_eq!(encode("\""), "\"".to_strbuf());
- assert_eq!(encode("#"), "#".to_strbuf());
- assert_eq!(encode("$"), "$".to_strbuf());
- assert_eq!(encode("%"), "%25".to_strbuf());
- assert_eq!(encode("&"), "&".to_strbuf());
- assert_eq!(encode("'"), "%27".to_strbuf());
- assert_eq!(encode("("), "(".to_strbuf());
- assert_eq!(encode(")"), ")".to_strbuf());
- assert_eq!(encode("*"), "*".to_strbuf());
- assert_eq!(encode("+"), "+".to_strbuf());
- assert_eq!(encode(","), ",".to_strbuf());
- assert_eq!(encode("/"), "/".to_strbuf());
- assert_eq!(encode(":"), ":".to_strbuf());
- assert_eq!(encode(";"), ";".to_strbuf());
- assert_eq!(encode("="), "=".to_strbuf());
- assert_eq!(encode("?"), "?".to_strbuf());
- assert_eq!(encode("@"), "@".to_strbuf());
- assert_eq!(encode("["), "[".to_strbuf());
- assert_eq!(encode("]"), "]".to_strbuf());
+ assert_eq!(encode(""), "".to_string());
+ assert_eq!(encode("http://example.com"), "http://example.com".to_string());
+ assert_eq!(encode("foo bar% baz"), "foo%20bar%25%20baz".to_string());
+ assert_eq!(encode(" "), "%20".to_string());
+ assert_eq!(encode("!"), "!".to_string());
+ assert_eq!(encode("\""), "\"".to_string());
+ assert_eq!(encode("#"), "#".to_string());
+ assert_eq!(encode("$"), "$".to_string());
+ assert_eq!(encode("%"), "%25".to_string());
+ assert_eq!(encode("&"), "&".to_string());
+ assert_eq!(encode("'"), "%27".to_string());
+ assert_eq!(encode("("), "(".to_string());
+ assert_eq!(encode(")"), ")".to_string());
+ assert_eq!(encode("*"), "*".to_string());
+ assert_eq!(encode("+"), "+".to_string());
+ assert_eq!(encode(","), ",".to_string());
+ assert_eq!(encode("/"), "/".to_string());
+ assert_eq!(encode(":"), ":".to_string());
+ assert_eq!(encode(";"), ";".to_string());
+ assert_eq!(encode("="), "=".to_string());
+ assert_eq!(encode("?"), "?".to_string());
+ assert_eq!(encode("@"), "@".to_string());
+ assert_eq!(encode("["), "[".to_string());
+ assert_eq!(encode("]"), "]".to_string());
}
#[test]
fn test_encode_component() {
- assert_eq!(encode_component(""), "".to_strbuf());
+ assert_eq!(encode_component(""), "".to_string());
assert!(encode_component("http://example.com") ==
- "http%3A%2F%2Fexample.com".to_strbuf());
+ "http%3A%2F%2Fexample.com".to_string());
assert!(encode_component("foo bar% baz") ==
- "foo%20bar%25%20baz".to_strbuf());
- assert_eq!(encode_component(" "), "%20".to_strbuf());
- assert_eq!(encode_component("!"), "%21".to_strbuf());
- assert_eq!(encode_component("#"), "%23".to_strbuf());
- assert_eq!(encode_component("$"), "%24".to_strbuf());
- assert_eq!(encode_component("%"), "%25".to_strbuf());
- assert_eq!(encode_component("&"), "%26".to_strbuf());
- assert_eq!(encode_component("'"), "%27".to_strbuf());
- assert_eq!(encode_component("("), "%28".to_strbuf());
- assert_eq!(encode_component(")"), "%29".to_strbuf());
- assert_eq!(encode_component("*"), "%2A".to_strbuf());
- assert_eq!(encode_component("+"), "%2B".to_strbuf());
- assert_eq!(encode_component(","), "%2C".to_strbuf());
- assert_eq!(encode_component("/"), "%2F".to_strbuf());
- assert_eq!(encode_component(":"), "%3A".to_strbuf());
- assert_eq!(encode_component(";"), "%3B".to_strbuf());
- assert_eq!(encode_component("="), "%3D".to_strbuf());
- assert_eq!(encode_component("?"), "%3F".to_strbuf());
- assert_eq!(encode_component("@"), "%40".to_strbuf());
- assert_eq!(encode_component("["), "%5B".to_strbuf());
- assert_eq!(encode_component("]"), "%5D".to_strbuf());
+ "foo%20bar%25%20baz".to_string());
+ assert_eq!(encode_component(" "), "%20".to_string());
+ assert_eq!(encode_component("!"), "%21".to_string());
+ assert_eq!(encode_component("#"), "%23".to_string());
+ assert_eq!(encode_component("$"), "%24".to_string());
+ assert_eq!(encode_component("%"), "%25".to_string());
+ assert_eq!(encode_component("&"), "%26".to_string());
+ assert_eq!(encode_component("'"), "%27".to_string());
+ assert_eq!(encode_component("("), "%28".to_string());
+ assert_eq!(encode_component(")"), "%29".to_string());
+ assert_eq!(encode_component("*"), "%2A".to_string());
+ assert_eq!(encode_component("+"), "%2B".to_string());
+ assert_eq!(encode_component(","), "%2C".to_string());
+ assert_eq!(encode_component("/"), "%2F".to_string());
+ assert_eq!(encode_component(":"), "%3A".to_string());
+ assert_eq!(encode_component(";"), "%3B".to_string());
+ assert_eq!(encode_component("="), "%3D".to_string());
+ assert_eq!(encode_component("?"), "%3F".to_string());
+ assert_eq!(encode_component("@"), "%40".to_string());
+ assert_eq!(encode_component("["), "%5B".to_string());
+ assert_eq!(encode_component("]"), "%5D".to_string());
}
#[test]
fn test_decode() {
- assert_eq!(decode(""), "".to_strbuf());
- assert_eq!(decode("abc/def 123"), "abc/def 123".to_strbuf());
- assert_eq!(decode("abc%2Fdef%20123"), "abc%2Fdef 123".to_strbuf());
- assert_eq!(decode("%20"), " ".to_strbuf());
- assert_eq!(decode("%21"), "%21".to_strbuf());
- assert_eq!(decode("%22"), "%22".to_strbuf());
- assert_eq!(decode("%23"), "%23".to_strbuf());
- assert_eq!(decode("%24"), "%24".to_strbuf());
- assert_eq!(decode("%25"), "%".to_strbuf());
- assert_eq!(decode("%26"), "%26".to_strbuf());
- assert_eq!(decode("%27"), "'".to_strbuf());
- assert_eq!(decode("%28"), "%28".to_strbuf());
- assert_eq!(decode("%29"), "%29".to_strbuf());
- assert_eq!(decode("%2A"), "%2A".to_strbuf());
- assert_eq!(decode("%2B"), "%2B".to_strbuf());
- assert_eq!(decode("%2C"), "%2C".to_strbuf());
- assert_eq!(decode("%2F"), "%2F".to_strbuf());
- assert_eq!(decode("%3A"), "%3A".to_strbuf());
- assert_eq!(decode("%3B"), "%3B".to_strbuf());
- assert_eq!(decode("%3D"), "%3D".to_strbuf());
- assert_eq!(decode("%3F"), "%3F".to_strbuf());
- assert_eq!(decode("%40"), "%40".to_strbuf());
- assert_eq!(decode("%5B"), "%5B".to_strbuf());
- assert_eq!(decode("%5D"), "%5D".to_strbuf());
+ assert_eq!(decode(""), "".to_string());
+ assert_eq!(decode("abc/def 123"), "abc/def 123".to_string());
+ assert_eq!(decode("abc%2Fdef%20123"), "abc%2Fdef 123".to_string());
+ assert_eq!(decode("%20"), " ".to_string());
+ assert_eq!(decode("%21"), "%21".to_string());
+ assert_eq!(decode("%22"), "%22".to_string());
+ assert_eq!(decode("%23"), "%23".to_string());
+ assert_eq!(decode("%24"), "%24".to_string());
+ assert_eq!(decode("%25"), "%".to_string());
+ assert_eq!(decode("%26"), "%26".to_string());
+ assert_eq!(decode("%27"), "'".to_string());
+ assert_eq!(decode("%28"), "%28".to_string());
+ assert_eq!(decode("%29"), "%29".to_string());
+ assert_eq!(decode("%2A"), "%2A".to_string());
+ assert_eq!(decode("%2B"), "%2B".to_string());
+ assert_eq!(decode("%2C"), "%2C".to_string());
+ assert_eq!(decode("%2F"), "%2F".to_string());
+ assert_eq!(decode("%3A"), "%3A".to_string());
+ assert_eq!(decode("%3B"), "%3B".to_string());
+ assert_eq!(decode("%3D"), "%3D".to_string());
+ assert_eq!(decode("%3F"), "%3F".to_string());
+ assert_eq!(decode("%40"), "%40".to_string());
+ assert_eq!(decode("%5B"), "%5B".to_string());
+ assert_eq!(decode("%5D"), "%5D".to_string());
}
#[test]
fn test_decode_component() {
- assert_eq!(decode_component(""), "".to_strbuf());
- assert_eq!(decode_component("abc/def 123"), "abc/def 123".to_strbuf());
- assert_eq!(decode_component("abc%2Fdef%20123"), "abc/def 123".to_strbuf());
- assert_eq!(decode_component("%20"), " ".to_strbuf());
- assert_eq!(decode_component("%21"), "!".to_strbuf());
- assert_eq!(decode_component("%22"), "\"".to_strbuf());
- assert_eq!(decode_component("%23"), "#".to_strbuf());
- assert_eq!(decode_component("%24"), "$".to_strbuf());
- assert_eq!(decode_component("%25"), "%".to_strbuf());
- assert_eq!(decode_component("%26"), "&".to_strbuf());
- assert_eq!(decode_component("%27"), "'".to_strbuf());
- assert_eq!(decode_component("%28"), "(".to_strbuf());
- assert_eq!(decode_component("%29"), ")".to_strbuf());
- assert_eq!(decode_component("%2A"), "*".to_strbuf());
- assert_eq!(decode_component("%2B"), "+".to_strbuf());
- assert_eq!(decode_component("%2C"), ",".to_strbuf());
- assert_eq!(decode_component("%2F"), "/".to_strbuf());
- assert_eq!(decode_component("%3A"), ":".to_strbuf());
- assert_eq!(decode_component("%3B"), ";".to_strbuf());
- assert_eq!(decode_component("%3D"), "=".to_strbuf());
- assert_eq!(decode_component("%3F"), "?".to_strbuf());
- assert_eq!(decode_component("%40"), "@".to_strbuf());
- assert_eq!(decode_component("%5B"), "[".to_strbuf());
- assert_eq!(decode_component("%5D"), "]".to_strbuf());
+ assert_eq!(decode_component(""), "".to_string());
+ assert_eq!(decode_component("abc/def 123"), "abc/def 123".to_string());
+ assert_eq!(decode_component("abc%2Fdef%20123"), "abc/def 123".to_string());
+ assert_eq!(decode_component("%20"), " ".to_string());
+ assert_eq!(decode_component("%21"), "!".to_string());
+ assert_eq!(decode_component("%22"), "\"".to_string());
+ assert_eq!(decode_component("%23"), "#".to_string());
+ assert_eq!(decode_component("%24"), "$".to_string());
+ assert_eq!(decode_component("%25"), "%".to_string());
+ assert_eq!(decode_component("%26"), "&".to_string());
+ assert_eq!(decode_component("%27"), "'".to_string());
+ assert_eq!(decode_component("%28"), "(".to_string());
+ assert_eq!(decode_component("%29"), ")".to_string());
+ assert_eq!(decode_component("%2A"), "*".to_string());
+ assert_eq!(decode_component("%2B"), "+".to_string());
+ assert_eq!(decode_component("%2C"), ",".to_string());
+ assert_eq!(decode_component("%2F"), "/".to_string());
+ assert_eq!(decode_component("%3A"), ":".to_string());
+ assert_eq!(decode_component("%3B"), ";".to_string());
+ assert_eq!(decode_component("%3D"), "=".to_string());
+ assert_eq!(decode_component("%3F"), "?".to_string());
+ assert_eq!(decode_component("%40"), "@".to_string());
+ assert_eq!(decode_component("%5B"), "[".to_string());
+ assert_eq!(decode_component("%5D"), "]".to_string());
}
#[test]
fn test_encode_form_urlencoded() {
let mut m = HashMap::new();
- assert_eq!(encode_form_urlencoded(&m), "".to_strbuf());
+ assert_eq!(encode_form_urlencoded(&m), "".to_string());
- m.insert("".to_strbuf(), vec!());
- m.insert("foo".to_strbuf(), vec!());
- assert_eq!(encode_form_urlencoded(&m), "".to_strbuf());
+ m.insert("".to_string(), vec!());
+ m.insert("foo".to_string(), vec!());
+ assert_eq!(encode_form_urlencoded(&m), "".to_string());
let mut m = HashMap::new();
- m.insert("foo".to_strbuf(), vec!("bar".to_strbuf(), "123".to_strbuf()));
- assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_strbuf());
+ m.insert("foo".to_string(), vec!("bar".to_string(), "123".to_string()));
+ assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_string());
let mut m = HashMap::new();
- m.insert("foo bar".to_strbuf(), vec!("abc".to_strbuf(), "12 = 34".to_strbuf()));
+ m.insert("foo bar".to_string(), vec!("abc".to_string(), "12 = 34".to_string()));
assert!(encode_form_urlencoded(&m) ==
- "foo+bar=abc&foo+bar=12+%3D+34".to_strbuf());
+ "foo+bar=abc&foo+bar=12+%3D+34".to_string());
}
#[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".to_strbuf()), &vec!("1".to_strbuf()));
- assert_eq!(form.get(&"foo bar".to_strbuf()),
- &vec!("abc".to_strbuf(), "12 = 34".to_strbuf()));
+ assert_eq!(form.get(&"a".to_string()), &vec!("1".to_string()));
+ assert_eq!(form.get(&"foo bar".to_string()),
+ &vec!("abc".to_string(), "12 = 34".to_string()));
}
}
*s.get_mut(i*2+0) = digit.as_slice()[0];
*s.get_mut(i*2+1) = digit.as_slice()[1];
}
- str::from_utf8(s.as_slice()).unwrap().to_strbuf()
+ str::from_utf8(s.as_slice()).unwrap().to_string()
}
/// Returns a string of hexadecimal digits, separated into groups with a hyphen.
let u = Uuid::from_fields(d1, d2, d3, d4.as_slice());
- let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_strbuf();
+ let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string();
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".to_strbuf();
+ let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string();
assert!(u.to_simple_str() == expected);
}
impl WorkKey {
pub fn new(kind: &str, name: &str) -> WorkKey {
WorkKey {
- kind: kind.to_strbuf(),
- name: name.to_strbuf(),
+ kind: kind.to_string(),
+ name: name.to_string(),
}
}
}
// FIXME(pcwalton): Yuck.
let mut new_db_cache = TreeMap::new();
for (ref k, ref v) in self.db_cache.iter() {
- new_db_cache.insert((*k).to_strbuf(), (*v).to_strbuf());
+ new_db_cache.insert((*k).to_string(), (*v).to_string());
}
new_db_cache.to_json().to_pretty_writer(&mut f)
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
let _ = t.encode(&mut encoder);
- str::from_utf8(writer.unwrap().as_slice()).unwrap().to_strbuf()
+ str::from_utf8(writer.unwrap().as_slice()).unwrap().to_string()
}
// FIXME(#5121)
dependency_val: &str) {
debug!("Discovering input {} {} {}", dependency_kind, dependency_name, dependency_val);
self.discovered_inputs.insert_work_key(WorkKey::new(dependency_kind, dependency_name),
- dependency_val.to_strbuf());
+ dependency_val.to_string());
}
pub fn discover_output(&mut self,
dependency_kind: &str,
dependency_val: &str) {
debug!("Discovering output {} {} {}", dependency_kind, dependency_name, dependency_val);
self.discovered_outputs.insert_work_key(WorkKey::new(dependency_kind, dependency_name),
- dependency_val.to_strbuf());
+ dependency_val.to_string());
}
// returns pairs of (kind, name)
pub fn declare_input(&mut self, kind: &str, name: &str, val: &str) {
debug!("Declaring input {} {} {}", kind, name, val);
self.declared_inputs.insert_work_key(WorkKey::new(kind, name),
- val.to_strbuf());
+ val.to_string());
}
fn is_fresh(&self, cat: &str, kind: &str, name: &str, val: &str) -> bool {
- let k = kind.to_strbuf();
+ let k = kind.to_string();
let f = self.ctxt.freshness.deref().find(&k);
debug!("freshness for: {}/{}/{}/{}", cat, kind, name, val)
let fresh = match f {
&'a self, blk: proc(&mut Exec):Send -> T) -> Work<'a, T> {
let mut bo = Some(blk);
- debug!("exec_work: looking up {} and {:?}", self.fn_name,
- self.declared_inputs);
+ debug!("exec_work: looking up {}", self.fn_name);
let cached = {
let db = self.ctxt.db.deref().read();
db.deref().prepare(self.fn_name, &self.declared_inputs)
self.all_fresh("discovered input", disc_in) &&
self.all_fresh("discovered output", disc_out) => {
debug!("Cache hit!");
- debug!("Trying to decode: {:?} / {:?} / {}",
- disc_in, disc_out, *res);
+ debug!("Trying to decode: {}", *res);
Work::from_value(json_decode(res.as_slice()))
}
return pth;
}
- let pth = make_path("foo.c".to_strbuf());
+ let pth = make_path("foo.c".to_string());
File::create(&pth).write(bytes!("int main() { return 0; }")).unwrap();
- let db_path = make_path("db.json".to_strbuf());
+ let db_path = make_path("db.json".to_string());
let cx = Context::new(Arc::new(RWLock::new(Database::new(db_path))),
Arc::new(TreeMap::new()));
let contents = File::open(&pth).read_to_end().unwrap();
let file_content = from_utf8(contents.as_slice()).unwrap()
- .to_strbuf();
+ .to_string();
// FIXME (#9639): This needs to handle non-utf8 paths
prep.declare_input("file",
pth.as_str().unwrap(),
file_content.as_slice());
prep.exec(proc(_exe) {
- let out = make_path("foo.o".to_strbuf());
+ let out = make_path("foo.o".to_string());
let compiler = if cfg!(windows) {"gcc"} else {"cc"};
Command::new(compiler).arg(pth).arg("-o").arg(out.clone()).status().unwrap();
// Could run sub-rules inside here.
// FIXME (#9639): This needs to handle non-utf8 paths
- out.as_str().unwrap().to_strbuf()
+ out.as_str().unwrap().to_string()
})
});
pub struct NameVal { pub name: String, pub val: int }
pub fn struct_nameval() -> NameVal {
- NameVal { name: "crateresolve5".to_strbuf(), val: 10 }
+ NameVal { name: "crateresolve5".to_string(), val: 10 }
}
pub enum e {
pub struct NameVal { pub name: String, pub val: int }
pub fn struct_nameval() -> NameVal {
- NameVal { name: "crateresolve5".to_strbuf(), val: 10 }
+ NameVal { name: "crateresolve5".to_string(), val: 10 }
}
pub enum e {
// Make sure Rust generates the correct calling convention for extern
// functions.
+extern crate debug;
+
#[inline(never)]
#[cfg(target_arch = "x86_64")]
pub extern "win64" fn foo(a: int, b: int, c: int, d: int) {
// the unused ty param is necessary so this gets monomorphized
pub fn request<T>(req: &header_map) {
- let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
+ let _x = (**((**req.get(&"METHOD".to_string())).clone()).borrow()
.clone()
.get(0)).clone();
}
#![feature(phase)]
#[phase(syntax, link)] extern crate log;
+extern crate debug;
pub fn foo<T>() {
fn death() -> int { fail!() }
impl Bort {
pub fn bort() -> String {
- "bort()".to_strbuf()
+ "bort()".to_string()
}
}
}
let mut set = f();
timed(&mut self.sequential_strings, || {
for i in range(0u, num_keys) {
- set.insert(i.to_str().to_strbuf());
+ set.insert(i.to_str().to_string());
}
for i in range(0u, num_keys) {
- assert!(set.contains(&i.to_str().to_strbuf()));
+ assert!(set.contains(&i.to_str().to_string()));
}
})
}
let mut set = f();
timed(&mut self.random_strings, || {
for _ in range(0, num_keys) {
- let s = rng.gen::<uint>().to_str().to_strbuf();
+ let s = rng.gen::<uint>().to_str().to_string();
set.insert(s);
}
})
{
let mut set = f();
for i in range(0u, num_keys) {
- set.insert(i.to_str().to_strbuf());
+ set.insert(i.to_str().to_string());
}
timed(&mut self.delete_strings, || {
for i in range(0u, num_keys) {
- assert!(set.remove(&i.to_str().to_strbuf()));
+ assert!(set.remove(&i.to_str().to_string()));
}
})
}
macro_rules! bench (
($argv:expr, $id:ident) => (maybe_run_test($argv.as_slice(),
- stringify!($id).to_strbuf(),
+ stringify!($id).to_string(),
$id))
)
fn main() {
- let argv = os::args().move_iter().map(|x| x.to_strbuf()).collect::<Vec<String>>();
+ let argv = os::args().move_iter().map(|x| x.to_string()).collect::<Vec<String>>();
let _tests = argv.slice(1, argv.len());
bench!(argv, shift_push);
if os::getenv("RUST_BENCH").is_some() {
run_test = true
} else if argv.len() > 0 {
- run_test = argv.iter().any(|x| x == &"all".to_strbuf()) || argv.iter().any(|x| x == &name)
+ run_test = argv.iter().any(|x| x == &"all".to_string()) || 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!("".to_owned(), "10000000".to_owned())
+ vec!("".to_string(), "10000000".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "100000".to_owned())
+ vec!("".to_string(), "100000".to_string())
} else {
args.move_iter().collect()
};
// version.
extern crate time;
+extern crate debug;
use std::comm;
use std::os;
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_strbuf(), "1000000".to_strbuf(), "10000".to_strbuf())
+ vec!("".to_string(), "1000000".to_string(), "10000".to_string())
} else if args.len() <= 1u {
- vec!("".to_strbuf(), "10000".to_strbuf(), "4".to_strbuf())
+ vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
- args.move_iter().map(|x| x.to_strbuf()).collect()
+ args.move_iter().map(|x| x.to_string()).collect()
};
println!("{}", args);
// I *think* it's the same, more or less.
extern crate time;
+extern crate debug;
use std::os;
use std::task;
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_strbuf(), "1000000".to_strbuf(), "8".to_strbuf())
+ vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
- vec!("".to_strbuf(), "10000".to_strbuf(), "4".to_strbuf())
+ vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
- args.clone().move_iter().map(|x| x.to_strbuf()).collect()
+ args.clone().move_iter().map(|x| x.to_string()).collect()
};
println!("{:?}", args);
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "100".to_owned(), "10000".to_owned())
+ vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "10".to_owned(), "100".to_owned())
+ vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "100".to_owned(), "10000".to_owned())
+ vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "10".to_owned(), "100".to_owned())
+ vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "12".to_owned())
+ vec!("".to_string(), "12".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "8".to_owned())
+ vec!("".to_string(), "8".to_string())
} else {
args.move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "40".to_owned())
+ vec!("".to_string(), "40".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "30".to_owned())
+ vec!("".to_string(), "30".to_string())
} else {
args.move_iter().collect()
};
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
- 3u => { format_strbuf!("{}\t{}", find(&freqs, "GGT".to_strbuf()), "GGT") }
- 4u => { format_strbuf!("{}\t{}", find(&freqs, "GGTA".to_strbuf()), "GGTA") }
- 6u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATT".to_strbuf()), "GGTATT") }
- 12u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_strbuf()), "GGTATTTTAATT") }
- 18u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_strbuf()),
+ 3u => { format_strbuf!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
+ 4u => { format_strbuf!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
+ 6u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
+ 12u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
+ 18u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
- _ => { "".to_strbuf() }
+ _ => { "".to_string() }
};
to_parent.send(buffer);
fn parse_opts(argv: Vec<String> ) -> Config {
let opts = vec!(getopts::optflag("", "stress", ""));
- let argv = argv.iter().map(|x| x.to_strbuf()).collect::<Vec<_>>();
+ let argv = argv.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let opt_args = argv.slice(1, argv.len());
match getopts::getopts(opt_args, opts.as_slice()) {
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_strbuf(), "20".to_strbuf())
+ vec!("".to_string(), "20".to_string())
} else if args.len() <= 1u {
- vec!("".to_strbuf(), "8".to_strbuf())
+ vec!("".to_string(), "8".to_string())
} else {
- args.move_iter().map(|x| x.to_strbuf()).collect()
+ args.move_iter().map(|x| x.to_string()).collect()
};
let opts = parse_opts(args.clone());
extern crate collections;
extern crate time;
+extern crate debug;
use collections::SmallIntMap;
use std::os;
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
+ vec!("".to_string(), "100000".to_string(), "100".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "10000".to_owned(), "50".to_owned())
+ vec!("".to_string(), "10000".to_string(), "50".to_string())
} else {
args.move_iter().collect()
};
pub fn read(mut reader: BufferedReader<StdReader>) -> Sudoku {
/* assert first line is exactly "9,9" */
- assert!(reader.read_line().unwrap() == "9,9".to_owned());
+ assert!(reader.read_line().unwrap() == "9,9".to_string());
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!("".to_owned(), "100000".to_owned())
+ vec!("".to_string(), "100000".to_string())
} else if args.len() <= 1 {
- vec!("".to_owned(), "100".to_owned())
+ vec!("".to_string(), "100".to_string())
} else {
args.clone().move_iter().collect()
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "30".to_owned())
+ vec!("".to_string(), "30".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "10".to_owned())
+ vec!("".to_string(), "10".to_string())
} else {
args
};
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
- vec!("".to_owned(), "400".to_owned())
+ vec!("".to_string(), "400".to_string())
} else if args.len() <= 1u {
- vec!("".to_owned(), "10".to_owned())
+ vec!("".to_string(), "10".to_string())
} else {
args.move_iter().collect()
};
#![feature(managed_boxes)]
+extern crate debug;
+
struct clam {
x: @int,
y: @int,
// error-pattern:`^` cannot be applied to type `std::string::String`
-fn main() { let x = "a".to_strbuf() ^ "b".to_strbuf(); }
+fn main() { let x = "a".to_string() ^ "b".to_string(); }
// Make sure that fn-to-block coercion isn't incorrectly lifted over
// other tycons.
+extern crate debug;
+
fn coerce(b: ||) -> extern fn() {
fn lol(f: extern fn(v: ||) -> extern fn(),
g: ||) -> extern fn() { return f(g); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct defer<'a> {
x: &'a [&'a str],
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn foo(x: int) { println!("{:?}", x); }
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
let f: || -> int = || {
let i: int;
}
fn move_in_match() {
- match S {f: "foo".to_strbuf(), g: "bar".to_strbuf()} {
+ match S {f: "foo".to_string(), g: "bar".to_string()} {
S { //~ ERROR cannot move out of type `S`, which defines the `Drop` trait
f: _s, //~ NOTE attempting to move value to here
g: _t //~ NOTE and here
}
fn let_pat() {
- let &_x = &"hi".to_owned();
+ let &_x = &"hi".to_string();
//~^ ERROR cannot move out of dereference of `&`-pointer
}
use std::rc::Rc;
pub fn main() {
- let _x = *Rc::new("hi".to_owned());
+ let _x = *Rc::new("hi".to_string());
//~^ ERROR cannot move out of dereference of `&`-pointer
}
}
fn move_in_match() {
- match S {f:"foo".to_strbuf()} {
+ match S {f:"foo".to_string()} {
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".to_strbuf()};
+ let S {f:_s} = S {f:"foo".to_string()};
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_match() {
- match S("foo".to_strbuf()) {
+ match S("foo".to_string()) {
S(_s) => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
- let S(_s) = S("foo".to_strbuf());
+ let S(_s) = S("foo".to_string());
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
// Test that we do not permit moves from &[] matched by a vec pattern.
+extern crate debug;
+
#[deriving(Clone)]
struct Foo {
string: String
pub fn main() {
let x = vec!(
- Foo { string: "foo".to_strbuf() },
- Foo { string: "bar".to_strbuf() },
- Foo { string: "baz".to_strbuf() }
+ Foo { string: "foo".to_string() },
+ Foo { string: "bar".to_string() },
+ Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
let x: int = 3;
let y: &mut int = &mut x; //~ ERROR cannot borrow
fn main() {
let msg;
- match Some("Hello".to_owned()) {
+ match Some("Hello".to_string()) {
Some(ref m) => { //~ ERROR borrowed value does not live long enough
msg = m;
},
fn f(x: String) {}
fn main() {
- let s = S { x: Bar("hello".to_strbuf()) };
+ let s = S { x: Bar("hello".to_string()) };
match &s.x {
&Foo => {}
&Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
static mut STATIC14: SafeStruct = SafeStruct {
//~^ ERROR mutable static items are not allowed to have destructors
field1: Variant1,
- field2: Variant4("str".to_strbuf())
+ field2: Variant4("str".to_string())
};
static STATIC15: &'static [Box<MyOwned>] = &'static [box MyOwned, box MyOwned];
mod circular_modules_hello; //~ERROR: circular modules
pub fn hi_str() -> String {
- "Hi!".to_owned()
+ "Hi!".to_string()
}
fn main() {
}
fn main() {
- let nyan: Box<noisy> = box cat(0, 2, "nyan".to_strbuf()) as Box<noisy>;
+ let nyan: Box<noisy> = box cat(0, 2, "nyan".to_string()) as Box<noisy>;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct foo {
i: int,
}
}
fn main() {
- let x = X { x: "hello".to_strbuf() };
+ let x = X { x: "hello".to_string() };
let y = unwrap(x);
println!("contents: {}", y);
}
}
fn main() {
- let x = X { x: "hello".to_strbuf() };
+ let x = X { x: "hello".to_string() };
match x {
X { x: y } => println!("contents: {}", y)
fn check_bound<T:Copy>(_: T) {}
fn main() {
- check_bound("nocopy".to_owned()); //~ ERROR does not fulfill `Copy`
+ check_bound("nocopy".to_string()); //~ ERROR does not fulfill `Copy`
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+fn main() {
+ for
+ &1 //~ ERROR refutable pattern in `for` loop binding
+ in [1].iter() {}
+}
// error-pattern:mismatched types: expected `()` but found `bool`
+extern crate debug;
+
fn main() {
let a = if true { true };
println!("{:?}", a);
pub fn main() {
let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5);
- let s: String = "abcdef".to_strbuf();
+ let s: String = "abcdef".to_string();
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".to_owned();
+ let x = "foo".to_string();
let y = x;
println!("{}", y);
}
}
fn bar() -> String { //~ ERROR not all control paths return a value
- "foobar".to_strbuf()
+ "foobar".to_string()
; //~ NOTE consider removing this semicolon
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
println!("{:?}", x); //~ ERROR unresolved name `x`.
}
// the compiler to attempt autoderef and then
// try to resolve the method.
impl to_str_2 for t {
- fn my_to_str() -> String { "t".to_strbuf() }
+ fn my_to_str() -> String { "t".to_string() }
}
fn new_t(x: t) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct C {
x: int,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
enum f { g(int, int) }
enum h { i(j, k) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
let foo = 100;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() { format!("{:?}", None); } //~ ERROR unconstrained type
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
format!("{:?}", None); //~ ERROR: cannot determine a type for this bounded
}
// except according to those terms.
fn foo(b: bool) -> Result<bool,String> {
- Err("bar".to_owned());
+ Err("bar".to_string());
//~^ ERROR: cannot determine a type for this expression: unconstrained type
}
impl CrateId {
fn new(s: &str) -> CrateId {
CrateId {
- local_path: s.to_strbuf(),
- junk: "wutevs".to_strbuf()
+ local_path: s.to_string(),
+ junk: "wutevs".to_string()
}
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn force(f: || -> int) -> int { f() }
fn main() { println!("{:?}", force(|| {})); } //~ ERROR mismatched types
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn main() {
let y: Box<int> = box 42;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn main() {
let y: Box<int> = box 42;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn main() {
let x = box 5;
let y = x;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn send<T:Send>(ch: _chan<T>, data: T) {
println!("{:?}", ch);
() => ( 1, 2 ) //~ ERROR macro expansion ignores token `,`
}
+macro_rules! ignored_pat {
+ () => ( 1, 2 ) //~ ERROR macro expansion ignores token `,`
+}
+
ignored_item!()
fn main() {
ignored_expr!()
+ match 1 {
+ ignored_pat!() => (),
+ _ => (),
+ }
}
// a good test that we merge paths correctly in the presence of a
// variable that's used before it's declared
+extern crate debug;
+
fn my_fail() -> ! { fail!(); }
fn main() {
// except according to those terms.
fn main() {
- match "foo".to_strbuf() {
+ match "foo".to_string() {
['f', 'o', ..] => {} //~ ERROR mismatched types
_ => { }
}
_ => ()
}
- let x: Vec<String> = vec!["foo".to_strbuf(),
- "bar".to_strbuf(),
- "baz".to_strbuf()];
+ let x: Vec<String> = vec!["foo".to_string(),
+ "bar".to_string(),
+ "baz".to_string()];
let x: &[String] = x.as_slice();
match x {
[a, _, _, ..] => { println!("{}", a); }
// error-pattern:cannot apply unary operator `-` to type `std::string::String`
-fn main() { -"foo".to_strbuf(); }
+fn main() { -"foo".to_string(); }
// Tests that if you move from `x.f` or `x[0]`, `x` is inaccessible.
// Also tests that we give a more specific error message.
+extern crate debug;
+
struct Foo { f: String, y: int }
fn consume(_s: String) {}
fn touch<A>(_a: &A) {}
fn f10() {
- let x = Foo { f: "hi".to_strbuf(), y: 3 };
+ let x = Foo { f: "hi".to_string(), y: 3 };
consume(x.f);
touch(&x.y); //~ ERROR use of partially moved value: `x`
}
fn f20() {
- let x = vec!("hi".to_strbuf());
+ let x = vec!("hi".to_string());
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!".to_owned();
+ let x = "Hello world!".to_string();
task::spawn(proc() {
println!("{}", x);
});
fn touch<A>(_a: &A) {}
fn f00() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:x }; //~ NOTE `x` moved here
touch(&x); //~ ERROR use of moved value: `x`
}
fn f05() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:(((x))) }; //~ NOTE `x` moved here
touch(&x); //~ ERROR use of moved value: `x`
}
fn f10() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:x.clone() };
touch(&x);
}
fn f20() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:(x).clone() };
touch(&x);
}
fn f30() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:((x)).clone() };
touch(&x);
}
fn f40() {
- let x = "hi".to_owned();
+ let x = "hi".to_string();
let _y = Foo { f:(((((((x)).clone()))))) };
touch(&x);
}
fn touch<A>(_a: &A) {}
fn f10() {
- let x = "hi".to_strbuf();
+ let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
- let x = "hi".to_strbuf();
+ let x = "hi".to_string();
let _y = (x, 3);
touch(&x); //~ ERROR use of moved value: `x`
}
}
fn f30(cond: bool) {
- let x = "hi".to_strbuf();
- let y = "ho".to_strbuf();
+ let x = "hi".to_string();
+ let y = "ho".to_string();
let _y = if cond {
x
} else {
}
fn f40(cond: bool) {
- let x = "hi".to_strbuf();
- let y = "ho".to_strbuf();
+ let x = "hi".to_string();
+ let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
}
fn f50(cond: bool) {
- let x = "hi".to_strbuf();
- let y = "ho".to_strbuf();
+ let x = "hi".to_string();
+ let y = "ho".to_string();
let _y = match cond {
_ if guard(x) => 10,
true => 10,
}
fn f70() {
- let x = "hi".to_strbuf();
+ let x = "hi".to_string();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
- let x = "hi".to_strbuf();
+ let x = "hi".to_string();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
- let x = vec!("hi".to_strbuf());
+ let x = vec!("hi".to_string());
let _y = x.move_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
- let x = vec!("hi".to_strbuf());
+ let x = vec!("hi".to_string());
let _y = [x.move_iter().next().unwrap(), ..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
- let mut x = vec!("hi".to_strbuf(), "ho".to_strbuf());
+ let mut x = vec!("hi".to_string(), "ho".to_string());
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".to_owned()};
+ let x = Foo {f: "hi".to_string()};
let y = match x {
Foo {f} => {} //~ NOTE moved here
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
+extern crate debug;
+
struct R<'a> {
// This struct is needed to create the
// otherwise infinite type of a fn that
}
fn innocent_looking_victim() {
- let mut x = Some("hello".to_owned());
+ let mut x = Some("hello".to_string());
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) -> String { "hi".to_owned() }
+ fn to_str(&self) -> String { "hi".to_string() }
}
#![feature(managed_boxes)]
+extern crate debug;
+
use std::task;
struct Port<T>(@T);
// Test that a class with a non-copyable field can't be
// copied
+
+extern crate debug;
+
struct bar {
x: int,
}
// error-pattern:non-scalar cast
+extern crate debug;
+
struct foo {
x:int
}
// error-pattern: transmute called on types with different size
+extern crate debug;
+
use std::mem;
#[packed]
// error-pattern: transmute called on types with different size
+extern crate debug;
+
use std::mem;
#[packed]
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(macro_rules)]
+
+macro_rules! foo ( () => ( x ) )
+
+fn main() {
+ let foo!() = 2;
+ x + 1; //~ ERROR unresolved name `x`
+}
// error-pattern: mismatched types
+extern crate debug;
+
enum bar { t1((), Option<Vec<int> >), t2, }
fn foo(t: bar) {
#![feature(managed_boxes)]
+extern crate debug;
+
use std::cell::Cell;
struct r {
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+fn func(
+ (
+ 1, //~ ERROR refutable pattern in function argument
+ (
+ Some( //~ ERROR refutable pattern in function argument
+ 1), // nested, so no warning.
+ 2..3 //~ ERROR refutable pattern in function argument
+ )
+ ): (int, (Option<int>, int))
+ ) {}
+
+fn main() {
+ let (
+ 1, //~ ERROR refutable pattern in local binding
+ (
+ Some( //~ ERROR refutable pattern in local binding
+ 1), // nested, so no warning.
+ 2..3 //~ ERROR refutable pattern in local binding
+ )
+ ) = (1, (None, 2));
+}
#![feature(concat_idents)]
pub fn main() {
- let asdf_fdsa = "<.<".to_owned();
- assert_eq!(concat_idents!(asd, f_f, dsa), "<.<".to_owned());
+ let asdf_fdsa = "<.<".to_string();
+ assert_eq!(concat_idents!(asd, f_f, dsa), "<.<".to_string());
//~^ ERROR: unresolved name `asdf_fdsa`
assert!(stringify!(use_mention_distinction) ==
}
fn main() {
- let person = "Fred".to_owned();
+ let person = "Fred".to_string();
let person: &str = person.as_slice(); //~ ERROR `person` does not live long enough
let s: Box<Trait<&'static str>> = box Struct { person: person };
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct r {
b: bool,
}
#![feature(managed_boxes)]
+extern crate debug;
use std::cell::Cell;
struct r {
}
fn main() {
- let cat = "kitty".to_strbuf();
+ let cat = "kitty".to_string();
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!".to_owned();
+ let x = "Hello!".to_string();
let _y = x;
println!("{}", x); //~ ERROR use of moved value
}
'\u205F', '\u3000'];
for c in chars.iter() {
let ws = c.is_whitespace();
- println!("{:?} {:?}" , c , ws);
+ println!("{} {}" , c , ws);
}
}
'\u2028', '\u2029', '\u202F', '\u205F', '\u3000'];
for c in chars.iter() {
let ws = c.is_whitespace();
- println!("{:?} {:?}", c , ws);
+ println!("{} {}", c , ws);
}
}
let _y =
match x {
Some(_) =>
- ["some(_)".to_owned(), "not".to_owned(), "SO".to_owned(),
- "long".to_owned(), "string".to_owned()],
+ ["some(_)".to_string(), "not".to_string(), "SO".to_string(),
+ "long".to_string(), "string".to_string()],
None =>
- ["none".to_owned(), "a".to_owned(), "a".to_owned(),
- "a".to_owned(), "a".to_owned()]
+ ["none".to_string(), "a".to_string(), "a".to_string(),
+ "a".to_string(), "a".to_string()]
};
}
let x = Some(3);
let _y =
match x {
- Some(_) => "some(_)".to_owned(),
- None => "none".to_owned()
+ Some(_) => "some(_)".to_string(),
+ None => "none".to_string()
};
}
// error-pattern:failed at 'test-assert-owned'
fn main() {
- assert!(false, "test-assert-owned".to_strbuf());
+ assert!(false, "test-assert-owned".to_string());
}
// error-pattern:quux
fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { 3u == my_err("bye".to_strbuf()); }
+fn main() { 3u == my_err("bye".to_string()); }
// error-pattern:quux
fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { 3u == my_err("bye".to_strbuf()); }
+fn main() { 3u == my_err("bye".to_string()); }
use std::task::TaskBuilder;
fn main() {
- TaskBuilder::new().named("owned name".to_owned()).try(proc() {
+ TaskBuilder::new().named("owned name".to_string()).try(proc() {
fail!("test");
1
}).unwrap()
// error-pattern:meh
fn main() {
- let str_var: String = "meh".to_strbuf();
+ let str_var: String = "meh".to_string();
fail!("{}", str_var);
}
// error-pattern:quux
fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
-fn main() { if my_err("bye".to_strbuf()) { } }
+fn main() { if my_err("bye".to_string()) { } }
// error-pattern:called `Result::unwrap()` on an `Err` value
+extern crate debug;
+
use std::result;
fn main() {
- println!("{:?}", result::Err::<int,String>("kitty".to_strbuf()).unwrap());
+ println!("{:?}", result::Err::<int,String>("kitty".to_string()).unwrap());
}
// error-pattern:index out of bounds: the len is 5 but the index is 5
fn main() {
- let s: String = "hello".to_strbuf();
+ let s: String = "hello".to_string();
// Bounds-check failure.
assert_eq!(s.as_slice()[5], 0x0 as u8);
// error-pattern:fail
+extern crate debug;
+
fn failfn() {
fail!();
}
#![feature(managed_boxes)]
+extern crate debug;
+
use std::mem;
fn failfn() {
#![feature(managed_boxes)]
+extern crate debug;
+
fn failfn() {
fail!();
}
fn main() {
- let x = @"hi".to_owned();
+ let x = @"hi".to_string();
failfn();
println!("{:?}", x);
}
#![feature(managed_boxes)]
+extern crate debug;
fn failfn() {
fail!();
#![feature(managed_boxes)]
+extern crate debug;
+
fn failfn() {
fail!();
}
#![feature(managed_boxes)]
+extern crate debug;
+
fn failfn() {
fail!();
}
// error-pattern:fail
fn main() {
- let cheese = "roquefort".to_strbuf();
- let carrots = @"crunchy".to_strbuf();
+ let cheese = "roquefort".to_string();
+ let carrots = @"crunchy".to_string();
let result: |@String, |String||: 'static = (|tasties, macerate| {
macerate((*tasties).clone());
@0;
}
fn test_str() {
- let res = match false { true => { "happy".to_owned() },
+ let res = match false { true => { "happy".to_string() },
_ => fail!("non-exhaustive match failure") };
- assert_eq!(res, "happy".to_owned());
+ assert_eq!(res, "happy".to_string());
}
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".to_strbuf());
+ arr.push(@"key stuff".to_string());
map.insert(arr.clone(),
- arr.clone().append([@"value stuff".to_strbuf()]));
+ arr.clone().append([@"value stuff".to_string()]));
if arr.len() == 5 {
fail!();
}
let cx = mk_ctxt();
let abc = quote_expr!(cx, 23);
- check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned());
+ check_pp(ext_cx, abc, pprust::print_expr, "23".to_string());
let ty = quote_ty!(cx, int);
- check_pp(ext_cx, ty, pprust::print_type, "int".to_owned());
+ check_pp(ext_cx, ty, pprust::print_type, "int".to_string());
let item = quote_item!(cx, static x : int = 10;).get();
- check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned());
+ check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_string());
let stmt = quote_stmt!(cx, let x = 20;);
- check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned());
+ check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_string());
let pat = quote_pat!(cx, Some(_));
- check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
+ check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_string());
}
pp::eof(pp.s);
});
stdout().write_line(s);
- if expect != "".to_owned() {
+ if expect != "".to_string() {
println!("expect: '%s', got: '%s'", expect, s);
assert_eq!(s, expect);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
struct pair<A,B> {
a: A, b: B
pub fn main() {
assert_eq!(14,14);
- assert_eq!("abc".to_owned(),"abc".to_owned());
+ assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(@Point{x:34},@Point{x:34});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-
-
+extern crate debug;
struct Pair<T, U> { a: T, b: U }
struct Triple { x: int, y: int, z: int }
pub fn main() {
assert_eq!(g(f), 1);
let f1: |Vec<String>| -> String = f;
- assert_eq!(f1(vec!["x".to_strbuf(), "y".to_strbuf(), "z".to_strbuf()]),
- "x".to_strbuf());
+ assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
+ "x".to_string());
}
pub fn main() {
let x = @3u;
- assert_eq!(x.foo(), "@3".to_strbuf());
+ assert_eq!(x.foo(), "@3".to_string());
}
fn runtest(me: &str) {
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
- (k.to_strbuf(), v.to_strbuf())
+ (k.to_string(), v.to_string())
}).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
None => {}
}
- env.push(("RUST_BACKTRACE".to_strbuf(), "1".to_strbuf()));
+ env.push(("RUST_BACKTRACE".to_string(), "1".to_string()));
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn inty(fun: proc(int) -> int) -> int {
fun(100)
}
pub fn main() {
fn as_buf<T>(s: String, f: |String| -> T) -> T { f(s) }
- as_buf("foo".to_strbuf(), |foo: String| -> () println!("{}", foo) );
+ as_buf("foo".to_string(), |foo: String| -> () println!("{}", foo) );
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
fn iter_vec<T>(v: Vec<T> , f: |&T|) { for x in v.iter() { f(x); } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
fn iter_vec<T>(v: Vec<T> , f: |&T|) { for x in v.iter() { f(x); } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
use std::mem::swap;
struct Ints {sum: Box<int>, values: Vec<int> }
}
pub fn main() {
- assert!(foo(&"kitty".to_strbuf()));
- assert!(!foo(&"gata".to_strbuf()));
+ assert!(foo(&"kitty".to_string()));
+ assert!(!foo(&"gata".to_string()));
}
pub fn main() {
assert!((@1 < @3));
- assert!((@@"hello ".to_owned() > @@"hello".to_owned()));
- assert!((@@@"hello".to_owned() != @@@"there".to_owned()));
+ assert!((@@"hello ".to_string() > @@"hello".to_string()));
+ assert!((@@@"hello".to_string() != @@@"there".to_string()));
}
pub fn main() {
- assert_eq!(3.hi(), "hello: 3".to_strbuf());
+ assert_eq!(3.hi(), "hello: 3".to_string());
assert_eq!(Some(Some(3)).hi(),
- "something!something!hello: 3".to_strbuf());
- assert_eq!(None::<int>.hi(), "hello - none".to_strbuf());
+ "something!something!hello: 3".to_string());
+ assert_eq!(None::<int>.hi(), "hello - none".to_string());
- assert_eq!(Some(None::<int>).hi(), "something!hello - none".to_strbuf());
- assert_eq!(Some(3).hi(), "something!hello: 3".to_strbuf());
+ assert_eq!(Some(None::<int>).hi(), "something!hello - none".to_string());
+ assert_eq!(Some(3).hi(), "something!hello: 3".to_string());
}
}
pub fn main() {
- assert_eq!(atol("1024".to_strbuf()) * 10, atol("10240".to_strbuf()));
- assert!((atoll("11111111111111111".to_strbuf()) * 10) ==
- atoll("111111111111111110".to_strbuf()));
+ assert_eq!(atol("1024".to_string()) * 10, atol("10240".to_string()));
+ assert!((atoll("11111111111111111".to_string()) * 10) ==
+ atoll("111111111111111110".to_string()));
}
pub fn main() {
let lst = new_int_alist();
- 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());
+ alist_add(&lst, 22, "hi".to_string());
+ alist_add(&lst, 44, "ho".to_string());
+ assert_eq!(alist_get(&lst, 22), "hi".to_string());
+ assert_eq!(alist_get(&lst, 44), "ho".to_string());
let lst = new_int_alist_2();
- 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());
+ alist_add(&lst, 22, "hi".to_string());
+ alist_add(&lst, 44, "ho".to_string());
+ assert_eq!(alist_get(&lst, 22), "hi".to_string());
+ assert_eq!(alist_get(&lst, 44), "ho".to_string());
}
fn child2(_s: String) { }
pub fn main() {
- let _x = task::spawn(proc() child2("hi".to_strbuf()));
+ let _x = task::spawn(proc() child2("hi".to_string()));
}
#[cat_maker]
fn cat(name: String) -> cat { cat{name: name,} }
-pub fn main() { let _kitty = cat("Spotty".to_strbuf()); }
+pub fn main() { let _kitty = cat("Spotty".to_string()); }
}
pub fn main() {
- let _kitty = cat("Spotty".to_strbuf());
+ let _kitty = cat("Spotty".to_string());
}
fn print_out(thing: Box<ToStr>, expected: String) {
let actual = thing.to_str();
println!("{}", actual);
- assert_eq!(actual.to_strbuf(), expected);
+ assert_eq!(actual.to_string(), expected);
}
pub fn main() {
- let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_strbuf()) as Box<ToStr>;
- print_out(nyan, "nyan".to_strbuf());
+ let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_string()) as Box<ToStr>;
+ print_out(nyan, "nyan".to_string());
}
}
pub fn main() {
- let mut nyan: cat = cat(0u, 2, "nyan".to_strbuf());
+ let mut nyan: cat = cat(0u, 2, "nyan".to_string());
let mut whitefang: dog = dog();
annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
pub fn main() {
- let mut nyan = cat(0u, 2, "nyan".to_strbuf());
+ let mut nyan = cat(0u, 2, "nyan".to_string());
let mut nyan: &mut noisy = &mut nyan;
nyan.speak();
}
}
pub fn main() {
- assert_eq!(cat("Spreckles".to_strbuf()).get_name(),
- "Spreckles".to_strbuf());
+ assert_eq!(cat("Spreckles".to_string()).get_name(),
+ "Spreckles".to_string());
}
}
pub fn main() {
- let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_strbuf());
+ let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string());
for _ in range(1u, 5) { nyan.speak(); }
- assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf());
+ assert!(*nyan.find(&1).unwrap() == "nyan".to_string());
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".to_strbuf());
+ let mut nyan = cat(0u, 2, "nyan".to_string());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
}
pub fn main() {
- let mut nyan = cat(0u, 2, "nyan".to_strbuf());
+ let mut nyan = cat(0u, 2, "nyan".to_string());
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".to_owned()));
+ let mut kitty = cat(1000u, 2, vec!("tabby".to_string()));
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".to_owned(), "mew".to_owned(), "purr".to_owned(), "chirp".to_owned()));
+ kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()));
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".to_owned()));
+ let mut kitty = cat(1000u, 2, vec!("tabby".to_string()));
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".to_owned(), "mew".to_owned(), "purr".to_owned(), "chirp".to_owned()));
+ kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()));
assert_eq!(kitty.meow_count(), 1004u);
}
fn print_out(thing: Box<ToStr>, expected: String) {
let actual = thing.to_str();
println!("{}", actual);
- assert_eq!(actual.to_strbuf(), expected);
+ assert_eq!(actual.to_string(), expected);
}
pub fn main() {
- let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_strbuf()) as Box<ToStr>;
- print_out(nyan, "nyan".to_strbuf());
+ let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_string()) as Box<ToStr>;
+ print_out(nyan, "nyan".to_string());
}
}
pub fn main() {
- let _nyan = cat("nyan".to_strbuf());
+ let _nyan = cat("nyan".to_string());
}
use cci_class_4::kitties::cat;
pub fn main() {
- let mut nyan = cat(0u, 2, "nyan".to_strbuf());
+ let mut nyan = cat(0u, 2, "nyan".to_string());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
}
pub fn main() {
- let mut nyan = cat(0u, 2, "nyan".to_strbuf());
+ let mut nyan = cat(0u, 2, "nyan".to_string());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
let args = os::args();
let args = args.as_slice();
- // Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
+ // Here, the rvalue `"signal".to_string()` 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".to_owned()`
+ // expression was the end of the `if`, and as the `"signal".to_string()`
// expression was never evaluated, we wound up trying to clean
// uninitialized memory.
// storing closure data (as we used to do), the u64 would
// overwrite the u16.
+extern crate debug;
struct Pair<A,B> {
a: A, b: B
use std::io::stdio::println;
fn call_it(f: proc(String) -> String) {
- println!("{}", f("Fred".to_strbuf()))
+ println!("{}", f("Fred".to_string()))
}
fn call_a_thunk(f: ||) {
pub fn main() {
// Procs
- let greeting = "Hello ".to_strbuf();
+ let greeting = "Hello ".to_string();
call_it(proc(s) {
format_strbuf!("{}{}", greeting, s)
});
- let greeting = "Goodbye ".to_strbuf();
+ let greeting = "Goodbye ".to_string();
call_it(proc(s) format_strbuf!("{}{}", greeting, s));
- let greeting = "How's life, ".to_strbuf();
+ let greeting = "How's life, ".to_string();
call_it(proc(s: String) -> String {
format_strbuf!("{}{}", greeting, s)
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
use std::task;
pub fn main() {
fn putint(_i: int) {
let mut i: int = 33;
- while i < 36 { putstr("hi".to_strbuf()); i = i + 1; }
+ while i < 36 { putstr("hi".to_string()); i = i + 1; }
}
fn zerg(i: int) -> int { return i; }
fn foo(x: int) -> int {
let mut y: t = x + 2;
- putstr("hello".to_strbuf());
+ putstr("hello".to_string());
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".to_strbuf());
- assert_eq!(format!(concat!()), "".to_strbuf());
+ assert_eq!(format!(concat!("foo", "bar", "{}"), "baz"), "foobarbaz".to_string());
+ assert_eq!(format!(concat!()), "".to_string());
assert_eq!(
concat!(1, 2i, 3u, 4f32, 4.0, 'a', true, ()),
#![feature(phase)]
#[phase(syntax, link)]
extern crate log;
+extern crate debug;
pub fn main() {
// only fails if println! evaluates its argument.
// exec-env:RUST_LOG=conditional-debug-macro-on=4
+extern crate debug;
+
pub fn main() {
// exits early if println! evaluates its arguments, otherwise it
// will hit the fail.
pub fn main() {
/*foo(1);
- foo("hi".to_owned());
+ foo("hi".to_string());
foo(~[1, 2, 3]);
foo(F{field: 42});
foo((1, 2u));
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
static x : [int, ..4] = [1,2,3,4];
static p : int = x[2];
static y : &'static [int] = &[1,2,3,4];
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".to_owned());
- assert_eq!(str::raw::from_buf_len(C, B.len()), "hi".to_owned());
+ assert_eq!(str::raw::from_buf_len(foo, A.len()), "hi".to_string());
+ assert_eq!(str::raw::from_buf_len(C, B.len()), "hi".to_string());
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".to_owned());
+ assert_eq!(bar.with_ref(|buf| str::raw::from_c_str(buf)), "hi".to_string());
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
static x : [int, ..4] = [1,2,3,4];
static y : &'static [int] = &[1,2,3,4];
let x = @();
x.cx();
let y = ();
- y.add("hi".to_strbuf());
+ y.add("hi".to_string());
}
#![feature(managed_boxes)]
+extern crate debug;
+
use std::cell::Cell;
pub fn main() {
fn main() {
let person1 = Person {
id: 5,
- name: "Janet".to_strbuf(),
+ name: "Janet".to_string(),
phone: 555_666_7777
};
let person2 = Person {
id: 5,
- name: "Bob".to_strbuf(),
+ name: "Bob".to_string(),
phone: 555_666_7777
};
assert!(hash::hash(&person1) == hash::hash(&person1));
}
pub fn main() {
- assert_eq!(B1.to_str(), "B1".to_strbuf());
- assert_eq!(B2.to_str(), "B2".to_strbuf());
- assert_eq!(C1(3).to_str(), "C1(3)".to_strbuf());
- assert_eq!(C2(B2).to_str(), "C2(B2)".to_strbuf());
- assert_eq!(D1{ a: 2 }.to_str(), "D1 { a: 2 }".to_strbuf());
- assert_eq!(E.to_str(), "E".to_strbuf());
- assert_eq!(F(3).to_str(), "F(3)".to_strbuf());
- assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_strbuf());
- assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_strbuf());
- assert_eq!(I{ a: 2, b: 4 }.to_str(), "I { a: 2, b: 4 }".to_strbuf());
- assert_eq!(J(Custom).to_str(), "J(yay)".to_strbuf());
+ assert_eq!(B1.to_str(), "B1".to_string());
+ assert_eq!(B2.to_str(), "B2".to_string());
+ assert_eq!(C1(3).to_str(), "C1(3)".to_string());
+ assert_eq!(C2(B2).to_str(), "C2(B2)".to_string());
+ assert_eq!(D1{ a: 2 }.to_str(), "D1 { a: 2 }".to_string());
+ assert_eq!(E.to_str(), "E".to_string());
+ assert_eq!(F(3).to_str(), "F(3)".to_string());
+ assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_string());
+ assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_string());
+ assert_eq!(I{ a: 2, b: 4 }.to_str(), "I { a: 2, b: 4 }".to_string());
+ assert_eq!(J(Custom).to_str(), "J(yay)".to_string());
}
macro_rules! t {
($x:expr, $expected:expr) => {
- assert_eq!(format!("{}", $x), $expected.to_strbuf())
+ assert_eq!(format!("{}", $x), $expected.to_string())
}
}
struct Foo(int, int, String);
pub fn main() {
- let a1 = Foo(5, 6, "abc".to_strbuf());
- let a2 = Foo(5, 6, "abc".to_strbuf());
- let b = Foo(5, 7, "def".to_strbuf());
+ let a1 = Foo(5, 6, "abc".to_string());
+ let a2 = Foo(5, 6, "abc".to_string());
+ let b = Foo(5, 7, "def".to_string());
assert!(a1 == a1);
assert!(a2 == a1);
fn f() -> int {
if true {
- let _s: String = "should not leak".to_strbuf();
+ let _s: String = "should not leak".to_string();
return 1;
}
return 0;
#![feature(macro_rules)]
+extern crate debug;
+
macro_rules! check {
($m:ident, $t:ty, $v:expr) => {{
mod $m {
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".to_strbuf());
- assert_eq!(format!("{:?}", C), "V".to_strbuf());
+ assert_eq!(format!("{:?}", V), "V".to_string());
+ assert_eq!(format!("{:?}", C), "V".to_string());
}
}
$m::check();
enum color { red = 1, green, blue, imaginary = -1, }
pub fn main() {
- test_color(red, 1, "red".to_strbuf());
- test_color(green, 2, "green".to_strbuf());
- test_color(blue, 3, "blue".to_strbuf());
- test_color(imaginary, -1, "imaginary".to_strbuf());
+ test_color(red, 1, "red".to_string());
+ test_color(green, 2, "green".to_string());
+ test_color(blue, 3, "blue".to_string());
+ test_color(imaginary, -1, "imaginary".to_string());
}
fn test_color(color: color, val: int, _name: String) {
}
pub fn main() {
- let mut a: Animal = Dog("Cocoa".to_strbuf(), 37.2);
- a = Cat{ name: "Spotty".to_strbuf(), weight: 2.7 };
+ let mut a: Animal = Dog("Cocoa".to_string(), 37.2);
+ a = Cat{ name: "Spotty".to_string(), weight: 2.7 };
// permuting the fields should work too
- let _c = Cat { weight: 3.1, name: "Spreckles".to_strbuf() };
+ let _c = Cat { weight: 3.1, name: "Spreckles".to_string() };
}
#![allow(dead_assignment)]
pub fn main() {
- let x : String = "hello".to_strbuf();
- let _y : String = "there".to_strbuf();
- let mut z = "thing".to_strbuf();
+ let x : String = "hello".to_string();
+ let _y : String = "there".to_string();
+ let mut z = "thing".to_string();
z = x;
assert_eq!(z.as_slice()[0], ('h' as u8));
assert_eq!(z.as_slice()[4], ('o' as u8));
#![allow(dead_assignment)]
+extern crate debug;
+
pub fn main() {
let x : &[int] = &[1,2,3,4,5];
let mut z = &[1,2,3,4,5];
use std::os;
pub fn main() {
- assert_eq!(os::getenv("TEST_EXEC_ENV"), Some("22".to_strbuf()));
+ assert_eq!(os::getenv("TEST_EXEC_ENV"), Some("22".to_string()));
}
use explicit_self_xcrate::{Foo, Bar};
pub fn main() {
- let x = Bar { x: "hello".to_strbuf() };
+ let x = Bar { x: "hello".to_string() };
x.f();
}
use s = std::num::strconv;
use to_str = std::num::strconv::float_to_str_common;
-macro_rules! t(($a:expr, $b:expr) => { { let (r, _) = $a; assert_eq!(r, $b.to_strbuf()) } })
+macro_rules! t(($a:expr, $b:expr) => { { let (r, _) = $a; assert_eq!(r, $b.to_string()) } })
pub fn main() {
// Basic usage
}
fn test_str() {
- let rs = if true { "happy".to_owned() } else { "sad".to_owned() };
- assert_eq!(rs, "happy".to_owned());
+ let rs = if true { "happy".to_string() } else { "sad".to_string() };
+ assert_eq!(rs, "happy".to_string());
}
pub fn main() { test_box(); test_str(); }
}
fn test_str() {
- let res = match true { true => { "happy".to_owned() },
+ let res = match true { true => { "happy".to_string() },
_ => fail!("not happy at all") };
- assert_eq!(res, "happy".to_owned());
+ assert_eq!(res, "happy".to_string());
}
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}".to_strbuf());
+ assert_eq!(s, "Struc{a: 13u8, b: [1, 2, 3], c: 42}".to_string());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
pub fn main() {
let pi = 3.1415927;
}
pub fn main() {
- let len = strlen("Rust".to_strbuf());
+ let len = strlen("Rust".to_string());
assert_eq!(len, 4u);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
use std::cell::RefCell;
pub fn main() {
let name = RefCell::new("rust");
let what = RefCell::new("rocks");
let msg = format!("{name:?} {:?}", &*what.borrow(), name=&*name.borrow());
- assert_eq!(msg, "&\"rust\" &\"rocks\"".to_strbuf());
+ assert_eq!(msg, "&\"rust\" &\"rocks\"".to_string());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct Foo {
x: int,
y: int
#![feature(managed_boxes)]
+extern crate debug;
+
fn id<T>(t: T) -> T { return t; }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn id<T:Send>(t: T) -> T { return t; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
fn g<X>(x: X) -> X { return x; }
#![feature(managed_boxes)]
+extern crate debug;
+
fn f<T>(x: @T) -> @T { return x; }
pub fn main() { let x = f(@3); println!("{:?}", *x); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn f<T>(x: Box<T>) -> Box<T> { return x; }
// This used to cause memory corruption in stage 0.
enum thing<K> { some(K), }
-pub fn main() { let _x = some("hi".to_owned()); }
+pub fn main() { let _x = some("hi".to_string()); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-
+extern crate debug;
enum noption<T> { some(T), }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
fn get_third<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; }
pub fn main() {
-
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// except according to those terms.
extern crate getopts;
+extern crate debug;
use getopts::{optopt, getopts};
#![feature(managed_boxes)]
extern crate collections;
-
+extern crate debug;
/**
A somewhat reduced test case to expose some Valgrind issues.
*/
pub fn map(filename: String, emit: map_reduce::putter) {
- emit(filename, "1".to_strbuf());
+ emit(filename, "1".to_string());
}
mod map_reduce {
find_reducer(k, cc) => {
let mut c;
match reducers.find(&str::from_utf8(
- k.as_slice()).unwrap().to_strbuf()) {
+ k.as_slice()).unwrap().to_string()) {
Some(&_c) => { c = _c; }
None => { c = 0; }
}
pub fn main() {
map_reduce::map_reduce(
- vec!("../src/test/run-pass/hashmap-memory.rs".to_strbuf()));
+ vec!("../src/test/run-pass/hashmap-memory.rs".to_string()));
}
) => (
parse_node!(
[$(: $tags ($(:$tag_nodes),*))*];
- [$(:$head_nodes,)* :tag(stringify!($head).to_strbuf(),
+ [$(:$head_nodes,)* :tag(stringify!($head).to_string(),
vec!($($nodes),*))];
$($rest)*
)
) => (
parse_node!(
[$(: $tags ($(:$tag_nodes),*))*];
- [$(:$nodes,)* :text(".".to_strbuf())];
+ [$(:$nodes,)* :text(".".to_string())];
$($rest)*
)
);
) => (
parse_node!(
[$(: $tags ($(:$tag_nodes),*))*];
- [$(:$nodes,)* :text(stringify!($word).to_strbuf())];
+ [$(:$nodes,)* :text(stringify!($word).to_string())];
$($rest)*
)
);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
pub fn main() {
let i: int = if false { fail!() } else { 5 };
#![allow(unused_must_use)]
#![allow(deprecated_owned_vector)]
+extern crate debug;
+
use std::fmt;
use std::io::MemWriter;
use std::io;
t!(format!("{}", 1.0f32), "1");
t!(format!("{}", 1.0f64), "1");
t!(format!("{}", "a"), "a");
- t!(format!("{}", "a".to_owned()), "a");
+ t!(format!("{}", "a".to_string()), "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".to_owned()), "foo");
+ t!(format!("{:s}", "foo".to_string()), "foo");
t!(format!("{:p}", 0x1234 as *int), "0x1234");
t!(format!("{:p}", 0x1234 as *mut int), "0x1234");
t!(format!("{:d}", A), "aloha");
writeln!(w, "{foo}", foo="bar");
}
- let s = str::from_utf8(buf.unwrap().as_slice()).unwrap().to_owned();
+ let s = str::from_utf8(buf.unwrap().as_slice()).unwrap().to_string();
t!(s, "34helloline\nbar\n");
}
format_args!(|args| { write!(w, "{}", args); }, "test");
format_args!(|args| { write!(w, "{}", args); }, "{test}", test=3);
}
- let s = str::from_utf8(buf.unwrap().as_slice()).unwrap().to_owned();
+ let s = str::from_utf8(buf.unwrap().as_slice()).unwrap().to_string();
t!(s, "1test3");
let s = format_args!(fmt::format, "hello {}", "world");
}
assert_eq!(format!("{} {} {a} {b} {} {c}",
foo(), foo(), foo(), a=foo(), b=foo(), c=foo()),
- "1 2 4 5 3 6".to_strbuf());
+ "1 2 4 5 3 6".to_string());
}
-
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
mod foo {
pub fn x(y: int) { println!("{:?}", y); }
}
pub fn main() {
let x = 2;
let x_message = match x {
- 0 .. 1 => { "not many".to_owned() }
- _ => { "lots".to_owned() }
+ 0 .. 1 => { "not many".to_string() }
+ _ => { "lots".to_string() }
};
- assert_eq!(x_message, "lots".to_owned());
+ assert_eq!(x_message, "lots".to_string());
let y = 2i;
let y_message = match y {
- 0 .. 1 => { "not many".to_owned() }
- _ => { "lots".to_owned() }
+ 0 .. 1 => { "not many".to_string() }
+ _ => { "lots".to_string() }
};
- assert_eq!(y_message, "lots".to_owned());
+ assert_eq!(y_message, "lots".to_string());
let z = 1u64;
let z_message = match z {
- 0 .. 1 => { "not many".to_owned() }
- _ => { "lots".to_owned() }
+ 0 .. 1 => { "not many".to_string() }
+ _ => { "lots".to_string() }
};
- assert_eq!(z_message, "not many".to_owned());
+ assert_eq!(z_message, "not many".to_string());
}
// except according to those terms.
pub fn main () {
- let mut line = "".to_owned();
+ let mut line = "".to_string();
let mut i = 0;
- while line != "exit".to_owned() {
- line = if i == 9 { "exit".to_owned() } else { "notexit".to_owned() };
+ while line != "exit".to_string() {
+ line = if i == 9 { "exit".to_string() } else { "notexit".to_string() };
i += 1;
}
}
rx.recv();
}
} else {
- parent("green".to_strbuf());
- parent("native".to_strbuf());
+ parent("green".to_string());
+ parent("native".to_string());
let (tx, rx) = channel();
native::task::spawn(proc() {
- parent("green".to_strbuf());
- parent("native".to_strbuf());
+ parent("green".to_string());
+ parent("native".to_string());
tx.send(());
});
rx.recv();
-
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// except according to those terms.
extern crate collections;
+extern crate debug;
use collections::HashMap;
fn noise(a: animal) -> Option<String> {
match a {
- cat(..) => { Some("meow".to_strbuf()) }
- dog(..) => { Some("woof".to_strbuf()) }
+ cat(..) => { Some("meow".to_string()) }
+ dog(..) => { Some("woof".to_string()) }
rabbit(..) => { None }
- tiger(..) => { Some("roar".to_strbuf()) }
+ tiger(..) => { Some("roar".to_string()) }
}
}
pub fn main() {
- assert_eq!(noise(cat(tabby)), Some("meow".to_strbuf()));
- assert_eq!(noise(dog(pug)), Some("woof".to_strbuf()));
- assert_eq!(noise(rabbit("Hilbert".to_strbuf(), upright)), None);
- assert_eq!(noise(tiger), Some("roar".to_strbuf()));
+ assert_eq!(noise(cat(tabby)), Some("meow".to_string()));
+ assert_eq!(noise(dog(pug)), Some("woof".to_string()));
+ assert_eq!(noise(rabbit("Hilbert".to_string(), upright)), None);
+ assert_eq!(noise(tiger), Some("roar".to_string()));
}
// Issue 1974
// Don't double free the condition allocation
pub fn main() {
- let s = "hej".to_owned();
- while s != "".to_owned() {
+ let s = "hej".to_string();
+ while s != "".to_string() {
return;
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
let mut x = 0;
use collections::HashMap;
pub fn main() {
- let v = vec!(@"hi".to_strbuf());
+ let v = vec!(@"hi".to_string());
let mut m: req::header_map = HashMap::new();
- m.insert("METHOD".to_strbuf(), @RefCell::new(v));
+ m.insert("METHOD".to_string(), @RefCell::new(v));
request::<int>(&m);
}
}
fn deadcode() {
- perform_hax(box "deadcode".to_owned());
+ perform_hax(box "deadcode".to_string());
}
pub fn main() {
}
fn deadcode() {
- perform_hax(box "deadcode".to_owned());
+ perform_hax(box "deadcode".to_string());
}
pub fn main() {
// clobber the previous node ID in a macro expr
extern crate collections;
+extern crate debug;
use collections::HashMap;
fn add_interfaces(managed_ip: String, device: HashMap<String, int>) {
- println!("{}, {:?}", managed_ip, device.get(&"interfaces".to_strbuf()));
+ println!("{}, {:?}", managed_ip, device.get(&"interfaces".to_string()));
}
pub fn main() {}
extern crate collections;
extern crate serialize;
+extern crate debug;
use collections::HashMap;
use serialize::json;
fn lookup(table: Box<json::Object>, key: String, default: String) -> String
{
- match table.find(&key.to_strbuf()) {
+ match table.find(&key.to_string()) {
option::Some(&json::String(ref s)) => {
- (*s).to_strbuf()
+ (*s).to_string()
}
option::Some(value) => {
println!("{} was expected to be a string but is a {:?}", key, value);
match &data {
&json::Object(ref interface) => {
let name = lookup((*interface).clone(),
- "ifDescr".to_strbuf(),
- "".to_strbuf());
+ "ifDescr".to_string(),
+ "".to_string());
let label = format_strbuf!("{}-{}", managed_ip, name);
(label, bool_value(false))
}
_ => {
println!("Expected dict for {} interfaces but found {:?}", managed_ip, data);
- ("gnos:missing-interface".to_strbuf(), bool_value(true))
+ ("gnos:missing-interface".to_string(), bool_value(true))
}
}
}
fn add_interfaces(store: int, managed_ip: String, device: HashMap<String, json::Json>)
-> Vec<(String, object)> {
- match device.get(&"interfaces".to_strbuf())
+ match device.get(&"interfaces".to_string())
{
&json::List(ref interfaces) =>
{
_ =>
{
println!("Expected list for {} interfaces but found {:?}", managed_ip,
- device.get(&"interfaces".to_strbuf()));
+ device.get(&"interfaces".to_string()));
Vec::new()
}
}
#![feature(managed_boxes)]
+extern crate debug;
+
/// Map representation
use std::io;
impl fmt::Show for square {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
- 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() }
+ bot => { "R".to_string() }
+ wall => { "#".to_string() }
+ rock => { "*".to_string() }
+ lambda => { "\\".to_string() }
+ closed_lift => { "L".to_string() }
+ open_lift => { "O".to_string() }
+ earth => { ".".to_string() }
+ empty => { " ".to_string() }
})
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
println!("{:?}", ("hi there!", "you"));
}
content: Vec::new(),
children: Vec::new()
};
- let v = vec!("123".to_strbuf(), "abc".to_strbuf());
- node.content = vec!("123".to_strbuf(), "abc".to_strbuf());
+ let v = vec!("123".to_string(), "abc".to_string());
+ node.content = vec!("123".to_string(), "abc".to_string());
print_str_vector(v);
print_str_vector(node.content.clone());
fn tester()
{
let loader: rsrc_loader = proc(_path) {
- result::Ok("more blah".to_strbuf())
+ result::Ok("more blah".to_string())
};
let path = path::Path::new("blah");
#![feature(managed_boxes)]
+extern crate debug;
+
enum Token {
Text(@String),
ETag(@Vec<String> , @String),
pub fn main()
{
-// assert!(check_strs(fmt!("%?", Text(@"foo".to_owned())), "Text(@~\"foo\")"));
-// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_owned()], @"bar".to_owned())),
+// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
+// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
- let t = Text(@"foo".to_strbuf());
- let u = Section(@vec!("alpha".to_strbuf()),
+ let t = Text(@"foo".to_string());
+ let u = Section(@vec!("alpha".to_string()),
true,
@vec!(t),
- @"foo".to_strbuf(),
- @"foo".to_strbuf(), @"foo".to_strbuf(), @"foo".to_strbuf(),
- @"foo".to_strbuf());
+ @"foo".to_string(),
+ @"foo".to_string(), @"foo".to_string(), @"foo".to_string(),
+ @"foo".to_string());
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".to_strbuf(), 1);
- table.insert("two".to_strbuf(), 2);
+ table.insert("one".to_string(), 1);
+ table.insert("two".to_string(), 2);
assert!(check_strs(table.to_str().as_slice(), "{one: 1, two: 2}") ||
check_strs(table.to_str().as_slice(), "{two: 2, one: 1}"));
}
// Convert each line into a string.
let lines = self.lines.iter()
.map(|line| {
- str::from_chars(line.as_slice()).to_strbuf()
+ str::from_chars(line.as_slice()).to_string()
})
.collect::<Vec<String>>();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
trait T {
fn print(&self);
}
pub fn main() {
- let town_bike = Bike { name: "schwinn".to_strbuf() };
- let my_bike = Bike { name: "surly".to_strbuf() };
+ let town_bike = Bike { name: "schwinn".to_string() };
+ let my_bike = Bike { name: "surly".to_string() };
assert!(town_bike != my_bike);
}
}
priv fn cmd_to_str(cmd: ~[String]) -> String {
- let mut res = "*".to_owned();
+ let mut res = "*".to_string();
res.push_str(cmd.len().to_str());
res.push_str("\r\n");
for s in cmd.iter() {
- res.push_str(["$".to_owned(), s.len().to_str(), "\r\n".to_owned(),
- (*s).clone(), "\r\n".to_owned()].concat() );
+ res.push_str(["$".to_string(), s.len().to_str(), "\r\n".to_string(),
+ (*s).clone(), "\r\n".to_string()].concat() );
}
res
}
fn query2(cmd: ~[String]) -> Result {
let _cmd = cmd_to_str(cmd);
- io::with_str_reader("$3\r\nXXX\r\n".to_owned())(|sb| {
+ io::with_str_reader("$3\r\nXXX\r\n".to_string())(|sb| {
let res = parse_response(@sb as @io::Reader);
println!("{:?}", res);
res
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
trait X {
fn call<T>(&self, x: &T);
fn default_method<T>(&self, x: &T) {
match args[n].as_slice() {
"-v" => (),
s => {
- return s.to_strbuf();
+ return s.to_string();
}
}
n += 1;
}
- return "".to_strbuf()
+ return "".to_string()
}
pub fn main() {
}
impl Thing {
- fn new() -> Thing { Thing { name: "dummy".to_strbuf() } }
+ fn new() -> Thing { Thing { name: "dummy".to_string() } }
}
impl Debuggable for Thing {
{
match err
{
- INVALID_ENUM => { "Invalid enum".to_strbuf() },
- INVALID_VALUE => { "Invalid value".to_strbuf() },
- _ => { "Unknown error".to_strbuf() }
+ INVALID_ENUM => { "Invalid enum".to_string() },
+ INVALID_VALUE => { "Invalid value".to_string() },
+ _ => { "Unknown error".to_string() }
}
}
#![allow(dead_assignment)]
pub fn main() {
- let s: String = "foobar".to_strbuf();
+ let s: String = "foobar".to_string();
let mut t: &str = s.as_slice();
t = t.slice(0, 3); // for master: str::view(t, 0, 3) maybe
}
impl Barks for Dog {
fn bark(&self) -> String {
- return format!("woof! (I'm {})", self.name).to_strbuf();
+ return format!("woof! (I'm {})", self.name).to_string();
}
}
pub fn main() {
- let snoopy = box Dog{name: "snoopy".to_strbuf()};
- let bubbles = box Dog{name: "bubbles".to_strbuf()};
+ let snoopy = box Dog{name: "snoopy".to_string()};
+ let bubbles = box Dog{name: "bubbles".to_string()};
let barker = [snoopy as Box<Barks>, bubbles as Box<Barks>];
for pup in barker.iter() {
failed to typecheck correctly.
*/
+extern crate debug;
+
struct X { vec: &'static [int] }
static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn main() {
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+
+extern crate debug;
+
struct A { x: uint }
impl Drop for A {
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+
+extern crate debug;
+
struct A { x: uint }
impl Drop for A {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
trait IDummy {
fn do_nothing(&self);
}
#![feature(managed_boxes)]
+extern crate debug;
+
fn assert_repr_eq<T>(obj : T, expected : String) {
assert_eq!(expected, format_strbuf!("{:?}", obj));
}
let slice = x.slice(0,1);
let z = @x;
- assert_repr_eq(abc, "[1, 2, 3]".to_strbuf());
- assert_repr_eq(tf, "[true, false]".to_strbuf());
- assert_repr_eq(x, "[(), ()]".to_strbuf());
- assert_repr_eq(slice, "&[()]".to_strbuf());
- assert_repr_eq(&x, "&[(), ()]".to_strbuf());
- assert_repr_eq(z, "@[(), ()]".to_strbuf());
+ assert_repr_eq(abc, "[1, 2, 3]".to_string());
+ assert_repr_eq(tf, "[true, false]".to_string());
+ assert_repr_eq(x, "[(), ()]".to_string());
+ assert_repr_eq(slice, "&[()]".to_string());
+ assert_repr_eq(&x, "&[(), ()]".to_string());
+ assert_repr_eq(z, "@[(), ()]".to_string());
}
let mut ch_start: uint;
break 'outer;
}
- "".to_strbuf()
+ "".to_string()
}
pub fn main() {
}
pub fn main() {
- let b = &["foo".to_strbuf()];
+ let b = &["foo".to_string()];
let a = A {
- a: &["test".to_strbuf()],
+ a: &["test".to_string()],
b: Some(b),
};
assert_eq!(a.b.get_ref()[0].as_slice(), "foo");
fn foo(&self) -> String;
fn foo1(&self) -> String;
fn foo2(&self) -> String{
- "base foo2".to_strbuf()
+ "base foo2".to_string()
}
}
impl Base for X {
fn foo(&self) -> String{
- "base foo".to_strbuf()
+ "base foo".to_string()
}
fn foo1(&self) -> String{
- "base foo1".to_strbuf()
+ "base foo1".to_string()
}
}
impl Base2 for X {
fn baz(&self) -> String{
- "base2 baz".to_strbuf()
+ "base2 baz".to_string()
}
}
impl Base3 for X {
fn root(&self) -> String{
- "base3 root".to_strbuf()
+ "base3 root".to_string()
}
}
impl Super for X {
fn bar(&self) -> String{
- "super bar".to_strbuf()
+ "super bar".to_string()
}
}
pub fn main() {
let n = X;
let s = &n as &Super;
- assert_eq!(s.bar(),"super bar".to_strbuf());
- assert_eq!(s.foo(),"base foo".to_strbuf());
- assert_eq!(s.foo1(),"base foo1".to_strbuf());
- assert_eq!(s.foo2(),"base foo2".to_strbuf());
- assert_eq!(s.baz(),"base2 baz".to_strbuf());
- assert_eq!(s.root(),"base3 root".to_strbuf());
+ assert_eq!(s.bar(),"super bar".to_string());
+ assert_eq!(s.foo(),"base foo".to_string());
+ assert_eq!(s.foo1(),"base foo1".to_string());
+ assert_eq!(s.foo2(),"base foo2".to_string());
+ assert_eq!(s.baz(),"base2 baz".to_string());
+ assert_eq!(s.root(),"base3 root".to_string());
}
pub fn main() {
{
// This runs without complaint.
- let x = Wrapper::new("Bob".to_strbuf());
+ let x = Wrapper::new("Bob".to_string());
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".to_strbuf()).say_hi();
+ Wrapper::new("Bob".to_string()).say_hi();
}
}
use std::string::String;
fn test_stack_assign() {
- let s: String = "a".to_strbuf();
+ let s: String = "a".to_string();
println!("{}", s.clone());
- let t: String = "a".to_strbuf();
+ let t: String = "a".to_string();
assert!(s == t);
- let u: String = "b".to_strbuf();
+ let u: String = "b".to_string();
assert!((s != u));
}
-fn test_heap_lit() { "a big string".to_strbuf(); }
+fn test_heap_lit() { "a big string".to_string(); }
fn test_heap_assign() {
- let s: String = "a big ol' string".to_strbuf();
- let t: String = "a big ol' string".to_strbuf();
+ let s: String = "a big ol' string".to_string();
+ let t: String = "a big ol' string".to_string();
assert!(s == t);
- let u: String = "a bad ol' string".to_strbuf();
+ let u: String = "a bad ol' string".to_string();
assert!((s != u));
}
fn test_heap_log() {
- let s = "a big ol' string".to_strbuf();
+ let s = "a big ol' string".to_string();
println!("{}", s);
}
// Make sure #1399 stays fixed
+extern crate debug;
struct A { a: Box<int> }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
let x = vec!(1, 2, 3);
let mut y = 0;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
- let s = "hello there".to_owned();
+ let s = "hello there".to_string();
let mut i: int = 0;
for c in s.as_slice().bytes() {
if i == 0 { assert!((c == 'h' as u8)); }
-
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
#[deriving(Clone)]
enum foo {
a(uint),
pub fn main() {
let mut x = Some(a(22u));
- let exp = "Some(a(22u))".to_strbuf();
+ let exp = "Some(a(22u))".to_string();
let act = format_strbuf!("{:?}", x);
assert_eq!(act, exp);
check_log(exp, x);
x = None;
- let exp = "None".to_strbuf();
+ let exp = "None".to_string();
let act = format_strbuf!("{:?}", x);
assert_eq!(act, exp);
check_log(exp, x);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
enum foo {
a(uint),
b(String),
}
pub fn main() {
- assert_eq!("a(22u)".to_strbuf(), format_strbuf!("{:?}", a(22u)));
- assert_eq!("c".to_strbuf(), format_strbuf!("{:?}", c));
- assert_eq!("d".to_strbuf(), format_strbuf!("{:?}", d));
+ assert_eq!("a(22u)".to_string(), format_strbuf!("{:?}", a(22u)));
+ assert_eq!("c".to_string(), format_strbuf!("{:?}", c));
+ assert_eq!("d".to_string(), format_strbuf!("{:?}", d));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
enum Numbers {
Three
}
return
}
- let env = [("RUST_LOG".to_owned(), "debug".to_owned())];
+ let env = [("RUST_LOG".to_string(), "debug".to_string())];
let p = Command::new(args[0].as_slice())
.arg("child").env(env.as_slice())
.spawn().unwrap().wait_with_output().unwrap();
--- /dev/null
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(macro_rules)]
+
+macro_rules! mypat(
+ () => (
+ Some('y')
+ )
+)
+
+macro_rules! char_x(
+ () => (
+ 'x'
+ )
+)
+
+macro_rules! some(
+ ($x:pat) => (
+ Some($x)
+ )
+)
+
+macro_rules! indirect(
+ () => (
+ some!(char_x!())
+ )
+)
+
+macro_rules! ident_pat(
+ ($x:ident) => (
+ $x
+ )
+)
+
+fn f(c: Option<char>) -> uint {
+ match c {
+ Some('x') => 1,
+ mypat!() => 2,
+ _ => 3,
+ }
+}
+
+pub fn main() {
+ assert_eq!(1, f(Some('x')));
+ assert_eq!(2, f(Some('y')));
+ assert_eq!(3, f(None));
+
+ assert_eq!(1, match Some('x') {
+ Some(char_x!()) => 1,
+ _ => 2,
+ });
+
+ assert_eq!(1, match Some('x') {
+ some!(char_x!()) => 1,
+ _ => 2,
+ });
+
+ assert_eq!(1, match Some('x') {
+ indirect!() => 1,
+ _ => 2,
+ });
+
+ assert_eq!(3, {
+ let ident_pat!(x) = 2;
+ x+1
+ });
+}
fn f1(ref_string: &str) -> String {
match ref_string {
- "a" => "found a".to_strbuf(),
- "b" => "found b".to_strbuf(),
- _ => "not found".to_strbuf()
+ "a" => "found a".to_string(),
+ "b" => "found b".to_string(),
+ _ => "not found".to_string()
}
}
fn f2(ref_string: &str) -> String {
match ref_string {
- "a" => "found a".to_strbuf(),
- "b" => "found b".to_strbuf(),
+ "a" => "found a".to_string(),
+ "b" => "found b".to_string(),
s => format_strbuf!("not found ({})", s)
}
}
fn g1(ref_1: &str, ref_2: &str) -> String {
match (ref_1, ref_2) {
- ("a", "b") => "found a,b".to_strbuf(),
- ("b", "c") => "found b,c".to_strbuf(),
- _ => "not found".to_strbuf()
+ ("a", "b") => "found a,b".to_string(),
+ ("b", "c") => "found b,c".to_string(),
+ _ => "not found".to_string()
}
}
fn g2(ref_1: &str, ref_2: &str) -> String {
match (ref_1, ref_2) {
- ("a", "b") => "found a,b".to_strbuf(),
- ("b", "c") => "found b,c".to_strbuf(),
+ ("a", "b") => "found a,b".to_string(),
+ ("b", "c") => "found b,c".to_string(),
(s1, s2) => format_strbuf!("not found ({}, {})", s1, s2)
}
}
pub fn main() {
- assert_eq!(f1("b"), "found b".to_strbuf());
- assert_eq!(f1("c"), "not found".to_strbuf());
- assert_eq!(f1("d"), "not found".to_strbuf());
- assert_eq!(f2("b"), "found b".to_strbuf());
- assert_eq!(f2("c"), "not found (c)".to_strbuf());
- assert_eq!(f2("d"), "not found (d)".to_strbuf());
- assert_eq!(g1("b", "c"), "found b,c".to_strbuf());
- assert_eq!(g1("c", "d"), "not found".to_strbuf());
- assert_eq!(g1("d", "e"), "not found".to_strbuf());
- assert_eq!(g2("b", "c"), "found b,c".to_strbuf());
- assert_eq!(g2("c", "d"), "not found (c, d)".to_strbuf());
- assert_eq!(g2("d", "e"), "not found (d, e)".to_strbuf());
+ assert_eq!(f1("b"), "found b".to_string());
+ assert_eq!(f1("c"), "not found".to_string());
+ assert_eq!(f1("d"), "not found".to_string());
+ assert_eq!(f2("b"), "found b".to_string());
+ assert_eq!(f2("c"), "not found (c)".to_string());
+ assert_eq!(f2("d"), "not found (d)".to_string());
+ assert_eq!(g1("b", "c"), "found b,c".to_string());
+ assert_eq!(g1("c", "d"), "not found".to_string());
+ assert_eq!(g1("d", "e"), "not found".to_string());
+ assert_eq!(g2("b", "c"), "found b,c".to_string());
+ assert_eq!(g2("c", "d"), "not found (c, d)".to_string());
+ assert_eq!(g2("d", "e"), "not found (d, e)".to_string());
}
fn test1() {
// from issue 6338
- match ((1, "a".to_owned()), (2, "b".to_owned())) {
+ match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
- assert_eq!(a, "a".to_owned());
- assert_eq!(b, "b".to_owned());
+ assert_eq!(a, "a".to_string());
+ assert_eq!(b, "b".to_string());
},
_ => fail!(),
}
enum t { tag1(String), tag2, }
- match tag1("test".to_strbuf()) {
+ match tag1("test".to_string()) {
tag2 => fail!(),
tag1(ref s) if "test" != s.as_slice() => fail!(),
tag1(ref s) if "test" == s.as_slice() => (),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
match box 100 {
box x => {
}
fn transform(x: Option<int>) -> Option<String> {
- x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str().to_strbuf()) )
+ x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str().to_string()) )
}
pub fn main() {
- assert_eq!(transform(Some(10)), Some("11".to_strbuf()));
+ assert_eq!(transform(Some(10)), Some("11".to_string()));
assert_eq!(transform(None), None);
- assert!((vec!("hi".to_strbuf()))
+ assert!((vec!("hi".to_string()))
.bind(|x| vec!(x.clone(), format_strbuf!("{}!", x)) )
.bind(|x| vec!(x.clone(), format_strbuf!("{}?", x)) ) ==
- vec!("hi".to_strbuf(),
- "hi?".to_strbuf(),
- "hi!".to_strbuf(),
- "hi!?".to_strbuf()));
+ vec!("hi".to_string(),
+ "hi?".to_string(),
+ "hi!".to_string(),
+ "hi!?".to_string()));
}
}
pub fn main() {
- let x = S { x: "Hello!".to_strbuf() };
+ let x = S { x: "Hello!".to_string() };
x.foo();
}
use std::task;
pub fn main() {
- let x = "Hello world!".to_owned();
+ let x = "Hello world!".to_string();
task::spawn(proc() {
println!("{}", x);
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn baz() -> ! { fail!(); }
check_type!(&17: &int);
check_type!(box 18: Box<int>);
check_type!(@19: @int);
- check_type!("foo".to_strbuf(): String);
+ check_type!("foo".to_string(): String);
check_type!(vec!(20, 22): Vec<int> );
let mint: uint = unsafe { mem::transmute(main) };
check_type!(main: fn(), |pthing| {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-
+extern crate debug;
// Regression test for issue #152.
pub fn main() {
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
+extern crate debug;
+
use std::ops::Index;
struct AssociationList<K,V> {
}
pub fn main() {
- let foo = "foo".to_owned();
- let bar = "bar".to_owned();
+ let foo = "foo".to_string();
+ let bar = "bar".to_string();
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".to_owned());
+ let s = Rc::new("foo".to_string());
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".to_owned());
- assert_eq!(*s, "foo".to_owned());
+ let s = Rc::new("foo".to_string());
+ assert_eq!(*s, "foo".to_string());
assert_eq!((*s).as_slice(), "foo");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
#![feature(managed_boxes)]
+extern crate debug;
+
fn magic(x: A) { println!("{:?}", x); }
fn magic2(x: @int) { println!("{:?}", x); }
// parameters sent to child / expected to be received from parent
let arg = blah;
let cwd = my_dir.join(Path::new(child_dir.clone()));
- let env = ("RUST_TEST_PROC_SPAWN_UNICODE".to_strbuf(), blah.to_strbuf());
+ let env = ("RUST_TEST_PROC_SPAWN_UNICODE".to_string(), blah.to_string());
// am I the parent or the child?
if my_args.len() == 1 { // parent
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
// Issue #2303
+extern crate debug;
+
use std::mem;
mod rusti {
// because `inner`s alignment was 4.
assert_eq!(mem::size_of::<Outer>(), m::size());
- assert_eq!(y, "Outer{c8: 22u8, t: Inner{c64: 44u32}}".to_strbuf());
+ assert_eq!(y, "Outer{c8: 22u8, t: Inner{c64: 44u32}}".to_string());
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
// Issue #2303
+extern crate debug;
+
use std::mem;
mod rusti {
// 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}}".to_strbuf());
+ assert_eq!(y, "Outer{c8: 22u8, t: Inner{c64: 44u64}}".to_string());
}
}
struct X { foo: String, bar: String }
pub fn main() {
- let x = X {foo: "hello".to_strbuf(), bar: "world".to_strbuf()};
+ let x = X {foo: "hello".to_string(), bar: "world".to_string()};
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()".to_strbuf(), Bort::bort());
+ assert_eq!("bort()".to_string(), Bort::bort());
}
impl TyVisitor for MyVisitor {
fn visit_bot(&mut self) -> bool {
- self.types.push("bot".to_strbuf());
+ self.types.push("bot".to_string());
println!("visited bot type");
true
}
fn visit_nil(&mut self) -> bool {
- self.types.push("nil".to_strbuf());
+ self.types.push("nil".to_string());
println!("visited nil type");
true
}
fn visit_bool(&mut self) -> bool {
- self.types.push("bool".to_strbuf());
+ self.types.push("bool".to_string());
println!("visited bool type");
true
}
fn visit_int(&mut self) -> bool {
- self.types.push("int".to_strbuf());
+ self.types.push("int".to_string());
println!("visited int type");
true
}
fn visit_i8(&mut self) -> bool {
- self.types.push("i8".to_strbuf());
+ self.types.push("i8".to_string());
println!("visited i8 type");
true
}
fn visit_i16(&mut self) -> bool {
- self.types.push("i16".to_strbuf());
+ self.types.push("i16".to_string());
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("[".to_strbuf());
+ self.types.push("[".to_string());
unsafe { visit_tydesc(inner, &mut *self as &mut TyVisitor); }
- self.types.push("]".to_strbuf());
+ self.types.push("]".to_string());
true
}
fn visit_evec_slice(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true }
}
let vec_types: Vec<String> = v.types.clone().move_iter().collect();
- assert_eq!(vec_types, vec!("bool".to_strbuf(), "int".to_strbuf(),
- "i8".to_strbuf(), "i16".to_strbuf()));
+ assert_eq!(vec_types, vec!("bool".to_string(), "int".to_string(),
+ "i8".to_string(), "i16".to_string()));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct Clam<'a> {
chowder: &'a int
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
enum int_wrapper<'a> {
int_wrapper_ctor(&'a int)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
let mut x: int = 3;
let y: &mut int = &mut x;
})
});
assert!((ostream as uint != 0u));
- let s = "hello".to_owned();
+ let s = "hello".to_string();
"hello".with_c_str(|buf| {
let write_len = libc::fwrite(buf as *libc::c_void,
1u as libc::size_t,
#![feature(managed_boxes)]
+extern crate debug;
+
pub fn main() {
let x = [ [true], ..512 ];
let y = [ 0, ..1 ];
#![feature(managed_boxes)]
+extern crate debug;
+
use std::cell::Cell;
struct r {
fn okay(i: uint) -> int {
if i == 3u {
- my_err("I don't like three".to_strbuf());
+ my_err("I don't like three".to_string());
} else {
return 42;
}
pub fn main() {
let mut map: HashMap<SendStr, uint> = HashMap::new();
assert!(map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned("foo".to_owned()), 42));
+ assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned("foo".to_owned()), 42));
+ assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 43));
- assert!(!map.insert(Owned("foo".to_owned()), 44));
+ assert!(!map.insert(Owned("foo".to_string()), 44));
assert!(!map.insert(Slice("foo"), 45));
- assert!(!map.insert(Owned("foo".to_owned()), 46));
+ assert!(!map.insert(Owned("foo".to_string()), 46));
let v = 46;
- assert_eq!(map.find(&Owned("foo".to_owned())), Some(&v));
+ assert_eq!(map.find(&Owned("foo".to_string())), 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".to_owned()), b));
+ assert!(map.insert(Owned("bcd".to_string()), b));
assert!(map.insert(Slice("cde"), c));
- assert!(map.insert(Owned("def".to_owned()), d));
+ assert!(map.insert(Owned("def".to_string()), d));
assert!(!map.insert(Slice("abc"), a));
- assert!(!map.insert(Owned("bcd".to_owned()), b));
+ assert!(!map.insert(Owned("bcd".to_string()), b));
assert!(!map.insert(Slice("cde"), c));
- assert!(!map.insert(Owned("def".to_owned()), d));
+ assert!(!map.insert(Owned("def".to_string()), d));
- assert!(!map.insert(Owned("abc".to_owned()), a));
+ assert!(!map.insert(Owned("abc".to_string()), a));
assert!(!map.insert(Slice("bcd"), b));
- assert!(!map.insert(Owned("cde".to_owned()), c));
+ assert!(!map.insert(Owned("cde".to_string()), c));
assert!(!map.insert(Slice("def"), d));
assert_eq!(map.find_equiv(&("abc")), Some(&a));
pub fn main() {
let mut map: TreeMap<SendStr, uint> = TreeMap::new();
assert!(map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned("foo".to_owned()), 42));
+ assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 42));
- assert!(!map.insert(Owned("foo".to_owned()), 42));
+ assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 43));
- assert!(!map.insert(Owned("foo".to_owned()), 44));
+ assert!(!map.insert(Owned("foo".to_string()), 44));
assert!(!map.insert(Slice("foo"), 45));
- assert!(!map.insert(Owned("foo".to_owned()), 46));
+ assert!(!map.insert(Owned("foo".to_string()), 46));
let v = 46;
- assert_eq!(map.find(&Owned("foo".to_owned())), Some(&v));
+ assert_eq!(map.find(&Owned("foo".to_string())), 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".to_owned()), b));
+ assert!(map.insert(Owned("bcd".to_string()), b));
assert!(map.insert(Slice("cde"), c));
- assert!(map.insert(Owned("def".to_owned()), d));
+ assert!(map.insert(Owned("def".to_string()), d));
assert!(!map.insert(Slice("abc"), a));
- assert!(!map.insert(Owned("bcd".to_owned()), b));
+ assert!(!map.insert(Owned("bcd".to_string()), b));
assert!(!map.insert(Slice("cde"), c));
- assert!(!map.insert(Owned("def".to_owned()), d));
+ assert!(!map.insert(Owned("def".to_string()), d));
- assert!(!map.insert(Owned("abc".to_owned()), a));
+ assert!(!map.insert(Owned("abc".to_string()), a));
assert!(!map.insert(Slice("bcd"), b));
- assert!(!map.insert(Owned("cde".to_owned()), c));
+ assert!(!map.insert(Owned("cde".to_string()), 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".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_eq!(map.find(&Owned("abc".to_string())), Some(&a));
+ assert_eq!(map.find(&Owned("bcd".to_string())), Some(&b));
+ assert_eq!(map.find(&Owned("cde".to_string())), Some(&c));
+ assert_eq!(map.find(&Owned("def".to_string())), Some(&d));
assert!(map.pop(&Slice("foo")).is_some());
assert_eq!(map.move_iter().map(|(k, v)| format_strbuf!("{}{}", k, v))
.collect::<Vec<String>>()
.concat(),
- "abc50bcd51cde52def53".to_owned());
+ "abc50bcd51cde52def53".to_string());
}
pub fn main() {
- assert!(("hello".to_owned() < "hellr".to_owned()));
- assert!(("hello ".to_owned() > "hello".to_owned()));
- assert!(("hello".to_owned() != "there".to_owned()));
+ assert!(("hello".to_string() < "hellr".to_string()));
+ assert!(("hello ".to_string() > "hello".to_string()));
+ assert!(("hello".to_string() != "there".to_string()));
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)));
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn foo(c: Vec<int> ) {
let a: int = 5;
#![feature(managed_boxes)]
+extern crate debug;
+
// Exercises a bug in the shape code that was exposed
// on x86_64: when there is an enum embedded in an
// interior record which is then itself interior to
let t: @ty = @Spanned { data: 3u, span: sp };
let p_: Path_ = Path_ {
global: true,
- idents: vec!("hi".to_strbuf()),
+ idents: vec!("hi".to_string()),
types: vec!(t),
};
let p: path = Spanned { data: p_, span: sp };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// copyright 2013-2014 the rust project developers. see the copyright
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/copyright.
-//
-// licensed under the apache license, version 2.0 <license-apache or
-// http://www.apache.org/licenses/license-2.0> or the mit license
-// <license-mit or http://opensource.org/licenses/mit>, at your
-// option. this file may not be copied, modified, or distributed
-// except according to those terms.
-
// ignore-win32
+extern crate debug;
+
use std::os;
use std::io::process::{Command, ExitSignal, ExitStatus};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
enum clam<T> { a(T, int), b, }
#![feature(macro_rules)]
+extern crate debug;
+
use std::mem::size_of;
#[deriving(Eq, Show)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
use std::task;
fn x(s: String, n: int) {
}
pub fn main() {
- task::spawn(proc() x("hello from first spawned fn".to_strbuf(), 65) );
- task::spawn(proc() x("hello from second spawned fn".to_strbuf(), 66) );
- task::spawn(proc() x("hello from third spawned fn".to_strbuf(), 67) );
+ task::spawn(proc() x("hello from first spawned fn".to_string(), 65) );
+ task::spawn(proc() x("hello from second spawned fn".to_string(), 66) );
+ task::spawn(proc() x("hello from third spawned fn".to_string(), 67) );
let mut i: int = 30;
while i > 0 {
i = i - 1;
type ctx = Sender<int>;
fn iotask(_tx: &ctx, ip: String) {
- assert_eq!(ip, "localhost".to_strbuf());
+ assert_eq!(ip, "localhost".to_string());
}
pub fn main() {
let (tx, _rx) = channel::<int>();
- task::spawn(proc() iotask(&tx, "localhost".to_strbuf()) );
+ task::spawn(proc() iotask(&tx, "localhost".to_string()) );
}
impl uint_utils for uint {
fn str(&self) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
fn multi(&self, f: |uint|) {
let mut c = 0u;
pub fn main() {
assert_eq!(10u.plus(), 30);
- assert_eq!(("hi".to_strbuf()).plus(), 200);
+ assert_eq!(("hi".to_string()).plus(), 200);
- assert_eq!((vec!(1)).length_().str(), "1".to_strbuf());
+ assert_eq!((vec!(1)).length_().str(), "1".to_string());
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".to_strbuf());
+ let result: int = read("5".to_string());
assert_eq!(result, 5);
- assert_eq!(read::readMaybe("false".to_strbuf()), Some(false));
- assert_eq!(read::readMaybe("foo".to_strbuf()), None::<bool>);
+ assert_eq!(read::readMaybe("false".to_string()), Some(false));
+ assert_eq!(read::readMaybe("foo".to_string()), None::<bool>);
}
pub fn main() {
- let a: String = "hello".to_strbuf();
- let b: String = "world".to_strbuf();
+ let a: String = "hello".to_string();
+ let b: String = "world".to_string();
let s: String = format_strbuf!("{}{}", a, b);
println!("{}", s.clone());
assert_eq!(s.as_slice()[9], 'd' as u8);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
+extern crate debug;
pub fn main() {
- let s = "hello".to_owned();
+ let s = "hello".to_string();
let c: u8 = s.as_slice()[4];
println!("{:?}", c);
assert_eq!(c, 0x6f as u8);
pub fn main() {
let a: String = "this \
-is a test".to_strbuf();
+is a test".to_string();
let b: String =
"this \
is \
another \
- test".to_strbuf();
- assert_eq!(a, "this is a test".to_strbuf());
- assert_eq!(b, "this is another test".to_strbuf());
+ test".to_string();
+ assert_eq!(a, "this is a test".to_string());
+ assert_eq!(b, "this is another test".to_string());
}
pub fn main() {
// Make sure we properly handle repeated self-appends.
- let mut a: String = "A".to_strbuf();
+ let mut a: String = "A".to_string();
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
assert_eq!(foo, foo_);
let foo = Foo {
- bar: "one".to_owned(),
- baz: "two".to_owned()
+ bar: "one".to_string(),
+ baz: "two".to_string()
};
let foo_ = foo.clone();
pub fn main() {
let _z = foo {
- x: "Hello".to_strbuf()
+ x: "Hello".to_string()
};
}
struct S { f0: String, f1: int }
pub fn main() {
- let s = "Hello, world!".to_strbuf();
+ let s = "Hello, world!".to_string();
let _s = S {
- f0: s.to_strbuf(),
+ f0: s.to_string(),
..S {
f0: s,
f1: 23
}
pub fn main() {
- let s = "Hello, world!".to_strbuf();
+ let s = "Hello, world!".to_string();
let _s = S {
- f1: s.to_strbuf(),
+ f1: s.to_string(),
f0: s
};
}
pub fn main() {
let mut test = TestDescAndFn {
desc: TestDesc {
- name: DynTestName("test".to_strbuf()),
+ name: DynTestName("test".to_string()),
should_fail: false
},
testfn: DynTestFn(proc() ()),
pub mod m1 {
pub mod m2 {
pub fn where_am_i() -> String {
- (module_path!()).to_strbuf()
+ (module_path!()).to_string()
}
}
}
//assert!((col!() == 11));
assert_eq!(indirect_line!(), 29);
assert!((file!().ends_with("syntax-extension-source-utils.rs")));
- assert_eq!(stringify!((2*3) + 5).to_strbuf(), "( 2 * 3 ) + 5".to_strbuf());
+ assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_string());
assert!(include!("syntax-extension-source-utils-files/includeme.\
- fragment").to_strbuf()
- == "victory robot 6".to_strbuf());
+ fragment").to_string()
+ == "victory robot 6".to_string());
assert!(
include_str!("syntax-extension-source-utils-files/includeme.\
- fragment").to_strbuf()
+ fragment").to_string()
.as_slice()
.starts_with("/* this is for "));
assert!(
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
enum a_tag {
a_tag(u64)
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)}".to_strbuf());
+ assert_eq!(y, "t_rec{c8: 22u8, t: a_tag(44u64)}".to_string());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
enum color {
red = 0xff0000,
green = 0x00ff00,
pub fn main() {
let act = format!("{:?}", red);
println!("{}", act);
- assert_eq!("red".to_strbuf(), act);
- assert_eq!("green".to_strbuf(), format!("{:?}", green));
- assert_eq!("white".to_strbuf(), format!("{:?}", white));
+ assert_eq!("red".to_string(), act);
+ assert_eq!("green".to_string(), format!("{:?}", green));
+ assert_eq!("white".to_string(), format!("{:?}", white));
}
}
pub fn main() {
- test_color(red, 0xff0000, "red".to_strbuf());
- test_color(green, 0x00ff00, "green".to_strbuf());
- test_color(blue, 0x0000ff, "blue".to_strbuf());
- test_color(black, 0x000000, "black".to_strbuf());
- test_color(white, 0xFFFFFF, "white".to_strbuf());
- test_color(imaginary, -1, "imaginary".to_strbuf());
- test_color(purple, 2, "purple".to_strbuf());
- test_color(orange, 4, "orange".to_strbuf());
+ test_color(red, 0xff0000, "red".to_string());
+ test_color(green, 0x00ff00, "green".to_string());
+ test_color(blue, 0x0000ff, "blue".to_string());
+ test_color(black, 0x000000, "black".to_string());
+ test_color(white, 0xFFFFFF, "white".to_string());
+ test_color(imaginary, -1, "imaginary".to_string());
+ test_color(purple, 2, "purple".to_string());
+ test_color(orange, 4, "orange".to_string());
}
fn test_color(color: color, val: int, name: String) {
fn get_color_alt(color: color) -> String {
match color {
- red => {"red".to_strbuf()}
- green => {"green".to_strbuf()}
- blue => {"blue".to_strbuf()}
- black => {"black".to_strbuf()}
- white => {"white".to_strbuf()}
- imaginary => {"imaginary".to_strbuf()}
- purple => {"purple".to_strbuf()}
- orange => {"orange".to_strbuf()}
+ red => {"red".to_string()}
+ green => {"green".to_string()}
+ blue => {"blue".to_string()}
+ black => {"black".to_string()}
+ white => {"white".to_string()}
+ imaginary => {"imaginary".to_string()}
+ purple => {"purple".to_string()}
+ orange => {"orange".to_string()}
}
}
fn get_color_if(color: color) -> String {
- if color == red {"red".to_strbuf()}
- else if color == green {"green".to_strbuf()}
- else if color == blue {"blue".to_strbuf()}
- else if color == black {"black".to_strbuf()}
- else if color == white {"white".to_strbuf()}
- else if color == imaginary {"imaginary".to_strbuf()}
- else if color == purple {"purple".to_strbuf()}
- else if color == orange {"orange".to_strbuf()}
- else {"unknown".to_strbuf()}
+ if color == red {"red".to_string()}
+ else if color == green {"green".to_string()}
+ else if color == blue {"blue".to_string()}
+ else if color == black {"black".to_string()}
+ else if color == white {"white".to_string()}
+ else if color == imaginary {"imaginary".to_string()}
+ else if color == purple {"purple".to_string()}
+ else if color == orange {"orange".to_string()}
+ else {"unknown".to_string()}
}
fn inner(dummy: String, b: bool) { if b { return inner(dummy, false); } }
pub fn main() {
- inner("hi".to_strbuf(), true);
+ inner("hi".to_string(), true);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-
+extern crate debug;
fn checktrue(rs: bool) -> bool { assert!((rs)); return true; }
let mut a;
let mut b;
a = rx.recv();
- assert!(a == "A".to_strbuf());
+ assert!(a == "A".to_string());
println!("{}", a);
b = rx.recv();
- assert!(b == "B".to_strbuf());
+ assert!(b == "B".to_string());
println!("{}", b);
}
let _child = task::spawn(proc() { start(&tx) });
let mut c = rx.recv();
- c.send("A".to_strbuf());
- c.send("B".to_strbuf());
+ c.send("A".to_string());
+ c.send("B".to_string());
task::deschedule();
}
fn test_str() {
let (tx, rx) = channel();
- let s0 = "test".to_owned();
+ let s0 = "test".to_string();
tx.send(s0);
let s1 = rx.recv();
assert_eq!(s1.as_slice()[0], 't' as u8);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
use std::task::TaskBuilder;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
use std::task::TaskBuilder;
use std::task;
pub fn main() {
- task::spawn(proc() child("Hello".to_strbuf()) );
+ task::spawn(proc() child("Hello".to_string()) );
}
fn child(_s: String) {
extern crate libc;
extern crate green;
extern crate rustuv;
+extern crate debug;
use std::io::net::tcp::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
// they're in a different location than before. Hence, these tests are all run
// serially here.
+extern crate debug;
+
use std::io::{fs, TempDir};
use std::io;
use std::os;
}
pub fn main() {
- let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_strbuf() };
+ let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
- name: "alan_turing".to_strbuf(),
+ name: "alan_turing".to_string(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
- name: "albert_einstein".to_strbuf(),
+ name: "albert_einstein".to_string(),
};
let fishe = Goldfyshe {
swim_speed: 998,
- name: "alec_guinness".to_strbuf(),
+ name: "alec_guinness".to_string(),
};
let arc = Arc::new(vec!(box catte as Box<Pet:Share+Send>,
box dogge1 as Box<Pet:Share+Send>,
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> String {
match *self {
- None => { "none".to_strbuf() }
+ None => { "none".to_string() }
Some(ref t) => format_strbuf!("some({})", t.to_str_()),
}
}
impl to_str for int {
fn to_str_(&self) -> String {
- self.to_str().to_strbuf()
+ self.to_str().to_string()
}
}
right: Some(t1),
val: box 2 as Box<to_str:Send>}));
let expected =
- "[2, some([1, none, none]), some([1, none, none])]".to_strbuf();
+ "[2, some([1, none, none]), some([1, none, none])]".to_string();
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
fn to_string(&self) -> String;
}
impl to_str for int {
- fn to_string(&self) -> String { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str() }
}
impl to_str for String {
fn to_string(&self) -> String { self.clone() }
}
impl to_str for () {
- fn to_string(&self) -> String { "()".to_strbuf() }
+ fn to_string(&self) -> String { "()".to_string() }
}
trait map<T> {
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
- x.map(|_e| "hi".to_strbuf() )
+ x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string() )
}
pub fn main() {
- assert_eq!(foo(vec!(1)), vec!("hi".to_strbuf()));
- assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_strbuf(), "5".to_strbuf()));
- assert_eq!(bar::<String, Vec<String> >(vec!("x".to_strbuf(), "y".to_strbuf())),
- vec!("x".to_strbuf(), "y".to_strbuf()));
- assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_strbuf()));
+ assert_eq!(foo(vec!(1)), vec!("hi".to_string()));
+ assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
+ assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
+ vec!("x".to_string(), "y".to_string()));
+ assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_string()));
}
}
impl to_str for int {
- fn to_string(&self) -> String { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str().to_string() }
}
impl<T:to_str> to_str for Vec<T> {
}
pub fn main() {
- assert!(1.to_string() == "1".to_strbuf());
- assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_strbuf());
+ assert!(1.to_string() == "1".to_string());
+ assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_string());
fn indirect<T:to_str>(x: T) -> String {
format_strbuf!("{}!", x.to_string())
}
- assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_strbuf());
+ assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_string());
fn indirect2<T:to_str>(x: T) -> String {
indirect(x)
}
- assert!(indirect2(vec!(1)) == "[1]!".to_strbuf());
+ assert!(indirect2(vec!(1)) == "[1]!".to_string());
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
- assert_eq!(Some("hi".to_owned()).do_get2(), ("hi".to_owned(), "hi".to_owned()));
+ assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
}
pub fn main() {
let q = Quux;
- assert_eq!(q.bar(), "test".to_strbuf());
+ assert_eq!(q.bar(), "test".to_string());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
/*
This is about the simplest program that can successfully send a
message.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
struct Foo(int, int);
pub fn main() {
fn empty_pointy() -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
- d : make_uniq_closure("hi".to_owned())
+ d : make_uniq_closure("hi".to_string())
})
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
fn test1() {
enum bar { u(Box<int>), w(int), }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
+
pub fn main() {
let i = box 100;
println!("{:?}", i);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+extern crate debug;
enum bar { u(Box<int>), w(int), }
assert_eq!(pi as int, '\u03a0' as int);
assert_eq!('\x0a' as int, '\n' as int);
- let bhutan: String = "འབྲུག་ཡུལ།".to_strbuf();
- let japan: String = "日本".to_strbuf();
- let uzbekistan: String = "Ўзбекистон".to_strbuf();
- let austria: String = "Österreich".to_strbuf();
+ let bhutan: String = "འབྲུག་ཡུལ།".to_string();
+ let japan: String = "日本".to_string();
+ let uzbekistan: String = "Ўзбекистон".to_string();
+ let austria: String = "Österreich".to_string();
let bhutan_e: String =
- "\u0f60\u0f56\u0fb2\u0f74\u0f42\u0f0b\u0f61\u0f74\u0f63\u0f0d".to_strbuf();
- let japan_e: String = "\u65e5\u672c".to_strbuf();
+ "\u0f60\u0f56\u0fb2\u0f74\u0f42\u0f0b\u0f61\u0f74\u0f63\u0f0d".to_string();
+ let japan_e: String = "\u65e5\u672c".to_string();
let uzbekistan_e: String =
- "\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e\u043d".to_strbuf();
- let austria_e: String = "\u00d6sterreich".to_strbuf();
+ "\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e\u043d".to_string();
+ let austria_e: String = "\u00d6sterreich".to_string();
let oo: char = 'Ö';
assert_eq!(oo as int, 0xd6);
pub fn main() {
// Chars of 1, 2, 3, and 4 bytes
let chs: Vec<char> = vec!('e', 'é', '€', '\U00010000');
- let s: String = str::from_chars(chs.as_slice()).to_strbuf();
+ let s: String = str::from_chars(chs.as_slice()).to_string();
let schs: Vec<char> = s.as_slice().chars().collect();
assert!(s.len() == 10u);
assert!(s.as_slice().char_len() == 4u);
assert!(schs.len() == 4u);
- assert!(str::from_chars(schs.as_slice()).to_strbuf() == s);
+ assert!(str::from_chars(schs.as_slice()).to_string() == s);
assert!(s.as_slice().char_at(0u) == 'e');
assert!(s.as_slice().char_at(1u) == 'é');
fn boldly_go(_crew_member: crew_of_enterprise_d, _where: String) { }
-pub fn main() { boldly_go(worf, "where no one has gone before".to_strbuf()); }
+pub fn main() { boldly_go(worf, "where no one has gone before".to_string()); }
pub fn main() {
let x = [
- Foo { string: "foo".to_strbuf() },
- Foo { string: "bar".to_strbuf() },
- Foo { string: "baz".to_strbuf() }
+ Foo { string: "foo".to_string() },
+ Foo { string: "bar".to_string() },
+ Foo { string: "baz".to_string() }
];
match x {
[ref first, ..tail] => {
- assert!(first.string == "foo".to_strbuf());
+ assert!(first.string == "foo".to_string());
assert_eq!(tail.len(), 2);
- assert!(tail[0].string == "bar".to_strbuf());
- assert!(tail[1].string == "baz".to_strbuf());
+ assert!(tail[0].string == "bar".to_string());
+ assert!(tail[1].string == "baz".to_string());
match tail {
[Foo { .. }, _, Foo { .. }, .. _tail] => {
// except according to those terms.
pub fn main() {
- assert_eq!((vec!(0, 1)).to_str(), "[0, 1]".to_strbuf());
- assert_eq!((&[1, 2]).to_str(), "[1, 2]".to_strbuf());
+ assert_eq!((vec!(0, 1)).to_str(), "[0, 1]".to_string());
+ assert_eq!((&[1, 2]).to_str(), "[1, 2]".to_string());
let foo = vec!(3, 4);
let bar = &[4, 5];
- assert_eq!(foo.to_str(), "[3, 4]".to_strbuf());
- assert_eq!(bar.to_str(), "[4, 5]".to_strbuf());
+ assert_eq!(foo.to_str(), "[3, 4]".to_string());
+ assert_eq!(bar.to_str(), "[4, 5]".to_string());
}