# * check-stage$(stage)-$(crate) - Test a crate in a specific stage
# * check-stage$(stage)-{rpass,rfail,cfail,rmake,...} - Run tests in src/test/
# * check-stage1-T-$(target)-H-$(host) - Run cross-compiled-tests
+# * tidy-basic - show file / line stats
+# * tidy-errors - show the highest rustc error code
+# * tidy-features - show the status of language and lib features
#
# Then mix in some of these environment variables to harness the
# ultimate power of The Rust Build System.
# numbers and dots here
CFG_VERSION_WIN = $(CFG_RELEASE_NUM)
+CFG_INFO := $(info cfg: version $(CFG_VERSION))
######################################################################
# More configuration
ifndef CFG_DISABLE_VALGRIND_RPASS
$(info cfg: enabling valgrind run-pass tests (CFG_ENABLE_VALGRIND_RPASS))
+ $(info cfg: valgrind-rpass command set to $(CFG_VALGRIND))
CFG_VALGRIND_RPASS :=$(CFG_VALGRIND)
else
CFG_VALGRIND_RPASS :=
######################################################################
# The main testing target. Tests lots of stuff.
-check: cleantmptestlogs cleantestlibs check-notidy tidy
+check: cleantmptestlogs cleantestlibs all check-stage2 tidy
+ $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log
# As above but don't bother running tidy.
check-notidy: cleantmptestlogs cleantestlibs all check-stage2
######################################################################
ifdef CFG_NOTIDY
+.PHONY: tidy
tidy:
else
-ALL_CS := $(wildcard $(S)src/rt/*.cpp \
- $(S)src/rt/*/*.cpp \
- $(S)src/rt/*/*/*.cpp \
- $(S)src/rustllvm/*.cpp)
-ALL_CS := $(filter-out $(S)src/rt/miniz.cpp \
- $(wildcard $(S)src/rt/hoedown/src/*.c) \
- $(wildcard $(S)src/rt/hoedown/bin/*.c) \
- ,$(ALL_CS))
-ALL_HS := $(wildcard $(S)src/rt/*.h \
- $(S)src/rt/*/*.h \
- $(S)src/rt/*/*/*.h \
- $(S)src/rustllvm/*.h)
-ALL_HS := $(filter-out $(S)src/rt/valgrind/valgrind.h \
- $(S)src/rt/valgrind/memcheck.h \
- $(S)src/rt/msvc/typeof.h \
- $(S)src/rt/msvc/stdint.h \
- $(S)src/rt/msvc/inttypes.h \
- $(wildcard $(S)src/rt/hoedown/src/*.h) \
- $(wildcard $(S)src/rt/hoedown/bin/*.h) \
- ,$(ALL_HS))
-
# Run the tidy script in multiple parts to avoid huge 'echo' commands
-tidy:
+.PHONY: tidy
+tidy: tidy-basic tidy-binaries tidy-errors tidy-features
+
+endif
+
+.PHONY: tidy-basic
+tidy-basic:
@$(call E, check: formatting)
- $(Q)find $(S)src -name '*.r[sc]' \
- -and -not -regex '^$(S)src/jemalloc.*' \
- -and -not -regex '^$(S)src/libuv.*' \
- -and -not -regex '^$(S)src/llvm.*' \
- -and -not -regex '^$(S)src/gyp.*' \
- -and -not -regex '^$(S)src/libbacktrace.*' \
- -print0 \
- | xargs -0 -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/etc -name '*.py' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/doc -name '*.js' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/etc -name '*.sh' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/etc -name '*.pl' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/etc -name '*.c' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)find $(S)src/etc -name '*.h' \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)echo $(ALL_CS) \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
- $(Q)echo $(ALL_HS) \
- | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
+ $(Q) $(CFG_PYTHON) $(S)src/etc/tidy.py $(S)src/
+
+.PHONY: tidy-binaries
+tidy-binaries:
+ @$(call E, check: binaries)
$(Q)find $(S)src -type f -perm +a+x \
-not -name '*.rs' -and -not -name '*.py' \
-and -not -name '*.sh' \
| grep '^$(S)src/libbacktrace' -v \
| grep '^$(S)src/rust-installer' -v \
| xargs $(CFG_PYTHON) $(S)src/etc/check-binaries.py
- $(Q) $(CFG_PYTHON) $(S)src/etc/errorck.py $(S)src/
- $(Q) $(CFG_PYTHON) $(S)src/etc/featureck.py $(S)src/
+.PHONY: tidy-errors
+tidy-errors:
+ @$(call E, check: extended errors)
+ $(Q) $(CFG_PYTHON) $(S)src/etc/errorck.py $(S)src/
-endif
+.PHONY: tidy-features
+tidy-features:
+ @$(call E, check: feature sanity)
+ $(Q) $(CFG_PYTHON) $(S)src/etc/featureck.py $(S)src/
######################################################################
ifdef CFG_VALGRIND_RPASS
ifdef GOOD_VALGRIND_$(2)
-$(info cfg: valgrind-path set to $(CFG_VALGRIND_RPASS))
CTEST_COMMON_ARGS$(1)-T-$(2)-H-$(3) += --valgrind-path "$(CFG_VALGRIND_RPASS)"
endif
endif
assert!(!args.is_empty());
let argv0 = args[0].clone();
let args_ = args.tail();
- if args[1].as_slice() == "-h" || args[1].as_slice() == "--help" {
+ if args[1] == "-h" || args[1] == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
- println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
+ println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
let matches =
- &match getopts::getopts(args_.as_slice(), groups.as_slice()) {
+ &match getopts::getopts(args_, &groups) {
Ok(m) => m,
Err(f) => panic!("{:?}", f)
};
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
- println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
+ println!("{}", getopts::usage(&message, &groups));
println!("");
panic!()
}
fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
- Path::new(m.opt_str(nm).unwrap())
+ match m.opt_str(nm) {
+ Some(s) => Path::new(s),
+ None => panic!("no option (=path) found for {}", nm),
+ }
}
let filter = if !matches.free.is_empty() {
adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")),
adb_device_status:
"arm-linux-androideabi" ==
- opt_str2(matches.opt_str("target")).as_slice() &&
+ opt_str2(matches.opt_str("target")) &&
"(none)" !=
- opt_str2(matches.opt_str("adb-test-dir")).as_slice() &&
+ opt_str2(matches.opt_str("adb-test-dir")) &&
!opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
lldb_python_dir: matches.opt_str("lldb-python-dir"),
verbose: matches.opt_present("verbose"),
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
- Some(ref s) => s.as_slice(),
+ Some(ref s) => s,
}
}
}
pub fn run_tests(config: &Config) {
- if config.target.as_slice() == "arm-linux-androideabi" {
+ if config.target == "arm-linux-androideabi" {
match config.mode {
DebugInfoGdb => {
println!("arm-linux-androideabi debug-info \
let mut valid = false;
for ext in &valid_extensions {
- if name.ends_with(ext.as_slice()) {
+ if name.ends_with(ext) {
valid = true;
}
}
for pre in &invalid_prefixes {
- if name.starts_with(pre.as_slice()) {
+ if name.starts_with(pre) {
valid = false;
}
}
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_string();
- test::DynMetricFn(box move |: mm: &mut test::MetricMap| {
+ test::DynMetricFn(box move |mm: &mut test::MetricMap| {
runtest::run_metrics(config, testfile, mm)
})
}
rdr.lines().enumerate().filter_map(|(line_no, ln)| {
parse_expected(last_nonfollow_error,
line_no + 1,
- ln.unwrap().as_slice())
+ &ln.unwrap())
.map(|(which, error)| {
match which {
FollowPrevious(_) => {}
pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
fn ignore_target(config: &Config) -> String {
- format!("ignore-{}", util::get_os(config.target.as_slice()))
+ format!("ignore-{}", util::get_os(&config.target))
}
fn ignore_stage(config: &Config) -> String {
format!("ignore-{}",
.expect("Malformed GDB version directive");
// Ignore if actual version is smaller the minimum required
// version
- gdb_version_to_int(actual_version.as_slice()) <
- gdb_version_to_int(min_version.as_slice())
+ gdb_version_to_int(actual_version) <
+ gdb_version_to_int(min_version)
} else {
false
}
.expect("Malformed lldb version directive");
// Ignore if actual version is smaller the minimum required
// version
- lldb_version_to_int(actual_version.as_slice()) <
- lldb_version_to_int(min_version.as_slice())
+ lldb_version_to_int(actual_version) <
+ lldb_version_to_int(min_version)
} else {
false
}
let val = iter_header(testfile, |ln| {
!parse_name_directive(ln, "ignore-test") &&
- !parse_name_directive(ln, ignore_target(config).as_slice()) &&
- !parse_name_directive(ln, ignore_stage(config).as_slice()) &&
+ !parse_name_directive(ln, &ignore_target(config)) &&
+ !parse_name_directive(ln, &ignore_stage(config)) &&
!(config.mode == common::Pretty && parse_name_directive(ln, "ignore-pretty")) &&
!(config.target != config.host && parse_name_directive(ln, "ignore-cross-compile")) &&
!ignore_gdb(config, ln) &&
fn parse_exec_env(line: &str) -> Option<(String, String)> {
parse_name_value_directive(line, "exec-env").map(|nv| {
// nv is either FOO or FOO=BAR
- let mut strs: Vec<String> = nv.as_slice()
+ let mut strs: Vec<String> = nv
.splitn(1, '=')
.map(|s| s.to_string())
.collect();
pub fn parse_name_value_directive(line: &str, directive: &str)
-> Option<String> {
let keycolon = format!("{}:", directive);
- match line.find_str(keycolon.as_slice()) {
+ match line.find_str(&keycolon) {
Some(colon) => {
let value = line[(colon + keycolon.len()) .. line.len()].to_string();
debug!("{}: {}", directive, value);
let error_string = format!(
"Encountered GDB version string with unexpected format: {}",
version_string);
- let error_string = error_string.as_slice();
+ let error_string = error_string;
let components: Vec<&str> = version_string.trim().split('.').collect();
panic!("{}", error_string);
}
- let major: int = components[0].parse().ok().expect(error_string);
- let minor: int = components[1].parse().ok().expect(error_string);
+ let major: int = components[0].parse().ok().expect(&error_string);
+ let minor: int = components[1].parse().ok().expect(&error_string);
return major * 1000 + minor;
}
let error_string = format!(
"Encountered LLDB version string with unexpected format: {}",
version_string);
- let error_string = error_string.as_slice();
- let major: int = version_string.parse().ok().expect(error_string);
+ let error_string = error_string;
+ let major: int = version_string.parse().ok().expect(&error_string);
return major;
}
// Add the new dylib search path var
let var = DynamicLibrary::envvar();
- let newpath = DynamicLibrary::create_path(path.as_slice());
+ let newpath = DynamicLibrary::create_path(&path);
let newpath = String::from_utf8(newpath).unwrap();
cmd.env(var.to_string(), newpath);
}
use test::MetricMap;
pub fn run(config: Config, testfile: String) {
- match config.target.as_slice() {
+ match &*config.target {
"arm-linux-androideabi" => {
if !config.adb_device_status {
}
check_expected_errors(expected_errors, testfile, &proc_res);
} else {
- check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
+ check_error_patterns(props, testfile, &output_to_check, &proc_res);
}
check_no_compiler_crash(&proc_res);
- check_forbid_output(props, output_to_check.as_slice(), &proc_res);
+ check_forbid_output(props, &output_to_check, &proc_res);
}
fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
let output_to_check = get_output(props, &proc_res);
check_correct_failure_status(&proc_res);
- check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
+ check_error_patterns(props, testfile, &output_to_check, &proc_res);
}
fn check_correct_failure_status(proc_res: &ProcRes) {
static RUST_ERR: int = 101;
if !proc_res.status.matches_exit_status(RUST_ERR) {
fatal_proc_rec(
- format!("failure produced the wrong error: {:?}",
- proc_res.status).as_slice(),
+ &format!("failure produced the wrong error: {:?}",
+ proc_res.status),
proc_res);
}
}
props,
testfile,
srcs[round].to_string(),
- props.pretty_mode.as_slice());
+ &props.pretty_mode);
if !proc_res.status.success() {
- fatal_proc_rec(format!("pretty-printing failed in round {}",
- round).as_slice(),
+ fatal_proc_rec(&format!("pretty-printing failed in round {}", round),
&proc_res);
}
if props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = "\r".to_string();
- actual = actual.replace(cr.as_slice(), "").to_string();
- expected = expected.replace(cr.as_slice(), "").to_string();
+ actual = actual.replace(&cr, "").to_string();
+ expected = expected.replace(&cr, "").to_string();
}
- compare_source(expected.as_slice(), actual.as_slice());
+ compare_source(&expected, &actual);
// If we're only making sure that the output matches then just stop here
if props.pretty_compare_only { return; }
testfile,
pretty_type.to_string()),
props.exec_env.clone(),
- config.compile_lib_path.as_slice(),
+ &config.compile_lib_path,
Some(aux_dir.as_str().unwrap()),
Some(src))
}
fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> ProcArgs {
let aux_dir = aux_output_dir_name(config, testfile);
let target = if props.force_host {
- config.host.as_slice()
+ &*config.host
} else {
- config.target.as_slice()
+ &*config.target
};
// FIXME (#9639): This needs to handle non-utf8 paths
let mut args = vec!("-".to_string(),
let exe_file = make_exe_name(config, testfile);
let debugger_run_result;
- match config.target.as_slice() {
+ match &*config.target {
"arm-linux-androideabi" => {
cmds = cmds.replace("run", "continue").to_string();
debug!("script_str = {}", script_str);
dump_output_file(config,
testfile,
- script_str.as_slice(),
+ &script_str,
"debugger.script");
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
&[
"push".to_string(),
],
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{:?}`", config.adb_path));
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
&[
"forward".to_string(),
],
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{:?}`", config.adb_path));
let adb_arg = format!("export LD_LIBRARY_PATH={}; \
gdbserver :5039 {}/{}",
.unwrap()).unwrap());
let mut process = procsrv::run_background("",
- config.adb_path
- .as_slice(),
+ &config.adb_path
+ ,
None,
&[
"shell".to_string(),
vec!(("".to_string(),
"".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{:?}`", config.adb_path));
loop {
//waiting 1 second for gdbserver start
timer::sleep(Duration::milliseconds(1000));
err,
status
} = procsrv::run("",
- gdb_path.as_slice(),
+ &gdb_path,
None,
- debugger_opts.as_slice(),
+ &debugger_opts,
vec!(("".to_string(), "".to_string())),
None)
- .expect(format!("failed to exec `{:?}`", gdb_path).as_slice());
+ .expect(&format!("failed to exec `{:?}`", gdb_path));
let cmdline = {
let cmdline = make_cmdline("",
"arm-linux-androideabi-gdb",
- debugger_opts.as_slice());
+ &debugger_opts);
logv(config, format!("executing {}", cmdline));
cmdline
};
match config.gdb_version {
Some(ref version) => {
println!("NOTE: compiletest thinks it is using GDB version {}",
- version.as_slice());
+ version);
- if header::gdb_version_to_int(version.as_slice()) >
+ if header::gdb_version_to_int(version) >
header::gdb_version_to_int("7.4") {
// Add the directory containing the pretty printers to
// GDB's script auto loading safe path
script_str.push_str(
- format!("add-auto-load-safe-path {}\n",
- rust_pp_module_abs_path.replace("\\", "\\\\").as_slice())
- .as_slice());
+ &format!("add-auto-load-safe-path {}\n",
+ rust_pp_module_abs_path.replace("\\", "\\\\"))
+ );
}
}
_ => {
*line)[]);
}
- script_str.push_str(cmds.as_slice());
+ script_str.push_str(&cmds);
script_str.push_str("quit\n");
debug!("script_str = {}", script_str);
dump_output_file(config,
testfile,
- script_str.as_slice(),
+ &script_str,
"debugger.script");
// run debugger script with gdb
testfile,
proc_args,
environment,
- config.run_lib_path.as_slice(),
+ &config.run_lib_path,
None,
None);
}
fatal("gdb failed to execute");
}
- check_debugger_output(&debugger_run_result, check_lines.as_slice());
+ check_debugger_output(&debugger_run_result, &check_lines);
}
fn find_rust_src_root(config: &Config) -> Option<Path> {
match config.lldb_version {
Some(ref version) => {
println!("NOTE: compiletest thinks it is using LLDB version {}",
- version.as_slice());
+ version);
}
_ => {
println!("NOTE: compiletest does not know which version of \
// Set breakpoints on every line that contains the string "#break"
for line in &breakpoint_lines {
- script_str.push_str(format!("breakpoint set --line {}\n",
- line).as_slice());
+ script_str.push_str(&format!("breakpoint set --line {}\n", line));
}
// Append the other commands
for line in &commands {
- script_str.push_str(line.as_slice());
+ script_str.push_str(line);
script_str.push_str("\n");
}
debug!("script_str = {}", script_str);
dump_output_file(config,
testfile,
- script_str.as_slice(),
+ &script_str,
"debugger.script");
let debugger_script = make_out_name(config, testfile, "debugger.script");
fatal_proc_rec("Error while running LLDB", &debugger_run_result);
}
- check_debugger_output(&debugger_run_result, check_lines.as_slice());
+ check_debugger_output(&debugger_run_result, &check_lines);
fn run_lldb(config: &Config,
test_executable: &Path,
cmd.arg(lldb_script_path)
.arg(test_executable)
.arg(debugger_script)
- .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap().as_slice())]);
+ .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap())]);
let (status, out, err) = match cmd.spawn() {
Ok(process) => {
String::from_utf8(error).unwrap())
},
Err(e) => {
- fatal(format!("Failed to setup Python process for \
- LLDB script: {}", e).as_slice())
+ fatal(&format!("Failed to setup Python process for \
+ LLDB script: {}", e))
}
};
- dump_output(config, test_executable, out.as_slice(), err.as_slice());
+ dump_output(config, test_executable, &out, &err);
return ProcRes {
status: status,
stdout: out,
}
header::parse_name_value_directive(
- line.as_slice(),
- command_directive.as_slice()).map(|cmd| {
+ &line,
+ &command_directive).map(|cmd| {
commands.push(cmd)
});
header::parse_name_value_directive(
- line.as_slice(),
- check_directive.as_slice()).map(|cmd| {
+ &line,
+ &check_directive).map(|cmd| {
check_lines.push(cmd)
});
}
Err(e) => {
- fatal(format!("Error while parsing debugger commands: {}",
- e).as_slice())
+ fatal(&format!("Error while parsing debugger commands: {}", e))
}
}
counter += 1;
// bits in the wrong case of an enum) with the notation "[...]".
let check_fragments: Vec<Vec<String>> =
check_lines.iter().map(|s| {
- s.as_slice()
+ s
.trim()
.split_str("[...]")
.map(|x| x.to_string())
let mut failed = false;
for frag in &check_fragments[i] {
let found = if first {
- if rest.starts_with(frag.as_slice()) {
+ if rest.starts_with(frag) {
Some(0)
} else {
None
}
} else {
- rest.find_str(frag.as_slice())
+ rest.find_str(frag)
};
match found {
None => {
}
}
if i != num_check_lines {
- fatal_proc_rec(format!("line not found in debugger output: {}",
- check_lines.get(i).unwrap()).as_slice(),
+ fatal_proc_rec(&format!("line not found in debugger output: {}",
+ check_lines.get(i).unwrap()),
debugger_run_result);
}
}
output_to_check: &str,
proc_res: &ProcRes) {
if props.error_patterns.is_empty() {
- fatal(format!("no error pattern specified in {:?}",
- testfile.display()).as_slice());
+ fatal(&format!("no error pattern specified in {:?}", testfile.display()));
}
let mut next_err_idx = 0;
let mut next_err_pat = &props.error_patterns[next_err_idx];
let mut done = false;
for line in output_to_check.lines() {
- if line.contains(next_err_pat.as_slice()) {
+ if line.contains(next_err_pat) {
debug!("found error pattern {}", next_err_pat);
next_err_idx += 1;
if next_err_idx == props.error_patterns.len() {
let missing_patterns = &props.error_patterns[next_err_idx..];
if missing_patterns.len() == 1 {
- fatal_proc_rec(format!("error pattern '{}' not found!",
- missing_patterns[0]).as_slice(),
+ fatal_proc_rec(&format!("error pattern '{}' not found!", missing_patterns[0]),
proc_res);
} else {
for pattern in missing_patterns {
- error(format!("error pattern '{}' not found!",
- *pattern).as_slice());
+ error(&format!("error pattern '{}' not found!", *pattern));
}
fatal_proc_rec("multiple error patterns not found", proc_res);
}
output_to_check: &str,
proc_res: &ProcRes) {
for pat in &props.forbid_output {
- if output_to_check.contains(pat.as_slice()) {
+ if output_to_check.contains(pat) {
fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
}
}
#[cfg(windows)]
fn prefix_matches( line : &str, prefix : &str ) -> bool {
- line.to_ascii_lowercase().starts_with(prefix.to_ascii_lowercase().as_slice())
+ line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
}
#[cfg(unix)]
for (i, ee) in expected_errors.iter().enumerate() {
if !found_flags[i] {
debug!("prefix={} ee.kind={} ee.msg={} line={}",
- prefixes[i].as_slice(),
+ prefixes[i],
ee.kind,
ee.msg,
line);
- if (prefix_matches(line, prefixes[i].as_slice()) || continuation(line)) &&
- line.contains(ee.kind.as_slice()) &&
- line.contains(ee.msg.as_slice()) {
+ if (prefix_matches(line, &prefixes[i]) || continuation(line)) &&
+ line.contains(&ee.kind) &&
+ line.contains(&ee.msg) {
found_flags[i] = true;
was_expected = true;
break;
}
if !was_expected && is_compiler_error_or_warning(line) {
- fatal_proc_rec(format!("unexpected compiler error or warning: '{}'",
- line).as_slice(),
+ fatal_proc_rec(&format!("unexpected compiler error or warning: '{}'",
+ line),
proc_res);
}
}
for (i, &flag) in found_flags.iter().enumerate() {
if !flag {
let ee = &expected_errors[i];
- fatal_proc_rec(format!("expected {} on line {} not found: {}",
- ee.kind, ee.line, ee.msg).as_slice(),
+ fatal_proc_rec(&format!("expected {} on line {} not found: {}",
+ ee.kind, ee.line, ee.msg),
proc_res);
}
}
let env = props.exec_env.clone();
- match config.target.as_slice() {
+ match &*config.target {
"arm-linux-androideabi" => {
_arm_exec_compiled_test(config, props, testfile, env)
testfile,
make_run_args(config, props, testfile),
env,
- config.run_lib_path.as_slice(),
+ &config.run_lib_path,
Some(aux_dir.as_str().unwrap()),
None)
}
let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
for rel_ab in &props.aux_builds {
- let abs_ab = config.aux_base.join(rel_ab.as_slice());
+ let abs_ab = config.aux_base.join(rel_ab);
let aux_props = header::load_props(&abs_ab);
let mut crate_type = if aux_props.no_prefer_dynamic {
Vec::new()
&abs_ab,
aux_args,
Vec::new(),
- config.compile_lib_path.as_slice(),
+ &config.compile_lib_path,
Some(aux_dir.as_str().unwrap()),
None);
if !auxres.status.success() {
fatal_proc_rec(
- format!("auxiliary build of {:?} failed to compile: ",
- abs_ab.display()).as_slice(),
+ &format!("auxiliary build of {:?} failed to compile: ",
+ abs_ab.display()),
&auxres);
}
- match config.target.as_slice() {
+ match &*config.target {
"arm-linux-androideabi" => {
_arm_push_aux_shared_library(config, testfile);
}
testfile,
args,
Vec::new(),
- config.compile_lib_path.as_slice(),
+ &config.compile_lib_path,
Some(aux_dir.as_str().unwrap()),
input)
}
{
let xform_file = xform(config, testfile);
let target = if props.force_host {
- config.host.as_slice()
+ &*config.host
} else {
- config.target.as_slice()
+ &*config.target
};
// FIXME (#9639): This needs to handle non-utf8 paths
let mut args = vec!(testfile.as_str().unwrap().to_string(),
"-L".to_string(),
config.build_base.as_str().unwrap().to_string(),
format!("--target={}", target));
- args.push_all(extras.as_slice());
+ args.push_all(&extras);
if !props.no_prefer_dynamic {
args.push("-C".to_string());
args.push("prefer-dynamic".to_string());
fn split_maybe_args(argstr: &Option<String>) -> Vec<String> {
match *argstr {
Some(ref s) => {
- s.as_slice()
+ s
.split(' ')
.filter_map(|s| {
if s.chars().all(|c| c.is_whitespace()) {
let cmdline =
{
let cmdline = make_cmdline(lib_path,
- prog.as_slice(),
- args.as_slice());
+ &prog,
+ &args);
logv(config, format!("executing {}", cmdline));
cmdline
};
err,
status
} = procsrv::run(lib_path,
- prog.as_slice(),
+ &prog,
aux_path,
- args.as_slice(),
+ &args,
env,
- input).expect(format!("failed to exec `{}`", prog).as_slice());
- dump_output(config, testfile, out.as_slice(), err.as_slice());
+ input).expect(&format!("failed to exec `{}`", prog));
+ dump_output(config, testfile, &out, &err);
return ProcRes {
status: status,
stdout: out,
fn output_base_name(config: &Config, testfile: &Path) -> Path {
config.build_base
.join(&output_testname(testfile))
- .with_extension(config.stage_id.as_slice())
+ .with_extension(&config.stage_id)
}
fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {
-> ProcRes {
let args = make_run_args(config, props, testfile);
let cmdline = make_cmdline("",
- args.prog.as_slice(),
- args.args.as_slice());
+ &args.prog,
+ &args.args);
// get bare program string
let mut tvec: Vec<String> = args.prog
- .as_slice()
.split('/')
.map(|ts| ts.to_string())
.collect();
// copy to target
let copy_result = procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
&[
"push".to_string(),
],
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
if config.verbose {
println!("push ({}) {} {} {}",
runargs.push(tv.to_string());
}
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
- runargs.as_slice(),
+ &runargs,
vec!(("".to_string(), "".to_string())), Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
// get exitcode of result
runargs = Vec::new();
let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
- runargs.as_slice(),
+ &runargs,
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
let mut exitcode: int = 0;
for c in exitcode_out.chars() {
let procsrv::Result{ out: stdout_out, err: _, status: _ } =
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
- runargs.as_slice(),
+ &runargs,
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
// get stderr of result
runargs = Vec::new();
let procsrv::Result{ out: stderr_out, err: _, status: _ } =
procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
- runargs.as_slice(),
+ &runargs,
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
dump_output(config,
testfile,
- stdout_out.as_slice(),
- stderr_out.as_slice());
+ &stdout_out,
+ &stderr_out);
ProcRes {
status: process::ProcessExit::ExitStatus(exitcode),
if file.extension_str() == Some("so") {
// FIXME (#9639): This needs to handle non-utf8 paths
let copy_result = procsrv::run("",
- config.adb_path.as_slice(),
+ &config.adb_path,
None,
&[
"push".to_string(),
vec!(("".to_string(),
"".to_string())),
Some("".to_string()))
- .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+ .expect(&format!("failed to exec `{}`", config.adb_path));
if config.verbose {
println!("push ({}) {:?} {} {}",
fn count_extracted_lines(p: &Path) -> uint {
let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
- let x = str::from_utf8(x.as_slice()).unwrap();
+ let x = str::from_utf8(&x).unwrap();
x.lines().count()
}
`phrases::japanese::farewells::goodbye()`. Our internal organization doesn't
define our external interface.
+Here we have a `pub use` for each function we want to bring into the
+`japanese` scope. We could alternatively use the wildcard syntax to include
+everything from `greetings` into the current scope: `pub use self::greetings::*`.
+
Also, note that we `pub use`d before we declared our `mod`s. Rust requires that
`use` declarations go first.
import os
import re
+if len(sys.argv) < 2:
+ print "usage: errorck.py <src-dir>"
+ sys.exit(1)
+
src_dir = sys.argv[1]
errcode_map = {}
error_re = re.compile("(E\d\d\d\d)")
print("{1}: {2}\n{3}".format(*entry))
errors = True
-print("{0} error codes".format(len(errcode_map)))
-print("highest error code: " + max(all_errors))
+print
+print("* {0} error codes".format(len(errcode_map)))
+print("* highest error code: " + max(all_errors))
+print
if errors:
sys.exit(1)
import sys, os, re
+if len(sys.argv) < 2:
+ print "usage: featurkck.py <src-dir>"
+ sys.exit(1)
+
src_dir = sys.argv[1]
# Features that are allowed to exist in both the language and the library
lines.sort()
-print
-print "Rust feature summary:"
print
for line in lines:
- print line
+ print "* " + line
print
\\1 except according to those terms.""")
exceptions = [
- "rt/rust_android_dummy.cpp", # BSD, chromium
- "rt/rust_android_dummy.h", # BSD, chromium
- "rt/isaac/randport.cpp", # public domain
- "rt/isaac/rand.h", # public domain
- "rt/isaac/standard.h", # public domain
"libstd/sync/mpsc/mpsc_queue.rs", # BSD
"libstd/sync/mpsc/spsc_queue.rs", # BSD
"test/bench/shootout-binarytrees.rs", # BSD
if not check_license(name, contents):
report_error_name_no(name, 1, "incorrect license")
-
-file_names = [s for s in sys.argv[1:] if (not s.endswith("_gen.rs"))
- and (not ".#" in s)]
-
current_name = ""
current_contents = ""
check_tab = True
check_cr = True
check_linelength = True
+if len(sys.argv) < 2:
+ print "usage: tidy.py <src-dir>"
+ sys.exit(1)
+
+src_dir = sys.argv[1]
try:
- for line in fileinput.input(file_names,
+ count_lines = 0
+ count_non_blank_lines = 0
+
+ interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+
+ file_counts = {ext: 0 for ext in interesting_files}
+ file_counts['other'] = 0
+
+ def update_counts(current_name):
+ global file_counts
+ _, ext = os.path.splitext(current_name)
+
+ if ext in file_counts:
+ file_counts[ext] += 1
+ else:
+ file_counts['other'] += 1
+
+ all_paths = set()
+
+ for (dirpath, dirnames, filenames) in os.walk(src_dir):
+
+ # Skip some third-party directories
+ skippable_dirs = {
+ 'src/jemalloc',
+ 'src/llvm',
+ 'src/gyp',
+ 'src/libbacktrace',
+ 'src/libuv',
+ 'src/compiler-rt',
+ 'src/rt/hoedown',
+ 'src/rustllvm',
+ 'src/rt/valgrind',
+ 'src/rt/msvc',
+ 'src/rust-installer'
+ }
+
+ if any(d in dirpath for d in skippable_dirs):
+ continue
+
+ def interesting_file(f):
+ if "miniz.c" in f \
+ or "jquery" in f \
+ or "rust_android_dummy" in f:
+ return False
+
+ return any(os.path.splitext(f)[1] == ext for ext in interesting_files)
+
+ file_names = [os.path.join(dirpath, f) for f in filenames
+ if interesting_file(f)
+ and not f.endswith("_gen.rs")
+ and not ".#" is f]
+
+ if not file_names:
+ continue
+
+ for line in fileinput.input(file_names,
openhook=fileinput.hook_encoded("utf-8")):
- if "tidy.py" not in fileinput.filename():
+ filename = fileinput.filename()
+
+ if "tidy.py" not in filename:
+ if "TODO" in line:
+ report_err("TODO is deprecated; use FIXME")
+ match = re.match(r'^.*/(\*|/!?)\s*XXX', line)
+ if match:
+ report_err("XXX is no longer necessary, use FIXME")
+ match = re.match(r'^.*//\s*(NOTE.*)$', line)
+ if match and "TRAVIS" not in os.environ:
+ m = match.group(1)
+ if "snap" in m.lower():
+ report_warn(match.group(1))
+ match = re.match(r'^.*//\s*SNAP\s+(\w+)', line)
+ if match:
+ hsh = match.group(1)
+ date, rev = snapshot.curr_snapshot_rev()
+ if not hsh.startswith(rev):
+ report_err("snapshot out of date (" + date
+ + "): " + line)
+ else:
+ if "SNAP" in line:
+ report_warn("unmatched SNAP line: " + line)
+
if cr_flag in line:
check_cr = False
if tab_flag in line:
check_tab = False
if linelength_flag in line:
check_linelength = False
- if "TODO" in line:
- report_err("TODO is deprecated; use FIXME")
- match = re.match(r'^.*/(\*|/!?)\s*XXX', line)
- if match:
- report_err("XXX is no longer necessary, use FIXME")
- match = re.match(r'^.*//\s*(NOTE.*)$', line)
- if match and "TRAVIS" not in os.environ:
- m = match.group(1)
- if "snap" in m.lower():
- report_warn(match.group(1))
- match = re.match(r'^.*//\s*SNAP\s+(\w+)', line)
- if match:
- hsh = match.group(1)
- date, rev = snapshot.curr_snapshot_rev()
- if not hsh.startswith(rev):
- report_err("snapshot out of date (" + date
- + "): " + line)
- else:
- if "SNAP" in line:
- report_warn("unmatched SNAP line: " + line)
-
- if check_tab and ('\t' in line and
- "Makefile" not in fileinput.filename()):
- report_err("tab character")
- if check_cr and not autocrlf and '\r' in line:
- report_err("CR character")
- if line.endswith(" \n") or line.endswith("\t\n"):
- report_err("trailing whitespace")
- line_len = len(line)-2 if autocrlf else len(line)-1
-
- if check_linelength and line_len > cols:
- report_err("line longer than %d chars" % cols)
-
- if fileinput.isfirstline() and current_name != "":
- do_license_check(current_name, current_contents)
-
- if fileinput.isfirstline():
- current_name = fileinput.filename()
- current_contents = ""
- check_cr = True
- check_tab = True
- check_linelength = True
-
- current_contents += line
+
+ if check_tab and ('\t' in line and
+ "Makefile" not in filename):
+ report_err("tab character")
+ if check_cr and not autocrlf and '\r' in line:
+ report_err("CR character")
+ if line.endswith(" \n") or line.endswith("\t\n"):
+ report_err("trailing whitespace")
+ line_len = len(line)-2 if autocrlf else len(line)-1
+
+ if check_linelength and line_len > cols:
+ report_err("line longer than %d chars" % cols)
+
+ if fileinput.isfirstline():
+ # This happens at the end of each file except the last.
+ if current_name != "":
+ update_counts(current_name)
+ assert len(current_contents) > 0
+ do_license_check(current_name, current_contents)
+
+ current_name = filename
+ current_contents = ""
+ check_cr = True
+ check_tab = True
+ check_linelength = True
+
+ # Put a reasonable limit on the amount of header data we use for
+ # the licenseck
+ if len(current_contents) < 1000:
+ current_contents += line
+
+ count_lines += 1
+ if line.strip():
+ count_non_blank_lines += 1
if current_name != "":
+ update_counts(current_name)
+ assert len(current_contents) > 0
do_license_check(current_name, current_contents)
except UnicodeDecodeError as e:
report_err("UTF-8 decoding error " + str(e))
+print
+for ext in file_counts:
+ print "* linted " + str(file_counts[ext]) + " " + ext + " files"
+print "* total lines of code: " + str(count_lines)
+print "* total non-blank lines of code: " + str(count_non_blank_lines)
+print
sys.exit(err)
#!/bin/sh
+# ignore-license
+
# Run the reference lexer against libsyntax and compare the tokens and spans.
# If "// ignore-lexer-test" is present in the file, it will be ignored.
# <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-tidy-linelength
+
import sys
import os
let toknum = &s[content_end + 3 .. toknum_end];
let proto_tok = tokens.get(toknum).expect(format!("didn't find token {:?} in the map",
- toknum).as_slice());
+ toknum));
let nm = parse::token::intern(content);
let args = std::os::args();
- let mut token_file = File::open(&Path::new(args[2].as_slice()));
- let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice());
+ let mut token_file = File::open(&Path::new(args[2]));
+ let token_map = parse_token_list(token_file.read_to_string().unwrap());
let mut stdin = std::io::stdin();
let mut lock = stdin.lock();
let mut antlr_tokens = lines.map(|l| parse_antlr_token(l.unwrap().trim(),
&token_map));
- let code = File::open(&Path::new(args[1].as_slice())).unwrap().read_to_string().unwrap();
+ let code = File::open(&Path::new(args[1])).unwrap().read_to_string().unwrap();
let options = config::basic_options();
let session = session::build_session(options, None,
syntax::diagnostics::registry::Registry::new(&[]));
use core::ptr::{self, PtrExt};
use core::result::Result;
use core::result::Result::{Ok, Err};
+use core::intrinsics::assume;
use heap::deallocate;
impl<T> RcBoxPtr<T> for Rc<T> {
#[inline(always)]
- fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
+ fn inner(&self) -> &RcBox<T> {
+ unsafe {
+ // Safe to assume this here, as if it weren't true, we'd be breaking
+ // the contract anyway.
+ // This allows the null check to be elided in the destructor if we
+ // manipulated the reference count in the same function.
+ if cfg!(not(stage0)) { // NOTE remove cfg after next snapshot
+ assume(!self._ptr.is_null());
+ }
+ &(**self._ptr)
+ }
+ }
}
impl<T> RcBoxPtr<T> for Weak<T> {
#[inline(always)]
- fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
+ fn inner(&self) -> &RcBox<T> {
+ unsafe {
+ // Safe to assume this here, as if it weren't true, we'd be breaking
+ // the contract anyway.
+ // This allows the null check to be elided in the destructor if we
+ // manipulated the reference count in the same function.
+ if cfg!(not(stage0)) { // NOTE remove cfg after next snapshot
+ assume(!self._ptr.is_null());
+ }
+ &(**self._ptr)
+ }
+ }
}
#[cfg(test)]
insert(map, *k);
}
- rng.shuffle(keys.as_mut_slice());
+ rng.shuffle(&mut keys);
// measure
let mut i = 0;
fn test_0_elements() {
let act = Bitv::new();
let exp = Vec::new();
- assert!(act.eq_vec(exp.as_slice()));
+ assert!(act.eq_vec(&exp));
assert!(act.none() && act.all());
}
// Non-empty to non-empty
let v = vec![1,2,3,4,5];
let u = vec![9,8,1,2,3,4,5];
- let mut m = list_from(v.as_slice());
- let mut n = list_from(u.as_slice());
+ let mut m = list_from(&v);
+ let mut n = list_from(&u);
m.append(&mut n);
check_links(&m);
let mut sum = v;
- sum.push_all(u.as_slice());
+ sum.push_all(&u);
assert_eq!(sum.len(), m.len());
for elt in sum {
assert_eq!(m.pop_front(), Some(elt))
// not singleton, forwards
{
let u = vec![1,2,3,4,5];
- let mut m = list_from(u.as_slice());
+ let mut m = list_from(&u);
let mut n = m.split_off(2);
assert_eq!(m.len(), 2);
assert_eq!(n.len(), 3);
// not singleton, backwards
{
let u = vec![1,2,3,4,5];
- let mut m = list_from(u.as_slice());
+ let mut m = list_from(&u);
let mut n = m.split_off(4);
assert_eq!(m.len(), 4);
assert_eq!(n.len(), 1);
// Test on-stack from_fn.
let mut v = (0u..3).map(square).collect::<Vec<_>>();
{
- let v = v.as_slice();
+ let v = v;
assert_eq!(v.len(), 3u);
assert_eq!(v[0], 0u);
assert_eq!(v[1], 1u);
// Test on-heap from_fn.
v = (0u..5).map(square).collect::<Vec<_>>();
{
- let v = v.as_slice();
+ let v = v;
assert_eq!(v.len(), 5u);
assert_eq!(v[0], 0u);
assert_eq!(v[1], 1u);
// Test on-stack from_elem.
let mut v = vec![10u, 10u];
{
- let v = v.as_slice();
+ let v = v;
assert_eq!(v.len(), 2u);
assert_eq!(v[0], 10u);
assert_eq!(v[1], 10u);
// Test on-heap from_elem.
v = vec![20u, 20u, 20u, 20u, 20u, 20u];
{
- let v = v.as_slice();
+ let v = v;
assert_eq!(v[0], 20u);
assert_eq!(v[1], 20u);
assert_eq!(v[2], 20u);
let vec_fixed = [1, 2, 3, 4];
let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
assert_eq!(v_a.len(), 3u);
- let v_a = v_a.as_slice();
+ let v_a = v_a;
assert_eq!(v_a[0], 2);
assert_eq!(v_a[1], 3);
assert_eq!(v_a[2], 4);
let vec_stack: &[_] = &[1, 2, 3];
let v_b = vec_stack[1u..3u].to_vec();
assert_eq!(v_b.len(), 2u);
- let v_b = v_b.as_slice();
+ let v_b = v_b;
assert_eq!(v_b[0], 2);
assert_eq!(v_b[1], 3);
let vec_unique = vec![1, 2, 3, 4, 5, 6];
let v_d = vec_unique[1u..6u].to_vec();
assert_eq!(v_d.len(), 5u);
- let v_d = v_d.as_slice();
+ let v_d = v_d;
assert_eq!(v_d[0], 2);
assert_eq!(v_d[1], 3);
assert_eq!(v_d[2], 4);
let mut v = vec![];
v.push(1);
assert_eq!(v.len(), 1u);
- assert_eq!(v.as_slice()[0], 1);
+ assert_eq!(v[0], 1);
// Test on-heap push().
v.push(2);
assert_eq!(v.len(), 2u);
- assert_eq!(v.as_slice()[0], 1);
- assert_eq!(v.as_slice()[1], 2);
+ assert_eq!(v[0], 1);
+ assert_eq!(v[1], 2);
}
#[test]
fn test_truncate() {
let mut v = vec![box 6,box 5,box 4];
v.truncate(1);
- let v = v.as_slice();
+ let v = v;
assert_eq!(v.len(), 1);
assert_eq!(*(v[0]), 6);
// If the unsafe block didn't drop things properly, we blow up here.
($x:expr, $x_str:expr) => ({
let (x, x_str) = ($x, $x_str);
assert_eq!(format!("{:?}", x), x_str);
- assert_eq!(format!("{:?}", x.as_slice()), x_str);
+ assert_eq!(format!("{:?}", x), x_str);
})
}
let empty: Vec<int> = vec![];
fn starts_with_same_vector(b: &mut Bencher) {
let vec: Vec<uint> = (0u..100).collect();
b.iter(|| {
- vec.starts_with(vec.as_slice())
+ vec.starts_with(&vec)
})
}
fn starts_with_single_element(b: &mut Bencher) {
let vec: Vec<uint> = vec![0];
b.iter(|| {
- vec.starts_with(vec.as_slice())
+ vec.starts_with(&vec)
})
}
let mut match_vec: Vec<uint> = (0u..99).collect();
match_vec.push(0);
b.iter(|| {
- vec.starts_with(match_vec.as_slice())
+ vec.starts_with(&match_vec)
})
}
fn ends_with_same_vector(b: &mut Bencher) {
let vec: Vec<uint> = (0u..100).collect();
b.iter(|| {
- vec.ends_with(vec.as_slice())
+ vec.ends_with(&vec)
})
}
fn ends_with_single_element(b: &mut Bencher) {
let vec: Vec<uint> = vec![0];
b.iter(|| {
- vec.ends_with(vec.as_slice())
+ vec.ends_with(&vec)
})
}
fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
let vec: Vec<uint> = (0u..100).collect();
let mut match_vec: Vec<uint> = (0u..100).collect();
- match_vec.as_mut_slice()[0] = 200;
+ match_vec[0] = 200;
b.iter(|| {
- vec.starts_with(match_vec.as_slice())
+ vec.starts_with(&match_vec)
})
}
let mut rng = weak_rng();
b.iter(|| {
let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
- v.as_mut_slice().sort();
+ v.sort();
});
b.bytes = 5 * mem::size_of::<u64>() as u64;
}
let mut rng = weak_rng();
b.iter(|| {
let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
- v.as_mut_slice().sort();
+ v.sort();
});
b.bytes = 100 * mem::size_of::<u64>() as u64;
}
let mut rng = weak_rng();
b.iter(|| {
let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
- v.as_mut_slice().sort();
+ v.sort();
});
b.bytes = 10000 * mem::size_of::<u64>() as u64;
}
let buffer = &mut self.buffer;
let sorted = &mut self.sorted;
{
- let callback = |&mut: d| {
+ let callback = |d| {
let class =
unicode::char::canonical_combining_class(d);
if class == 0 && !*sorted {
- canonical_sort(buffer.as_mut_slice());
+ canonical_sort(buffer);
*sorted = true;
}
buffer.push((d, class));
}
if !self.sorted {
- canonical_sort(self.buffer.as_mut_slice());
+ canonical_sort(&mut self.buffer);
self.sorted = true;
}
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
///
- /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).collect();
+ /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
/// assert_eq!(v, vec!["abc", "def", "ghi"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
/// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
/// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
///
- /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |&: c: char| c.is_numeric()).collect();
+ /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
/// assert_eq!(v, vec!["abc", "def2ghi"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
/// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
///
- /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).rev().collect();
+ /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).rev().collect();
/// assert_eq!(v, vec!["ghi", "def", "abc"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
/// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
///
- /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |&: c: char| c.is_numeric()).collect();
+ /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
/// assert_eq!(v, vec!["ghi", "abc1def"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
/// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
/// let x: &[_] = &['1', '2'];
/// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
- /// assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
+ /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn trim_matches<P: CharEq>(&self, pat: P) -> &str {
/// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
/// let x: &[_] = &['1', '2'];
/// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
- /// assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
+ /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn trim_left_matches<P: CharEq>(&self, pat: P) -> &str {
/// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
/// let x: &[_] = &['1', '2'];
/// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
- /// assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
+ /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn trim_right_matches<P: CharEq>(&self, pat: P) -> &str {
/// assert_eq!(s.find('é'), Some(14));
///
/// // the first space
- /// assert_eq!(s.find(|&: c: char| c.is_whitespace()), Some(5));
+ /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
///
/// // neither are found
/// let x: &[_] = &['1', '2'];
/// assert_eq!(s.rfind('é'), Some(14));
///
/// // the second space
- /// assert_eq!(s.rfind(|&: c: char| c.is_whitespace()), Some(12));
+ /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
///
/// // searches for an occurrence of either `1` or `2`, but neither are found
/// let x: &[_] = &['1', '2'];
#[test]
fn test_find() {
assert_eq!("hello".find('l'), Some(2u));
- assert_eq!("hello".find(|&: c:char| c == 'o'), Some(4u));
+ assert_eq!("hello".find(|c:char| c == 'o'), Some(4u));
assert!("hello".find('x').is_none());
- assert!("hello".find(|&: c:char| c == 'x').is_none());
+ assert!("hello".find(|c:char| c == 'x').is_none());
assert_eq!("ประเทศไทย中华Việt Nam".find('华'), Some(30u));
- assert_eq!("ประเทศไทย中华Việt Nam".find(|&: c: char| c == '华'), Some(30u));
+ assert_eq!("ประเทศไทย中华Việt Nam".find(|c: char| c == '华'), Some(30u));
}
#[test]
fn test_rfind() {
assert_eq!("hello".rfind('l'), Some(3u));
- assert_eq!("hello".rfind(|&: c:char| c == 'o'), Some(4u));
+ assert_eq!("hello".rfind(|c:char| c == 'o'), Some(4u));
assert!("hello".rfind('x').is_none());
- assert!("hello".rfind(|&: c:char| c == 'x').is_none());
+ assert!("hello".rfind(|c:char| c == 'x').is_none());
assert_eq!("ประเทศไทย中华Việt Nam".rfind('华'), Some(30u));
- assert_eq!("ประเทศไทย中华Việt Nam".rfind(|&: c: char| c == '华'), Some(30u));
+ assert_eq!("ประเทศไทย中华Việt Nam".rfind(|c: char| c == '华'), Some(30u));
}
#[test]
fn test_concat_for_different_types() {
test_concat!("ab", vec![s("a"), s("b")]);
test_concat!("ab", vec!["a", "b"]);
- test_concat!("ab", vec!["a", "b"].as_slice());
+ test_concat!("ab", vec!["a", "b"]);
test_concat!("ab", vec![s("a"), s("b")]);
}
fn test_connect_for_different_types() {
test_connect!("a-b", ["a", "b"], "-");
let hyphen = "-".to_string();
- test_connect!("a-b", [s("a"), s("b")], hyphen.as_slice());
- test_connect!("a-b", vec!["a", "b"], hyphen.as_slice());
- test_connect!("a-b", vec!["a", "b"].as_slice(), "-");
+ test_connect!("a-b", [s("a"), s("b")], &*hyphen);
+ test_connect!("a-b", vec!["a", "b"], &*hyphen);
+ test_connect!("a-b", &*vec!["a", "b"], "-");
test_connect!("a-b", vec![s("a"), s("b")], "-");
}
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
let chars: &[char] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(chars), "foo1bar12");
- assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
+ assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
}
#[test]
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
let chars: &[char] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(chars), "12foo1bar");
- assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
+ assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
}
#[test]
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
let chars: &[char] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(chars), "foo1bar");
- assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
+ assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
}
#[test]
let s1: String = String::from_str("All mimsy were the borogoves");
let v: Vec<u8> = s1.as_bytes().to_vec();
- let s2: String = String::from_str(from_utf8(v.as_slice()).unwrap());
+ let s2: String = String::from_str(from_utf8(&v).unwrap());
let mut i: uint = 0u;
let n1: uint = s1.len();
let n2: uint = v.len();
let split: Vec<&str> = data.splitn(3, ' ').collect();
assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
- let split: Vec<&str> = data.splitn(3, |&: c: char| c == ' ').collect();
+ let split: Vec<&str> = data.splitn(3, |c: char| c == ' ').collect();
assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
// Unicode
let split: Vec<&str> = data.splitn(3, 'ä').collect();
assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
- let split: Vec<&str> = data.splitn(3, |&: c: char| c == 'ä').collect();
+ let split: Vec<&str> = data.splitn(3, |c: char| c == 'ä').collect();
assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
}
let s = String::from_str("01234");
assert_eq!(5, sum_len(&["012", "", "34"]));
- assert_eq!(5, sum_len(&[String::from_str("01").as_slice(),
- String::from_str("2").as_slice(),
- String::from_str("34").as_slice(),
- String::from_str("").as_slice()]));
- assert_eq!(5, sum_len(&[s.as_slice()]));
+ assert_eq!(5, sum_len(&[&String::from_str("01"),
+ &String::from_str("2"),
+ &String::from_str("34"),
+ &String::from_str("")]));
+ assert_eq!(5, sum_len(&[&s]));
}
#[test]
let s = "Mary had a little lamb, Little lamb, little-lamb.";
let len = s.split(' ').count();
- b.iter(|| assert_eq!(s.split(|&: c: char| c == ' ').count(), len));
+ b.iter(|| assert_eq!(s.split(|c: char| c == ' ').count(), len));
}
#[bench]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
- match str::from_utf8(vec.as_slice()) {
+ match str::from_utf8(&vec) {
Ok(..) => Ok(String { vec: vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
- self.vec.as_slice()
+ &self.vec
}
/// Shortens a string to the specified length.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn as_slice<'a>(&'a self) -> &'a str {
- unsafe { mem::transmute(self.vec.as_slice()) }
+ unsafe { mem::transmute(&*self.vec) }
}
}
type Output = str;
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &str {
- unsafe { mem::transmute(self.vec.as_slice()) }
+ unsafe { mem::transmute(&*self.vec) }
}
}
impl<'a> Str for CowString<'a> {
#[inline]
fn as_slice<'b>(&'b self) -> &'b str {
- (**self).as_slice()
+ &**self
}
}
#[test]
fn test_as_string() {
let x = "foo";
- assert_eq!(x, as_string(x).as_slice());
+ assert_eq!(x, &**as_string(x));
}
#[test]
fn test_from_str() {
let owned: Option<::std::string::String> = "string".parse().ok();
- assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
+ assert_eq!(owned.as_ref().map(|s| &**s), Some("string"));
}
#[test]
for p in &pairs {
let (s, u) = (*p).clone();
let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
- let u_as_string = String::from_utf16(u.as_slice()).unwrap();
+ let u_as_string = String::from_utf16(&u).unwrap();
- assert!(::unicode::str::is_utf16(u.as_slice()));
+ assert!(::unicode::str::is_utf16(&u));
assert_eq!(s_as_utf16, u);
assert_eq!(u_as_string, s);
- assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
+ assert_eq!(String::from_utf16_lossy(&u), s);
- assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
+ assert_eq!(String::from_utf16(&s_as_utf16).unwrap(), s);
assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
}
}
fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
let s = repeat(0xf5u8).take(100).collect::<Vec<_>>();
b.iter(|| {
- let _ = String::from_utf8_lossy(s.as_slice());
+ let _ = String::from_utf8_lossy(&s);
});
}
pub fn into_boxed_slice(mut self) -> Box<[T]> {
self.shrink_to_fit();
unsafe {
- let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
+ let xs: Box<[T]> = mem::transmute(&mut *self);
mem::forget(self);
xs
}
let len = self.len();
let mut del = 0u;
{
- let v = self.as_mut_slice();
+ let v = &mut **self;
for i in 0u..len {
if !f(&v[i]) {
#[unstable(feature = "collections")]
impl<T:Clone> Clone for Vec<T> {
- fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(self.as_slice()) }
+ fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(&**self) }
fn clone_from(&mut self, other: &Vec<T>) {
// drop anything in self that will not be overwritten
impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> {
#[inline]
fn hash(&self, state: &mut S) {
- self.as_slice().hash(state);
+ Hash::hash(&**self, state)
}
}
#[inline]
fn index<'a>(&'a self, index: &uint) -> &'a T {
- &self.as_slice()[*index]
+ // NB built-in indexing via `&[T]`
+ &(**self)[*index]
}
}
#[inline]
fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
- &mut self.as_mut_slice()[*index]
+ // NB built-in indexing via `&mut [T]`
+ &mut (**self)[*index]
}
}
type Output = [T];
#[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] {
- self.as_slice().index(index)
+ Index::index(&**self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
- self.as_slice().index(index)
+ Index::index(&**self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
- self.as_slice().index(index)
+ Index::index(&**self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
- self.as_mut_slice().index_mut(index)
+ IndexMut::index_mut(&mut **self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
- self.as_mut_slice().index_mut(index)
+ IndexMut::index_mut(&mut **self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
- self.as_mut_slice().index_mut(index)
+ IndexMut::index_mut(&mut **self, index)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: PartialOrd> PartialOrd for Vec<T> {
#[inline]
fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
- self.as_slice().partial_cmp(other.as_slice())
+ PartialOrd::partial_cmp(&**self, &**other)
}
}
impl<T: Ord> Ord for Vec<T> {
#[inline]
fn cmp(&self, other: &Vec<T>) -> Ordering {
- self.as_slice().cmp(other.as_slice())
+ Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug> fmt::Debug for Vec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- fmt::Debug::fmt(self.as_slice(), f)
+ fmt::Debug::fmt(&**self, f)
}
}
#[test]
fn test_as_vec() {
let xs = [1u8, 2u8, 3u8];
- assert_eq!(as_vec(&xs).as_slice(), xs);
+ assert_eq!(&**as_vec(&xs), xs);
}
#[test]
fn test_into_boxed_slice() {
let xs = vec![1u, 2, 3];
let ys = xs.into_boxed_slice();
- assert_eq!(ys.as_slice(), [1u, 2, 3]);
+ assert_eq!(ys, [1u, 2, 3]);
}
#[test]
b.iter(|| {
let mut dst = dst.clone();
- dst.push_all(src.as_slice());
+ dst.push_all(&src);
assert_eq!(dst.len(), dst_len + src_len);
assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
});
//!
//! use std::finally::Finally;
//!
-//! (|&mut:| {
+//! (|| {
//! // ...
//! }).finally(|| {
//! // this code is always run
// cut off the one extra digit, and depending on its value
// round the remaining ones.
if limit_digits && dig == digit_count {
- let ascii2value = |&: chr: u8| {
+ let ascii2value = |chr: u8| {
(chr as char).to_digit(radix).unwrap()
};
- let value2ascii = |&: val: uint| {
+ let value2ascii = |val: uint| {
char::from_digit(val, radix).unwrap() as u8
};
}
// Writes the sign if it exists, and then the prefix if it was requested
- let write_prefix = |&: f: &mut Formatter| {
+ let write_prefix = |f: &mut Formatter| {
if let Some(c) = sign {
let mut b = [0; 4];
let n = c.encode_utf8(&mut b).unwrap_or(0);
let a: [u8; ::$ty::BYTES] = unsafe {
mem::transmute((*self as $uty).to_le() as $ty)
};
- state.write(a.as_slice())
+ state.write(&a)
}
}
}
#[unstable(feature = "core",
reason = "this function may be removed in the future due to its \
questionable utility")]
-pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a mut S,
- ptr: &mut T)
- -> &'a mut T {
+pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
+ ptr: &mut T)
+ -> &'a mut T
+{
transmute(ptr)
}
#[inline]
fn trim_matches<P: CharEq>(&self, mut pat: P) -> &str {
- let cur = match self.find(|&mut: c: char| !pat.matches(c)) {
+ let cur = match self.find(|c: char| !pat.matches(c)) {
None => "",
Some(i) => unsafe { self.slice_unchecked(i, self.len()) }
};
- match cur.rfind(|&mut: c: char| !pat.matches(c)) {
+ match cur.rfind(|c: char| !pat.matches(c)) {
None => "",
Some(i) => {
let right = cur.char_range_at(i).next;
#[inline]
fn trim_left_matches<P: CharEq>(&self, mut pat: P) -> &str {
- match self.find(|&mut: c: char| !pat.matches(c)) {
+ match self.find(|c: char| !pat.matches(c)) {
None => "",
Some(first) => unsafe { self.slice_unchecked(first, self.len()) }
}
#[inline]
fn trim_right_matches<P: CharEq>(&self, mut pat: P) -> &str {
- match self.rfind(|&mut: c: char| !pat.matches(c)) {
+ match self.rfind(|c: char| !pat.matches(c)) {
None => "",
Some(last) => {
let next = self.char_range_at(last).next;
fn test_encode_utf8() {
fn check(input: char, expect: &[u8]) {
let mut buf = [0u8; 4];
- let n = input.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
+ let n = input.encode_utf8(&mut buf).unwrap_or(0);
assert_eq!(&buf[..n], expect);
}
fn test_encode_utf16() {
fn check(input: char, expect: &[u16]) {
let mut buf = [0u16; 2];
- let n = input.encode_utf16(buf.as_mut_slice()).unwrap_or(0);
+ let n = input.encode_utf16(&mut buf).unwrap_or(0);
assert_eq!(&buf[..n], expect);
}
#[test]
fn test_retval() {
- let mut closure = |&mut:| 10;
- let i = closure.finally(|| { });
+ let mut closure = || 10;
+ // FIXME(#16640) `: i32` annotation shouldn't be necessary
+ let i: i32 = closure.finally(|| { });
assert_eq!(i, 10);
}
fn to_hex_str(r: &[u8; 8]) -> String {
let mut s = String::new();
for b in r {
- s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice());
+ s.push_str(format!("{}", fmt::radix(*b, 16)));
}
s
}
let r = result_bytes(h);
let mut s = String::new();
for b in &r {
- s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice());
+ s.push_str(format!("{}", fmt::radix(*b, 16)));
}
s
}
while t < 64 {
debug!("siphash test {}: {}", t, buf);
let vec = u8to64_le!(vecs[t], 0);
- let out = hash_with_keys(k0, k1, &Bytes(buf.as_slice()));
+ let out = hash_with_keys(k0, k1, &Bytes(buf));
debug!("got {}, expected {}", out, vec);
assert_eq!(vec, out);
state_full.reset();
- state_full.write(buf.as_slice());
+ state_full.write(buf);
let f = result_str(state_full.result());
let i = result_str(state_inc.result());
let v = to_hex_str(&vecs[t]);
split.reverse();
assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
- let mut split: Vec<&str> = data.rsplitn(3, |&: c: char| c == ' ').collect();
+ let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == ' ').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
split.reverse();
assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
- let mut split: Vec<&str> = data.rsplitn(3, |&: c: char| c == 'ä').collect();
+ let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == 'ä').collect();
split.reverse();
assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
}
rsplit.reverse();
assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
- let split: Vec<&str> = data.split(|&: c: char| c == ' ').collect();
+ let split: Vec<&str> = data.split(|c: char| c == ' ').collect();
assert_eq!( split, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
- let mut rsplit: Vec<&str> = data.split(|&: c: char| c == ' ').rev().collect();
+ let mut rsplit: Vec<&str> = data.split(|c: char| c == ' ').rev().collect();
rsplit.reverse();
assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
rsplit.reverse();
assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
- let split: Vec<&str> = data.split(|&: c: char| c == 'ä').collect();
+ let split: Vec<&str> = data.split(|c: char| c == 'ä').collect();
assert_eq!( split, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
- let mut rsplit: Vec<&str> = data.split(|&: c: char| c == 'ä').rev().collect();
+ let mut rsplit: Vec<&str> = data.split(|c: char| c == 'ä').rev().collect();
rsplit.reverse();
assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
}
for _ in 0..20 {
let mut input = vec![];
for _ in 0..2000 {
- input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
+ input.push_all(r.choose(&words).unwrap());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
- let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
- let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
+ let cmp = deflate_bytes(&input).expect("deflation failed");
+ let out = inflate_bytes(&cmp).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
- assert_eq!(input, out.as_slice());
+ assert_eq!(&*input, &*out);
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
- let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
- let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
- assert_eq!(inflated.as_slice(), bytes);
+ let deflated = deflate_bytes(&bytes).expect("deflation failed");
+ let inflated = inflate_bytes(&deflated).expect("inflation failed");
+ assert_eq!(&*inflated, &*bytes);
}
}
/// Returns true if any of several options were matched.
pub fn opts_present(&self, names: &[String]) -> bool {
for nm in names {
- match find_opt(self.opts.as_slice(), Name::from_str(&nm[])) {
+ match find_opt(&self.opts, Name::from_str(&**nm)) {
Some(id) if !self.vals[id].is_empty() => return true,
_ => (),
};
interpreted correctly
*/
- let opt_id = match find_opt(opts.as_slice(), opt.clone()) {
+ let opt_id = match find_opt(&opts, opt.clone()) {
Some(id) => id,
None => return Err(UnrecognizedOption(opt.to_string()))
};
let mut name_pos = 0;
for nm in &names {
name_pos += 1;
- let optid = match find_opt(opts.as_slice(), (*nm).clone()) {
+ let optid = match find_opt(&opts, (*nm).clone()) {
Some(id) => id,
None => return Err(UnrecognizedOption(nm.to_string()))
};
lim = fake_i;
}
- let mut machine = |&mut: cont: &mut bool, (i, c): (uint, char)| -> bool {
+ let mut machine = |cont: &mut bool, (i, c): (uint, char)| -> bool {
let whitespace = if c.is_whitespace() { Ws } else { Cr };
let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim };
fn test_reqopt() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
_ => { panic!("test_reqopt failed (long arg)"); }
}
let short_args = vec!("-t".to_string(), "20".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Ok(ref m) => {
assert!((m.opt_present("test")));
assert_eq!(m.opt_str("test").unwrap(), "20");
fn test_reqopt_missing() {
let args = vec!("blah".to_string());
let opts = vec!(reqopt("t", "test", "testing", "TEST"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Err(OptionMissing(_)) => {},
_ => panic!()
fn test_reqopt_no_arg() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
let short_args = vec!("-t".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
fn test_reqopt_multi() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Err(OptionDuplicated(_)) => {},
_ => panic!()
fn test_optopt() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
_ => panic!()
}
let short_args = vec!("-t".to_string(), "20".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Ok(ref m) => {
assert!((m.opt_present("test")));
assert_eq!(m.opt_str("test").unwrap(), "20");
fn test_optopt_missing() {
let args = vec!("blah".to_string());
let opts = vec!(optopt("t", "test", "testing", "TEST"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert!(!m.opt_present("test"));
fn test_optopt_no_arg() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
let short_args = vec!("-t".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
fn test_optopt_multi() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Err(OptionDuplicated(_)) => {},
_ => panic!()
fn test_optflag() {
let long_args = vec!("--test".to_string());
let opts = vec!(optflag("t", "test", "testing"));
- let rs = getopts(long_args.as_slice(), opts.as_slice());
+ let rs = getopts(&long_args, &opts);
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
_ => panic!()
}
let short_args = vec!("-t".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Ok(ref m) => {
assert!(m.opt_present("test"));
assert!(m.opt_present("t"));
fn test_optflag_missing() {
let args = vec!("blah".to_string());
let opts = vec!(optflag("t", "test", "testing"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert!(!m.opt_present("test"));
fn test_optflag_long_arg() {
let args = vec!("--test=20".to_string());
let opts = vec!(optflag("t", "test", "testing"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Err(UnexpectedArgument(_)) => {},
_ => panic!()
fn test_optflag_multi() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Err(OptionDuplicated(_)) => {},
_ => panic!()
fn test_optflag_short_arg() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
// The next variable after the flag is just a free argument
fn test_optflagmulti_short1() {
let args = vec!("-v".to_string());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 1);
fn test_optflagmulti_short2a() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
fn test_optflagmulti_short2b() {
let args = vec!("-vv".to_string());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
fn test_optflagmulti_long1() {
let args = vec!("--verbose".to_string());
let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 1);
fn test_optflagmulti_long2() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 2);
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());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 4);
fn test_optmulti() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Ok(ref m) => {
assert!((m.opt_present("test")));
_ => panic!()
}
let short_args = vec!("-t".to_string(), "20".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Ok(ref m) => {
assert!((m.opt_present("test")));
assert_eq!(m.opt_str("test").unwrap(), "20");
fn test_optmulti_missing() {
let args = vec!("blah".to_string());
let opts = vec!(optmulti("t", "test", "testing", "TEST"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert!(!m.opt_present("test"));
fn test_optmulti_no_arg() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
let short_args = vec!("-t".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Err(ArgumentMissing(_)) => {},
_ => panic!()
}
fn test_optmulti_multi() {
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());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert!(m.opt_present("test"));
fn test_unrecognized_option() {
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());
+ let rs = getopts(&long_args, &opts);
match rs {
Err(UnrecognizedOption(_)) => {},
_ => panic!()
}
let short_args = vec!("-u".to_string());
- match getopts(short_args.as_slice(), opts.as_slice()) {
+ match getopts(&short_args, &opts) {
Err(UnrecognizedOption(_)) => {},
_ => panic!()
}
optmulti("m", "", "mmmmmm", "YUM"),
optmulti("n", "", "nothing", "NOTHING"),
optopt("", "notpresent", "nothing to see here", "NOPE"));
- let rs = getopts(args.as_slice(), opts.as_slice());
+ let rs = getopts(&args, &opts);
match rs {
Ok(ref m) => {
assert!(m.free[0] == "prog");
optopt("f", "", "flag", "FLAG"));
let args_single = vec!("-e".to_string(), "foo".to_string());
- let matches_single = &match getopts(args_single.as_slice(),
- opts.as_slice()) {
+ let matches_single = &match getopts(&args_single, &opts) {
result::Result::Ok(m) => m,
result::Result::Err(_) => panic!()
};
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()) {
+ let matches_both = &match getopts(&args_both, &opts) {
result::Result::Ok(m) => m,
result::Result::Err(_) => panic!()
};
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()) {
+ let matches = &match getopts(&args, &opts) {
result::Result::Ok(m) => m,
result::Result::Err(_) => panic!()
};
let args = vec!("-vvLverbose".to_string(), "-v".to_string() );
let opts = vec!(optmulti("L", "", "library directory", "LIB"),
optflagmulti("v", "verbose", "Verbose"));
- let matches = &match getopts(args.as_slice(), opts.as_slice()) {
+ let matches = &match getopts(&args, &opts) {
result::Result::Ok(m) => m,
result::Result::Err(e) => panic!( "{}", e )
};
let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string());
- let matches = getopts(args.as_slice(), opts.as_slice()).unwrap();
+ let matches = getopts(&args, &opts).unwrap();
assert_eq!(3, matches.opt_count("a"));
assert_eq!(3, matches.opt_count("apple"));
}
-l VAL Desc
";
- let generated_usage = usage("Usage: fruits", optgroups.as_slice());
+ let generated_usage = usage("Usage: fruits", &optgroups);
debug!("expected: <<{}>>", expected);
debug!("generated: <<{}>>", generated_usage);
wrapped..+..
";
- let usage = usage("Usage: fruits", optgroups.as_slice());
+ let usage = usage("Usage: fruits", &optgroups);
debug!("expected: <<{}>>", expected);
debug!("generated: <<{}>>", usage);
some parts of Europe.
";
- let usage = usage("Usage: fruits", optgroups.as_slice());
+ let usage = usage("Usage: fruits", &optgroups);
debug!("expected: <<{}>>", expected);
debug!("generated: <<{}>>", usage);
optmulti("l", "", "Desc", "VAL"));
let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string();
- let generated_usage = short_usage("fruits", optgroups.as_slice());
+ let generated_usage = short_usage("fruits", &optgroups);
debug!("expected: <<{}>>", expected);
debug!("generated: <<{}>>", generated_usage);
} else {
let escaped = g.node_label(n).escape();
try!(writeln(w, &[id.as_slice(),
- "[label=\"", escaped.as_slice(), "\"];"]));
+ "[label=\"", &escaped, "\"];"]));
}
}
} else {
try!(writeln(w, &[source_id.as_slice(),
" -> ", target_id.as_slice(),
- "[label=\"", escaped_label.as_slice(), "\"];"]));
+ "[label=\"", &escaped_label, "\"];"]));
}
}
fn test_input(g: LabelledGraph) -> IoResult<String> {
let mut writer = Vec::new();
render(&g, &mut writer).unwrap();
- (&mut writer.as_slice()).read_to_string()
+ (&mut &*writer).read_to_string()
}
// All of the tests use raw-strings as the format for the expected outputs,
edge(1, 3, ";"), edge(2, 3, ";" )));
render(&g, &mut writer).unwrap();
- let r = (&mut writer.as_slice()).read_to_string();
+ let r = (&mut &*writer).read_to_string();
assert_eq!(r.unwrap(),
r#"digraph syntax_tree {
DIRECTIVES = mem::transmute(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
- rt::at_exit(move |:| {
+ rt::at_exit(move || {
assert!(!DIRECTIVES.is_null());
let _directives: Box<Vec<directive::LogDirective>> =
mem::transmute(DIRECTIVES);
#[test]
fn test_rng_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
- let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
- let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
+ let mut ra: ChaChaRng = SeedableRng::from_seed(&*s);
+ let mut rb: ChaChaRng = SeedableRng::from_seed(&*s);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
- let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
+ let mut r: ChaChaRng = SeedableRng::from_seed(&*s);
let string1: String = r.gen_ascii_chars().take(100).collect();
- r.reseed(s.as_slice());
+ r.reseed(&s);
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
macro_rules! t {
($items:expr, $expected:expr) => {{
let mut items = $items;
- let wc = WeightedChoice::new(items.as_mut_slice());
+ let wc = WeightedChoice::new(&mut items);
let expected = $expected;
let mut rng = CountingRng { i: 0 };
#[test]
fn test_rng_32_rand_seeded() {
let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
- let mut ra: IsaacRng = SeedableRng::from_seed(s.as_slice());
- let mut rb: IsaacRng = SeedableRng::from_seed(s.as_slice());
+ let mut ra: IsaacRng = SeedableRng::from_seed(&*s);
+ let mut rb: IsaacRng = SeedableRng::from_seed(&*s);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_64_rand_seeded() {
let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
- let mut ra: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
- let mut rb: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
+ let mut ra: Isaac64Rng = SeedableRng::from_seed(&*s);
+ let mut rb: Isaac64Rng = SeedableRng::from_seed(&*s);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_rng_32_reseed() {
let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
- let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
+ let mut r: IsaacRng = SeedableRng::from_seed(&*s);
let string1: String = r.gen_ascii_chars().take(100).collect();
- r.reseed(s.as_slice());
+ r.reseed(&s);
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
#[test]
fn test_rng_64_reseed() {
let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
- let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
+ let mut r: Isaac64Rng = SeedableRng::from_seed(&*s);
let string1: String = r.gen_ascii_chars().take(100).collect();
- r.reseed(s.as_slice());
+ r.reseed(&s);
let string2: String = r.gen_ascii_chars().take(100).collect();
assert_eq!(string1, string2);
pub use core::marker;
// for-loops
pub use core::iter;
+ pub use core::ops; // slicing syntax
}
#[cfg(test)]
#[test]
fn test_rng_fill_bytes() {
let mut v = repeat(0u8).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
- ::test::rng().fill_bytes(v.as_mut_slice());
+ ::test::rng().fill_bytes(&mut v);
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
- pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+ pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in 0..times {
- wr.write(src.as_slice()).unwrap();
+ wr.write(&src).unwrap();
}
let v = wr.unwrap();
b.iter(|| {
let mut i = 0;
while i < data.len() {
- sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+ sum += reader::vuint_at(&data, i).unwrap().val;
i += 4;
}
});
b.iter(|| {
let mut i = 1;
while i < data.len() {
- sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+ sum += reader::vuint_at(&data, i).unwrap().val;
i += 4;
}
});
b.iter(|| {
let mut i = 0;
while i < data.len() {
- sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+ sum += reader::vuint_at(&data, i).unwrap().val;
i += 4;
}
});
b.iter(|| {
let mut i = 1;
while i < data.len() {
- sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+ sum += reader::vuint_at(&data, i).unwrap().val;
i += 4;
}
});
fn to_snake_case(mut str: &str) -> String {
let mut words = vec![];
// Preserve leading underscores
- str = str.trim_left_matches(|&mut: c: char| {
+ str = str.trim_left_matches(|c: char| {
if c == '_' {
words.push(String::new());
true
.map(|c| c.to_uppercase()).collect();
if uc != s.get() {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
- format!("{} `{}` should have an upper case name such as `{}`",
- sort, s, uc).as_slice());
+ &format!("{} `{}` should have an upper case name such as `{}`",
+ sort, s, uc));
} else {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
- format!("{} `{}` should have an upper case name",
- sort, s).as_slice());
+ &format!("{} `{}` should have an upper case name",
+ sort, s));
}
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
match it.node {
ast::ItemFn(..) => {
- if attr::contains_name(it.attrs.as_slice(), "no_mangle") &&
+ if attr::contains_name(&it.attrs, "no_mangle") &&
!cx.exported_items.contains(&it.id) {
let msg = format!("function {} is marked #[no_mangle], but not exported",
it.ident);
- cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg.as_slice());
+ cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
}
},
_ => {},
.collect(),
None => {
self.span_lint(builtin::UNKNOWN_LINTS, span,
- format!("unknown `{}` attribute: `{}`",
- level.as_str(), lint_name).as_slice());
+ &format!("unknown `{}` attribute: `{}`",
+ level.as_str(), lint_name));
continue;
}
}
for (id, v) in &*tcx.sess.lints.borrow() {
for &(lint, span, ref msg) in v {
tcx.sess.span_bug(span,
- format!("unprocessed lint {} at {}: {}",
- lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice())
+ &format!("unprocessed lint {} at {}: {}",
+ lint.as_str(), tcx.map.node_to_string(*id), *msg))
}
}
}
pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
- let err = |&: s: &str| {
+ let err = |s: &str| {
match (sp, sess) {
(_, None) => panic!("{}", s),
(Some(sp), Some(sess)) => sess.span_err(sp, s),
F: FnMut(decoder::DefLike, ast::Name, ast::Visibility),
{
let crate_data = cstore.get_crate_data(def_id.krate);
- let get_crate_data = |&mut: cnum| {
+ let get_crate_data = |cnum| {
cstore.get_crate_data(cnum)
};
decoder::each_child_of_item(cstore.intr.clone(),
F: FnMut(decoder::DefLike, ast::Name, ast::Visibility),
{
let crate_data = cstore.get_crate_data(cnum);
- let get_crate_data = |&mut: cnum| {
+ let get_crate_data = |cnum| {
cstore.get_crate_data(cnum)
};
decoder::each_top_level_item_of_crate(cstore.intr.clone(),
// FIXME #1920: This path is not always correct if the crate is not linked
// into the root namespace.
let mut r = vec![ast_map::PathMod(token::intern(&cdata.name[]))];
- r.push_all(path.as_slice());
+ r.push_all(&path);
r
}
encode_bounds_and_type(rbml_w, ecx, &lookup_item_type(tcx, def_id));
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
- encode_attributes(rbml_w, item.attrs.as_slice());
+ encode_attributes(rbml_w, &item.attrs);
encode_inlined_item(ecx, rbml_w, IIItemRef(item));
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
let trait_def = ty::lookup_trait_def(tcx, def_id);
encode_unsafety(rbml_w, trait_def.unsafety);
encode_paren_sugar(rbml_w, trait_def.paren_sugar);
- encode_associated_type_names(rbml_w, trait_def.associated_type_names.as_slice());
+ encode_associated_type_names(rbml_w, &trait_def.associated_type_names);
encode_generics(rbml_w, ecx, &trait_def.generics, tag_item_generics);
encode_trait_ref(rbml_w, ecx, &*trait_def.trait_ref, tag_item_trait_ref);
encode_name(rbml_w, item.ident.name);
encode_parent_sort(rbml_w, 't');
let trait_item = &ms[i];
- let encode_trait_item = |&: rbml_w: &mut Encoder| {
+ let encode_trait_item = |rbml_w: &mut Encoder| {
// If this is a static method, we've already
// encoded this.
if is_nonstatic_method {
file.ends_with(".rlib") {
(&file[(rlib_prefix.len()) .. (file.len() - ".rlib".len())],
true)
- } else if file.starts_with(dylib_prefix.as_slice()) &&
- file.ends_with(dypair.1.as_slice()) {
+ } else if file.starts_with(&dylib_prefix) &&
+ file.ends_with(&dypair.1) {
(&file[(dylib_prefix.len()) .. (file.len() - dypair.1.len())],
false)
} else {
'P' => {
assert_eq!(next(st), '[');
let trait_ref = parse_trait_ref_(st, conv);
- let name = token::intern(parse_str(st, ']').as_slice());
+ let name = token::intern(&parse_str(st, ']'));
return ty::mk_projection(tcx, trait_ref, name);
}
'e' => {
ty::ProjectionPredicate {
projection_ty: ty::ProjectionTy {
trait_ref: parse_trait_ref_(st, conv),
- item_name: token::str_to_ident(parse_str(st, '|').as_slice()).name,
+ item_name: token::str_to_ident(&parse_str(st, '|')).name,
},
ty: parse_ty_(st, conv),
}
rbml_w.tag(c::tag_table_freevars, |rbml_w| {
rbml_w.id(id);
rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_from_vec(fv.as_slice(), |rbml_w, fv_entry| {
+ rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
Ok(encode_freevar_entry(rbml_w, fv_entry))
});
})
ast::ExprBlock(ref block) => {
// Check all statements in the block
for stmt in &block.stmts {
- let block_span_err = |&: span|
+ let block_span_err = |span|
span_err!(v.tcx.sess, span, E0016,
"blocks in constants are limited to items and \
tail expressions");
})
}
- let check_move = |&: p: &Pat, sub: Option<&Pat>| {
+ let check_move = |p: &Pat, sub: Option<&Pat>| {
// check legality of moving out of the enum
// x @ Foo(..) is legal, but x @ Foo(y) isn't.
Entry => on_entry,
Exit => {
let mut t = on_entry.to_vec();
- self.apply_gen_kill(cfgidx, t.as_mut_slice());
+ self.apply_gen_kill(cfgidx, &mut t);
temp_bits = t;
&temp_bits[]
}
Some(cfg_idx) => {
let (start, end) = self.compute_id_range(cfg_idx);
let kills = &self.kills[start.. end];
- if bitwise(orig_kills.as_mut_slice(), kills, &Union) {
+ if bitwise(&mut orig_kills, kills, &Union) {
changed = true;
}
}
let mut temp: Vec<_> = repeat(0).take(words_per_id).collect();
while propcx.changed {
propcx.changed = false;
- propcx.reset(temp.as_mut_slice());
- propcx.walk_cfg(cfg, temp.as_mut_slice());
+ propcx.reset(&mut temp);
+ propcx.walk_cfg(cfg, &mut temp);
}
}
let def_map = &self.tcx.def_map;
match pat.node {
ast::PatStruct(_, ref fields, _) => {
- self.handle_field_pattern_match(pat, fields.as_slice());
+ self.handle_field_pattern_match(pat, fields);
}
_ if pat_util::pat_is_const(def_map, pat) => {
// it might be the only use of a const
}
fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
- if attr::contains_name(attrs.as_slice(), "lang") {
+ if attr::contains_name(attrs, "lang") {
return true;
}
impl<'v> Visitor<'v> for LifeSeeder {
fn visit_item(&mut self, item: &ast::Item) {
- let allow_dead_code = has_allow_dead_code_or_lang_attr(item.attrs.as_slice());
+ let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
if allow_dead_code {
self.worklist.push(item.id);
}
// Check for method here because methods are not ast::Item
match fk {
visit::FkMethod(_, _, method) => {
- if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
+ if has_allow_dead_code_or_lang_attr(&method.attrs) {
self.worklist.push(id);
}
}
is_named
&& !self.symbol_is_live(node.id, None)
&& !is_marker_field
- && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
+ && !has_allow_dead_code_or_lang_attr(&node.attrs)
}
fn should_warn_about_variant(&mut self, variant: &ast::Variant_) -> bool {
!self.symbol_is_live(variant.id, None)
- && !has_allow_dead_code_or_lang_attr(variant.attrs.as_slice())
+ && !has_allow_dead_code_or_lang_attr(&variant.attrs)
}
// id := node id of an item's definition.
}
// If the user wants no main function at all, then stop here.
- if attr::contains_name(ast_map.krate().attrs.as_slice(), "no_main") {
+ if attr::contains_name(&ast_map.krate().attrs, "no_main") {
session.entry_type.set(Some(config::EntryNone));
return
}
});
}
- if attr::contains_name(item.attrs.as_slice(), "main") {
+ if attr::contains_name(&item.attrs, "main") {
if ctxt.attr_main_fn.is_none() {
ctxt.attr_main_fn = Some((item.id, item.span));
} else {
}
}
- if attr::contains_name(item.attrs.as_slice(), "start") {
+ if attr::contains_name(&item.attrs, "start") {
if ctxt.start_fn.is_none() {
ctxt.start_fn = Some((item.id, item.span));
} else {
None => {
self.tcx().sess.span_bug(
callee.span,
- format!("unexpected callee type {}",
- callee_ty.repr(self.tcx())).as_slice())
+ &format!("unexpected callee type {}", callee_ty.repr(self.tcx())))
}
};
match overloaded_call_type {
let msg = format!("Pattern has unexpected type: {:?} and type {}",
def,
cmt_pat.ty.repr(tcx));
- tcx.sess.span_bug(pat.span, msg.as_slice())
+ tcx.sess.span_bug(pat.span, &msg)
}
}
#[inline]
pub fn all_nodes<'a>(&'a self) -> &'a [Node<N>] {
- let nodes: &'a [Node<N>] = self.nodes.as_slice();
- nodes
+ &self.nodes
}
#[inline]
pub fn all_edges<'a>(&'a self) -> &'a [Edge<E>] {
- let edges: &'a [Edge<E>] = self.edges.as_slice();
- edges
+ &self.edges
}
///////////////////////////////////////////////////////////////////////////
}
let inputs = try!(argvecs(self,
- a.inputs.as_slice(),
- b.inputs.as_slice()));
+ &a.inputs,
+ &b.inputs));
let output = try!(match (a.output, b.output) {
(ty::FnConverging(a_ty), ty::FnConverging(b_ty)) =>
Some(node) => match node {
ast_map::NodeItem(item) => match item.node {
ast::ItemImpl(_, _, ref gen, _, _, _) => {
- taken.push_all(gen.lifetimes.as_slice());
+ taken.push_all(&gen.lifetimes);
}
_ => ()
},
ty::ty_infer(ty::FreshIntTy(c)) => {
if c >= self.freshen_count {
self.tcx().sess.bug(
- format!("Encountered a freshend type with id {} \
- but our counter is only at {}",
- c,
- self.freshen_count).as_slice());
+ &format!("Encountered a freshend type with id {} \
+ but our counter is only at {}",
+ c,
+ self.freshen_count));
}
t
}
self.tcx(),
&result0,
|r, debruijn| generalize_region(self.infcx(), span, snapshot, debruijn,
- new_vars.as_slice(), &a_map, r));
+ &new_vars, &a_map, r));
debug!("lub({},{}) = {}",
a.repr(self.tcx()),
self.tcx(),
&result0,
|r, debruijn| generalize_region(self.infcx(), span, snapshot, debruijn,
- new_vars.as_slice(),
- &a_map, a_vars.as_slice(), b_vars.as_slice(),
+ &new_vars,
+ &a_map, &a_vars, &b_vars,
r));
debug!("glb({},{}) = {}",
let output_path = {
let output_template = match requested_output {
- Some(ref s) if s.as_slice() == "help" => {
+ Some(ref s) if &**s == "help" => {
static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
if !PRINTED_YET.load(Ordering::SeqCst) {
print_help_message();
let mut new_str = String::new();
for c in output_template.chars() {
if c == '%' {
- new_str.push_str(subject_node.to_string().as_slice());
+ new_str.push_str(&subject_node.to_string());
} else {
new_str.push(c);
}
};
let constraints = &*region_vars.constraints.borrow();
- match dump_region_constraints_to(tcx, constraints, output_path.as_slice()) {
+ match dump_region_constraints_to(tcx, constraints, &output_path) {
Ok(()) => {}
Err(e) => {
let msg = format!("io error dumping region constraints: {}", e);
- region_vars.tcx.sess.err(msg.as_slice())
+ region_vars.tcx.sess.err(&msg)
}
}
}
let mut i = 0;
let mut node_ids = FnvHashMap();
{
- let mut add_node = |&mut : node| {
+ let mut add_node = |node| {
if let Vacant(e) = node_ids.entry(node) {
e.insert(i);
i += 1;
impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
fn graph_id(&self) -> dot::Id {
- dot::Id::new(self.graph_name.as_slice()).ok().unwrap()
+ dot::Id::new(&*self.graph_name).ok().unwrap()
}
fn node_id(&self, n: &Node) -> dot::Id {
dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).ok().unwrap()
debug!("----() End constraint listing {:?}---", self.dump_constraints());
graphviz::maybe_print_constraints_for(self, subject);
- self.expansion(var_data.as_mut_slice());
- self.contraction(var_data.as_mut_slice());
+ self.expansion(&mut var_data);
+ self.contraction(&mut var_data);
let values =
self.extract_values_and_collect_conflicts(&var_data[],
errors);
match var_data[idx].classification {
Expanding => {
self.collect_error_for_expanding_node(
- graph, var_data, dup_vec.as_mut_slice(),
+ graph, var_data, &mut dup_vec,
node_vid, errors);
}
Contracting => {
self.collect_error_for_contracting_node(
- graph, var_data, dup_vec.as_mut_slice(),
+ graph, var_data, &mut dup_vec,
node_vid, errors);
}
}
impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
fn visit_item(&mut self, item: &ast::Item) {
- match extract(item.attrs.as_slice()) {
+ match extract(&item.attrs) {
Some(value) => {
let item_index = self.item_refs.get(value.get()).map(|x| *x);
{
let region_maps = &mut visitor.region_maps;
- let terminating = |&: id| {
+ let terminating = |id| {
let scope = CodeExtent::from_node_id(id);
region_maps.mark_as_terminating_scope(scope)
};
if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
self.sess.span_warn(
lifetime.span,
- format!("lifetime name `{}` shadows another \
- lifetime name that is already in scope",
- token::get_name(lifetime.name)).as_slice());
+ &format!("lifetime name `{}` shadows another \
+ lifetime name that is already in scope",
+ token::get_name(lifetime.name)));
self.sess.span_note(
lifetime_def.span,
- format!("shadowed lifetime `{}` declared here",
- token::get_name(lifetime.name)).as_slice());
+ &format!("shadowed lifetime `{}` declared here",
+ token::get_name(lifetime.name)));
self.sess.span_note(
lifetime.span,
"shadowed lifetimes are deprecated \
attrs: &Vec<Attribute>, item_sp: Span, f: F, required: bool) where
F: FnOnce(&mut Annotator),
{
- match attr::find_stability(self.sess.diagnostic(), attrs.as_slice(), item_sp) {
+ match attr::find_stability(self.sess.diagnostic(), attrs, item_sp) {
Some(stab) => {
self.index.local.insert(id, stab.clone());
}
pub fn as_slice(&self) -> &[T] {
- self.content.as_slice()
+ &self.content
}
pub fn into_vec(self) -> Vec<T> {
and then a call to that function:
- let v: Vec<int> = clone_slice([1, 2, 3].as_slice())
+ let v: Vec<int> = clone_slice([1, 2, 3])
it is the job of trait resolution to figure out (in which case)
whether there exists an impl of `int : Clone`
Piece::String(s) => Some(s),
Piece::NextArgument(a) => match a.position {
Position::ArgumentNamed(s) => match generic_map.get(s) {
- Some(val) => Some(val.as_slice()),
+ Some(val) => Some(val),
None => {
span_err!(infcx.tcx.sess, err_sp, E0272,
"the #[rustc_on_unimplemented] \
obligation.cause.span);
if let Some(s) = custom_note {
infcx.tcx.sess.span_note(obligation.cause.span,
- s.as_slice());
+ &s);
}
}
}
// Ambiguity. Coherence should have reported an error.
infcx.tcx.sess.span_bug(
obligation.cause.span,
- format!(
+ &format!(
"coherence failed to report ambiguity: \
cannot locate the impl of the trait `{}` for \
the type `{}`",
trait_ref.user_string(infcx.tcx),
- self_ty.user_string(infcx.tcx)).as_slice());
+ self_ty.user_string(infcx.tcx)));
}
}
let item_name = ty::item_path_str(tcx, item_def_id);
tcx.sess.span_note(
cause_span,
- format!("required by `{}`", item_name).as_slice());
+ &format!("required by `{}`", item_name));
}
ObligationCauseCode::ObjectCastObligation(object_ty) => {
tcx.sess.span_note(
cause_span,
- format!(
+ &format!(
"required for the cast to the object type `{}`",
- infcx.ty_to_string(object_ty)).as_slice());
+ infcx.ty_to_string(object_ty)));
}
ObligationCauseCode::RepeatVec => {
tcx.sess.span_note(
{
match self.region_obligations.get(&body_id) {
None => Default::default(),
- Some(vec) => vec.as_slice(),
+ Some(vec) => vec,
}
}
_ => {
selcx.tcx().sess.span_bug(
obligation.cause.span,
- format!("assemble_candidates_from_object_type called with non-object: {}",
- object_ty.repr(selcx.tcx())).as_slice());
+ &format!("assemble_candidates_from_object_type called with non-object: {}",
+ object_ty.repr(selcx.tcx())));
}
};
let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty);
// These traits have no associated types.
selcx.tcx().sess.span_bug(
obligation.cause.span,
- format!("Cannot project an associated type from `{}`",
- vtable.repr(selcx.tcx())).as_slice());
+ &format!("Cannot project an associated type from `{}`",
+ vtable.repr(selcx.tcx())));
}
}
Err(e) => {
selcx.tcx().sess.span_bug(
obligation.cause.span,
- format!("Failed to unify `{}` and `{}` in projection: {}",
- obligation.repr(selcx.tcx()),
- projection.repr(selcx.tcx()),
- ty::type_err_to_str(selcx.tcx(), &e)).as_slice());
+ &format!("Failed to unify `{}` and `{}` in projection: {}",
+ obligation.repr(selcx.tcx()),
+ projection.repr(selcx.tcx()),
+ ty::type_err_to_str(selcx.tcx(), &e)));
}
}
_ => {
self.tcx().sess.span_bug(
obligation.cause.span,
- format!("match_projection_obligation_against_bounds_from_trait() called \
- but self-ty not a projection: {}",
- skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())).as_slice());
+ &format!("match_projection_obligation_against_bounds_from_trait() called \
+ but self-ty not a projection: {}",
+ skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())));
}
};
debug!("match_projection_obligation_against_bounds_from_trait: \
Ok(obligations) => obligations,
Err(()) => {
self.tcx().sess.bug(
- format!("Where clause `{}` was applicable to `{}` but now is not",
- param.repr(self.tcx()),
- obligation.repr(self.tcx())).as_slice());
+ &format!("Where clause `{}` was applicable to `{}` but now is not",
+ param.repr(self.tcx()),
+ obligation.repr(self.tcx())));
}
}
}
Some(r) => r,
None => {
self.tcx().sess.span_bug(obligation.cause.span,
- format!("unable to upcast from {} to {}",
- poly_trait_ref.repr(self.tcx()),
- obligation_def_id.repr(self.tcx())).as_slice());
+ &format!("unable to upcast from {} to {}",
+ poly_trait_ref.repr(self.tcx()),
+ obligation_def_id.repr(self.tcx())));
}
};
}))
}
Err(e) => {
- tcx.sess.err(e.as_slice());
+ tcx.sess.err(&e);
Err(ErrorReported)
}
}
bounds: ExistentialBounds<'tcx>)
-> Ty<'tcx>
{
- assert!(bound_list_is_sorted(bounds.projection_bounds.as_slice()));
+ assert!(bound_list_is_sorted(&bounds.projection_bounds));
let inner = box TyTrait {
principal: principal,
// FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
let param_env = ty::empty_parameter_environment(cx);
let upvars = closure_upvars(¶m_env, did, substs).unwrap();
- TypeContents::union(upvars.as_slice(),
- |f| tc_ty(cx, f.ty, cache))
+ TypeContents::union(&upvars,
+ |f| tc_ty(cx, &f.ty, cache))
| borrowed_contents(*r, MutMutable)
}
ty_closure(..) => {
// this check is run on type definitions, so we don't expect to see
// inference by-products or closure types
- cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
- ty).as_slice())
+ cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
}
ty_tup(ref ts) => {
ty_closure(..) => {
// this check is run on type definitions, so we don't expect
// to see closure types
- cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
- ty).as_slice())
+ cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
}
_ => Representable,
}
macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
macro_rules! hash { ($e:expr) => { $e.hash(state) } }
- let region = |&: state: &mut SipHasher, r: Region| {
+ let region = |state: &mut SipHasher, r: Region| {
match r {
ReStatic => {}
ReLateBound(db, BrAnon(i)) => {
}
}
};
- let did = |&: state: &mut SipHasher, did: DefId| {
+ let did = |state: &mut SipHasher, did: DefId| {
let h = if ast_util::is_local(did) {
svh.clone()
} else {
h.as_str().hash(state);
did.node.hash(state);
};
- let mt = |&: state: &mut SipHasher, mt: mt| {
+ let mt = |state: &mut SipHasher, mt: mt| {
mt.mutbl.hash(state);
};
- let fn_sig = |&: state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
+ let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
let sig = anonymize_late_bound_regions(tcx, sig).0;
for a in &sig.inputs { helper(tcx, *a, svh, state); }
if let ty::FnConverging(output) = sig.output {
_ => {
// All named regions are instantiated with free regions.
tcx.sess.bug(
- format!("record_region_bounds: non free region: {} / {}",
- r_a.repr(tcx),
- r_b.repr(tcx)).as_slice());
+ &format!("record_region_bounds: non free region: {} / {}",
+ r_a.repr(tcx),
+ r_b.repr(tcx)));
}
}
}
}
ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
self.push_reversed(principal.substs().types.as_slice());
- self.push_reversed(bounds.projection_bounds.iter().map(|pred| {
+ self.push_reversed(&bounds.projection_bounds.iter().map(|pred| {
pred.0.ty
- }).collect::<Vec<_>>().as_slice());
+ }).collect::<Vec<_>>());
}
ty::ty_enum(_, ref substs) |
ty::ty_struct(_, ref substs) |
self.push_reversed(substs.types.as_slice());
}
ty::ty_tup(ref ts) => {
- self.push_reversed(ts.as_slice());
+ self.push_reversed(ts);
}
ty::ty_bare_fn(_, ref ft) => {
self.push_sig_subtypes(&ft.sig);
ty::FnConverging(output) => { self.stack.push(output); }
ty::FnDiverging => { }
}
- self.push_reversed(sig.0.inputs.as_slice());
+ self.push_reversed(&sig.0.inputs);
}
fn push_reversed(&mut self, tys: &[Ty<'tcx>]) {
$(
if missing.contains(&lang_items::$item) && items.$name().is_none() {
- sess.err(format!("language item required, but not found: `{}`",
- stringify!($name)).as_slice());
+ sess.err(&format!("language item required, but not found: `{}`",
+ stringify!($name)));
}
)*
impl<'a, 'v> Visitor<'v> for Context<'a> {
fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
- match lang_items::extract(i.attrs.as_slice()) {
+ match lang_items::extract(&i.attrs) {
None => {}
Some(lang_item) => self.register(lang_item.get(), i.span),
}
impl<'v> Visitor<'v> for RegistrarFinder {
fn visit_item(&mut self, item: &ast::Item) {
if let ast::ItemFn(..) = item.node {
- if attr::contains_name(item.attrs.as_slice(),
+ if attr::contains_name(&item.attrs,
"plugin_registrar") {
self.registrars.push((item.id, item.span));
}
visit::walk_crate(&mut loader, krate);
if let Some(plugins) = addl_plugins {
- for plugin in &plugins {
- loader.load_plugin(CrateOrString::Str(plugin.as_slice()),
+ for plugin in plugins {
+ loader.load_plugin(CrateOrString::Str(&plugin),
None, None, None)
}
}
let target = match Target::search(&opts.target_triple[]) {
Ok(t) => t,
Err(e) => {
- sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
+ sp.handler().fatal(&format!("Error loading target specification: {}", e));
}
};
let unparsed_output_types = matches.opt_strs("emit");
for unparsed_output_type in &unparsed_output_types {
for part in unparsed_output_type.split(',') {
- let output_type = match part.as_slice() {
+ let output_type = match part {
"asm" => OutputTypeAssembly,
"llvm-ir" => OutputTypeLlvmAssembly,
"llvm-bc" => OutputTypeBitcode,
Some(2) => Default,
Some(3) => Aggressive,
Some(arg) => {
- early_error(format!("optimization level needs to be \
- between 0-3 (instead was `{}`)",
- arg).as_slice());
+ early_error(&format!("optimization level needs to be \
+ between 0-3 (instead was `{}`)",
+ arg));
}
}
}
Some(1) => LimitedDebugInfo,
Some(2) => FullDebugInfo,
Some(arg) => {
- early_error(format!("debug info level needs to be between \
- 0-2 (instead was `{}`)",
- arg).as_slice());
+ early_error(&format!("debug info level needs to be between \
+ 0-2 (instead was `{}`)",
+ arg));
}
}
};
"framework" => cstore::NativeFramework,
"static" => cstore::NativeStatic,
s => {
- early_error(format!("unknown library kind `{}`, expected \
- one of dylib, framework, or static",
- s).as_slice());
+ early_error(&format!("unknown library kind `{}`, expected \
+ one of dylib, framework, or static",
+ s));
}
};
return (name.to_string(), kind)
let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None);
let prints = matches.opt_strs("print").into_iter().map(|s| {
- match s.as_slice() {
+ match &*s {
"crate-name" => PrintRequest::CrateName,
"file-names" => PrintRequest::FileNames,
"sysroot" => PrintRequest::Sysroot,
req => {
- early_error(format!("unknown print request `{}`", req).as_slice())
+ early_error(&format!("unknown print request `{}`", req))
}
}
}).collect::<Vec<_>>();
Ok(t) => t,
Err(e) => {
span_diagnostic.handler()
- .fatal((format!("Error loading host specification: {}", e)).as_slice());
+ .fatal(&format!("Error loading host specification: {}", e));
}
};
let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
/// ```
/// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
/// cache: &RefCell<M>,
-/// f: &|&: T| -> U
-/// ) -> impl |&: T| -> U {
+/// f: &|T| -> U
+/// ) -> impl |T| -> U {
/// ```
/// but currently it is not possible.
///
return match region {
ReScope(scope) => {
let new_string;
- let on_unknown_scope = |&:| {
+ let on_unknown_scope = || {
(format!("unknown scope: {:?}. Please report a bug.", scope), None)
};
let span = match scope.span(&cx.map) {
region::CodeExtent::Remainder(r) => {
new_string = format!("block suffix following statement {}",
r.first_statement_index);
- new_string.as_slice()
+ &*new_string
}
};
explain_span(cx, scope_decorated_tag, span)
match unsafety {
ast::Unsafety::Normal => {}
ast::Unsafety::Unsafe => {
- s.push_str(unsafety.to_string().as_slice());
+ s.push_str(&unsafety.to_string());
s.push(' ');
}
};
.iter()
.map(|a| ty_to_string(cx, *a))
.collect::<Vec<_>>();
- s.push_str(strs.connect(", ").as_slice());
+ s.push_str(&strs.connect(", "));
if sig.0.variadic {
s.push_str(", ...");
}
ty_enum(did, substs) | ty_struct(did, substs) => {
let base = ty::item_path_str(cx, did);
let generics = ty::lookup_item_type(cx, did).generics;
- parameterized(cx, base.as_slice(), substs, &generics, did, &[])
+ parameterized(cx, &base, substs, &generics, did, &[])
}
ty_trait(ref data) => {
data.user_string(cx)
let base = ty::item_path_str(tcx, trait_ref.def_id);
let trait_def = ty::lookup_trait_def(tcx, trait_ref.def_id);
parameterized(tcx,
- base.as_slice(),
+ &base,
trait_ref.substs,
&trait_def.generics,
trait_ref.def_id,
let trait_def = ty::lookup_trait_def(tcx, self.def_id);
format!("TraitRef({}, {})",
self.substs.self_ty().repr(tcx),
- parameterized(tcx, base.as_slice(), self.substs,
+ parameterized(tcx, &base, self.substs,
&trait_def.generics, self.def_id, &[]))
}
}
fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
let path_str = ty::item_path_str(tcx, self.def_id);
let trait_def = ty::lookup_trait_def(tcx, self.def_id);
- parameterized(tcx, path_str.as_slice(), self.substs,
+ parameterized(tcx, &path_str, self.substs,
&trait_def.generics, self.def_id, &[])
}
}
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
- self.result(buf.as_mut_slice());
+ self.result(&mut buf);
buf
}
// Test that it works when accepting the message all at once
for t in tests {
sh.reset();
- sh.input_str(t.input.as_slice());
+ sh.input_str(&t.input);
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
let mut sh = box Sha256::new();
- test_hash(&mut *sh, tests.as_slice());
+ test_hash(&mut *sh, &tests);
}
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
let result_str = digest.result_str();
let result_bytes = digest.result_bytes();
- assert_eq!(expected, result_str.as_slice());
+ assert_eq!(expected, result_str);
let expected_vec: Vec<u8> = expected.from_hex()
.unwrap()
let handler = diagnostic::default_handler(diagnostic::Auto, None, true);
- let get_req_field = |&: name: &str| {
+ let get_req_field = |name: &str| {
match obj.find(name)
.map(|s| s.as_string())
.and_then(|os| os.map(|s| s.to_string())) {
impl Fragment {
fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) -> String {
- let repr = |&: mpi| move_data.path_loan_path(mpi).repr(tcx);
+ let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
match *self {
Just(mpi) => repr(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
fn loan_path_user_string<'tcx>(&self,
move_data: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>) -> String {
- let user_string = |&: mpi| move_data.path_loan_path(mpi).user_string(tcx);
+ let user_string = |mpi| move_data.path_loan_path(mpi).user_string(tcx);
match *self {
Just(mpi) => user_string(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
if !span_err && !print { return; }
- let instrument_all_paths = |&: kind, vec_rc: &Vec<MovePathIndex>| {
+ let instrument_all_paths = |kind, vec_rc: &Vec<MovePathIndex>| {
for (i, mpi) in vec_rc.iter().enumerate() {
- let render = |&:| this.path_loan_path(*mpi).user_string(tcx);
+ let render = || this.path_loan_path(*mpi).user_string(tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
}
}
};
- let instrument_all_fragments = |&: kind, vec_rc: &Vec<Fragment>| {
+ let instrument_all_fragments = |kind, vec_rc: &Vec<Fragment>| {
for (i, f) in vec_rc.iter().enumerate() {
- let render = |&:| f.loan_path_user_string(this, tcx);
+ let render = || f.loan_path_user_string(this, tcx);
if span_err {
tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
}
let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
- let path_lps = |&: mpis: &[MovePathIndex]| -> Vec<String> {
+ let path_lps = |mpis: &[MovePathIndex]| -> Vec<String> {
mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
};
- let frag_lps = |&: fs: &[Fragment]| -> Vec<String> {
+ let frag_lps = |fs: &[Fragment]| -> Vec<String> {
fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
};
Rc<LoanPath<'tcx>>)>) {
let parent_ty = parent_lp.to_type();
- let mut add_fragment_sibling_local = |&mut : field_name, variant_did| {
+ let mut add_fragment_sibling_local = |field_name, variant_did| {
add_fragment_sibling_core(
this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
variant_did);
cmt: mc::cmt<'tcx>) -> RestrictionResult<'tcx> {
debug!("restrict(cmt={})", cmt.repr(self.bccx.tcx));
- let new_lp = |&: v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
+ let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat.clone() {
mc::cat_rvalue(..) => {
//! which allows it to share common loan path pieces as it
//! traverses the CMT.
- let new_lp = |&: v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
+ let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat {
mc::cat_rvalue(..) |
}
mc::AliasableClosure(id) => {
self.tcx.sess.span_err(span,
- format!("{} in a captured outer \
- variable in an `Fn` closure", prefix).as_slice());
+ &format!("{} in a captured outer \
+ variable in an `Fn` closure", prefix));
if let BorrowViolation(euv::ClosureCapture(_)) = kind {
// The aliasability violation with closure captures can
// happen for nested closures, so we know the enclosing
fn dataflow_loans_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
let dfcx = &self.analysis_data.loans;
- let loan_index_to_path = |&mut: loan_index| {
+ let loan_index_to_path = |loan_index| {
let all_loans = &self.analysis_data.all_loans;
let l: &borrowck::Loan = &all_loans[loan_index];
l.loan_path()
fn dataflow_moves_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
let dfcx = &self.analysis_data.move_data.dfcx_moves;
- let move_index_to_path = |&mut: move_index| {
+ let move_index_to_path = |move_index| {
let move_data = &self.analysis_data.move_data.move_data;
let moves = move_data.moves.borrow();
let the_move: &borrowck::move_data::Move = &(*moves)[move_index];
fn dataflow_assigns_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
let dfcx = &self.analysis_data.move_data.dfcx_assign;
- let assign_index_to_path = |&mut: assign_index| {
+ let assign_index_to_path = |assign_index| {
let move_data = &self.analysis_data.move_data.move_data;
let assignments = move_data.var_assignments.borrow();
let assignment: &borrowck::move_data::Assignment = &(*assignments)[assign_index];
pub fn basic() -> PhaseController<'a> {
PhaseController {
stop: false,
- callback: box |&: _| {},
+ callback: box |_| {},
}
}
}
}
if let Some(ref s) = sess.opts.show_span {
- syntax::show_span::run(sess.diagnostic(), s.as_slice(), &krate);
+ syntax::show_span::run(sess.diagnostic(), s, &krate);
}
krate
_ => return,
};
- let result = (|&:| -> old_io::IoResult<()> {
+ let result = (|| -> old_io::IoResult<()> {
// Build a list of files used to compile the output and
// write Makefile-compatible dependency rules
let files: Vec<String> = sess.codemap().files.borrow()
pub mod pretty;
pub fn run(args: Vec<String>) -> int {
- monitor(move |:| run_compiler(args.as_slice()));
+ monitor(move || run_compiler(&args));
0
}
let pretty = if sess.opts.debugging_opts.unstable_options {
matches.opt_default("pretty", "normal").map(|a| {
// stable pretty-print variants only
- pretty::parse_pretty(&sess, a.as_slice(), false)
+ pretty::parse_pretty(&sess, &a, false)
})
} else {
None
sess.unstable_options() {
matches.opt_str("xpretty").map(|a| {
// extended with unstable pretty-print variants
- pretty::parse_pretty(&sess, a.as_slice(), true)
+ pretty::parse_pretty(&sess, &a, true)
})
} else {
pretty
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc{}\n",
- getopts::usage(message.as_slice(), groups.as_slice()),
+ getopts::usage(&message, &groups),
extra_help);
}
let max_name_len = plugin.iter().chain(builtin.iter())
.map(|&s| s.name.width(true))
.max().unwrap_or(0);
- let padded = |&: x: &str| {
+ let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
- let print_lints = |&: lints: Vec<&Lint>| {
+ let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}",
let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
.map(|&(s, _)| s.width(true))
.max().unwrap_or(0);
- let padded = |&: x: &str| {
+ let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
- let print_lint_groups = |&: lints: Vec<(&'static str, Vec<lint::LintId>)>| {
+ let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
for (name, to) in lints {
let name = name.chars().map(|x| x.to_lowercase())
.collect::<String>().replace("_", "-");
// unstable ones.
let all_groups : Vec<getopts::OptGroup>
= config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
- match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
+ match getopts::getopts(&args, &all_groups) {
Ok(m_unstable) => {
let r = m_unstable.opt_strs("Z");
let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
if include_unstable_options {
m_unstable
} else {
- early_error(f_stable_attempt.to_string().as_slice());
+ early_error(&f_stable_attempt.to_string());
}
}
Err(_) => {
// ignore the error from the unstable attempt; just
// pass the error we got from the first try.
- early_error(f_stable_attempt.to_string().as_slice());
+ early_error(&f_stable_attempt.to_string());
}
}
}
Some(input) => input,
None => early_error("no input file provided"),
};
- let attrs = attrs.as_ref().unwrap().as_slice();
+ let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs,
sess);
- let id = link::find_crate_name(Some(sess), attrs.as_slice(),
+ let id = link::find_crate_name(Some(sess), attrs,
input);
if *req == PrintRequest::CrateName {
println!("{}", id);
*sess.crate_metadata.borrow_mut() = metadata;
for &style in &crate_types {
let fname = link::filename_for_input(sess, style,
- id.as_slice(),
+ &id,
&t_outputs.with_extension(""));
println!("{}", fname.filename_display());
}
("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
_ => {
if extended {
- sess.fatal(format!(
+ sess.fatal(&format!(
"argument to `xpretty` must be one of `normal`, \
`expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
- `expanded,identified`, or `everybody_loops`; got {}", name).as_slice());
+ `expanded,identified`, or `everybody_loops`; got {}", name));
} else {
- sess.fatal(format!(
+ sess.fatal(&format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `typed`, `identified`, \
- or `expanded,identified`; got {}", name).as_slice());
+ or `expanded,identified`; got {}", name));
}
}
};
}
fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
- let fail_because = |&: is_wrong_because| -> ast::NodeId {
+ let fail_because = |is_wrong_because| -> ast::NodeId {
let message =
format!("{} needs NodeId (int) or unique \
path suffix (b::c::d); got {}, which {}",
krate
};
- let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
+ let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
let is_expanded = needs_expansion(&ppm);
let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
}
debug!("Error: {}", msg);
- match e.messages.iter().position(|m| msg.contains(m.as_slice())) {
+ match e.messages.iter().position(|m| msg.contains(m)) {
Some(i) => {
e.messages.remove(i);
}
fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
debug!("privacy - path {}", self.nodestr(path_id));
let orig_def = self.tcx.def_map.borrow()[path_id].clone();
- let ck = |&: tyname: &str| {
- let ck_public = |&: def: ast::DefId| {
+ let ck = |tyname: &str| {
+ let ck_public = |def: ast::DefId| {
debug!("privacy - ck_public {:?}", def);
let name = token::get_ident(path.segments.last().unwrap().identifier);
let origdid = orig_def.def_id();
}
}
ast::ExprPath(_) | ast::ExprQPath(_) => {
- let guard = |&: did: ast::DefId| {
+ let guard = |did: ast::DefId| {
let fields = ty::lookup_struct_fields(self.tcx, did);
let any_priv = fields.iter().any(|f| {
f.vis != ast::Public && (
/// later on down the road...
fn check_sane_privacy(&self, item: &ast::Item) {
let tcx = self.tcx;
- let check_inherited = |&: sp: Span, vis: ast::Visibility, note: &str| {
+ let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
if vis != ast::Inherited {
tcx.sess.span_err(sp, "unnecessary visibility qualifier");
if note.len() > 0 {
tcx.sess.span_err(sp, "visibility has no effect inside functions");
}
}
- let check_struct = |&: def: &ast::StructDef| {
+ let check_struct = |def: &ast::StructDef| {
for f in &def.fields {
match f.node.kind {
ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
let mut import_resolutions = module_.import_resolutions.borrow_mut();
let import_resolution = &mut (*import_resolutions)[target];
{
- let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
+ let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
let namespace_name = match namespace {
TypeNS => "type",
ValueNS => "value",
// Merge the child item into the import resolution.
{
- let mut merge_child_item = |&mut : namespace| {
+ let mut merge_child_item = |namespace| {
if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
let namespace_name = match namespace {
TypeNS => "type",
in this module",
namespace_name,
token::get_name(name).get());
- span_err!(self.session, import_directive.span, E0251, "{}", msg.as_slice());
+ span_err!(self.session, import_directive.span, E0251, "{}", msg);
} else {
let target = Target::new(containing_module.clone(),
name_bindings.clone(),
}
Some(_) => {
self.resolve_error(path.span,
- format!("`{}` is not an enum variant, struct or const",
+ &format!("`{}` is not an enum variant, struct or const",
token::get_ident(
- path.segments.last().unwrap().identifier)).as_slice());
+ path.segments.last().unwrap().identifier)));
}
None => {
self.resolve_error(path.span,
- format!("unresolved enum variant, struct or const `{}`",
- token::get_ident(
- path.segments.last().unwrap().identifier)).as_slice());
+ &format!("unresolved enum variant, struct or const `{}`",
+ token::get_ident(path.segments.last().unwrap().identifier)));
}
}
Some((span, msg)) => (span, msg),
None => {
let msg = format!("Use of undeclared type or module `{}`",
- self.names_to_string(module_path.as_slice()));
+ self.names_to_string(&module_path));
(path.span, msg)
}
};
let search_result = match namespace {
ValueNS => {
let renamed = mtwt::resolve(ident);
- self.search_ribs(self.value_ribs.as_slice(), renamed, span)
+ self.search_ribs(&self.value_ribs, renamed, span)
}
TypeNS => {
let name = ident.name;
Some((DefVariant(_, _, true), _)) => {
let path_name = self.path_names_to_string(path);
self.resolve_error(expr.span,
- format!("`{}` is a struct variant name, but \
- this expression \
- uses it like a function name",
- path_name).as_slice());
+ &format!("`{}` is a struct variant name, but \
+ this expression \
+ uses it like a function name",
+ path_name));
self.session.span_help(expr.span,
- format!("Did you mean to write: \
- `{} {{ /* fields */ }}`?",
- path_name).as_slice());
+ &format!("Did you mean to write: \
+ `{} {{ /* fields */ }}`?",
+ path_name));
}
Some(def) => {
// Write the result into the def map.
Some((DefTy(struct_id, _), _))
if self.structs.contains_key(&struct_id) => {
self.resolve_error(expr.span,
- format!("`{}` is a structure name, but \
- this expression \
- uses it like a function name",
- path_name).as_slice());
+ &format!("`{}` is a structure name, but \
+ this expression \
+ uses it like a function name",
+ path_name));
self.session.span_help(expr.span,
- format!("Did you mean to write: \
- `{} {{ /* fields */ }}`?",
- path_name).as_slice());
+ &format!("Did you mean to write: \
+ `{} {{ /* fields */ }}`?",
+ path_name));
}
_ => {
NoSuggestion => {
// limit search to 5 to reduce the number
// of stupid suggestions
- self.find_best_match_for_name(path_name.as_slice(), 5)
+ self.find_best_match_for_name(&path_name, 5)
.map_or("".to_string(),
|x| format!("`{}`", x))
}
self.resolve_error(
expr.span,
- format!("unresolved name `{}`{}",
- path_name,
- msg).as_slice());
+ &format!("unresolved name `{}`{}",
+ path_name,
+ msg));
}
}
}
pub fn find_crate_name(sess: Option<&Session>,
attrs: &[ast::Attribute],
input: &Input) -> String {
- let validate = |&: s: String, span: Option<Span>| {
+ let validate = |s: String, span: Option<Span>| {
creader::validate_crate_name(sess, &s[], span);
s
};
// extension to it. This is to work around a bug in LLDB that
// would cause it to crash if the name of a file in an archive
// was exactly 16 bytes.
- let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice());
+ let bc_filename = obj_filename.with_extension(&format!("{}.bc", i));
let bc_deflated_filename = obj_filename.with_extension(
&format!("{}.bytecode.deflate", i)[]);
if sess.opts.cg.rpath {
let sysroot = sess.sysroot();
let target_triple = &sess.opts.target_triple[];
- let get_install_prefix_lib_path = |:| {
+ let get_install_prefix_lib_path = || {
let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
let mut path = Path::new(install_prefix);
// -force_load is the OSX equivalent of --whole-archive, but it
// involves passing the full path to the library to link.
let lib = archive::find_library(&l[],
- sess.target.target.options.staticlib_prefix.as_slice(),
- sess.target.target.options.staticlib_suffix.as_slice(),
+ &sess.target.target.options.staticlib_prefix,
+ &sess.target.target.options.staticlib_suffix,
&search_path[],
&sess.diagnostic().handler);
let mut v = b"-Wl,-force_load,".to_vec();
debug!("reading {}", file);
for i in iter::count(0us, 1) {
let bc_encoded = time(sess.time_passes(),
- format!("check for {}.{}.bytecode.deflate", name, i).as_slice(),
+ &format!("check for {}.{}.bytecode.deflate", name, i),
(),
|_| {
archive.read(&format!("{}.{}.bytecode.deflate",
};
let bc_decoded = if is_versioned_bytecode_format(bc_encoded) {
- time(sess.time_passes(), format!("decode {}.{}.bc", file, i).as_slice(), (), |_| {
+ time(sess.time_passes(), &format!("decode {}.{}.bc", file, i), (), |_| {
// Read the version
let version = extract_bytecode_format_version(bc_encoded);
}
})
} else {
- time(sess.time_passes(), format!("decode {}.{}.bc", file, i).as_slice(), (), |_| {
+ time(sess.time_passes(), &format!("decode {}.{}.bc", file, i), (), |_| {
// the object must be in the old, pre-versioning format, so simply
// inflate everything and let LLVM decide if it can make sense of it
match flate::inflate_bytes(bc_encoded) {
handler.fatal(&msg[]);
} else {
let err = ffi::c_str_to_bytes(&cstr);
- let err = String::from_utf8_lossy(err.as_slice()).to_string();
+ let err = String::from_utf8_lossy(err).to_string();
libc::free(cstr as *mut _);
handler.fatal(&format!("{}: {}",
&msg[],
let tm = unsafe {
let triple = CString::from_slice(triple.as_bytes());
let cpu = match sess.opts.cg.target_cpu {
- Some(ref s) => s.as_slice(),
- None => sess.target.target.options.cpu.as_slice()
+ Some(ref s) => &**s,
+ None => &*sess.target.target.options.cpu
};
let cpu = CString::from_slice(cpu.as_bytes());
let features = CString::from_slice(target_feature(sess).as_bytes());
match llvm::diagnostic::Diagnostic::unpack(info) {
llvm::diagnostic::InlineAsm(inline) => {
report_inline_asm(cgcx,
- llvm::twine_to_string(inline.message).as_slice(),
+ &*llvm::twine_to_string(inline.message),
inline.cookie);
}
if enabled {
let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
- cgcx.handler.note(format!("optimization {} for {} at {}: {}",
- opt.kind.describe(),
- pass_name,
- if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
- llvm::twine_to_string(opt.message)).as_slice());
+ cgcx.handler.note(&format!("optimization {} for {} at {}: {}",
+ opt.kind.describe(),
+ pass_name,
+ if loc.is_empty() { "[unknown]" } else { &*loc },
+ llvm::twine_to_string(opt.message)));
}
}
if config.emit_no_opt_bc {
let ext = format!("{}.no-opt.bc", name_extra);
- let out = output_names.with_extension(ext.as_slice());
+ let out = output_names.with_extension(&ext);
let out = CString::from_slice(out.as_vec());
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
// If we're verifying or linting, add them to the function pass
// manager.
- let addpass = |&: pass: &str| {
+ let addpass = |pass: &str| {
let pass = CString::from_slice(pass.as_bytes());
llvm::LLVMRustAddPass(fpm, pass.as_ptr())
};
for pass in &config.passes {
let pass = CString::from_slice(pass.as_bytes());
if !llvm::LLVMRustAddPass(mpm, pass.as_ptr()) {
- cgcx.handler.warn(format!("unknown pass {:?}, ignoring",
- pass).as_slice());
+ cgcx.handler.warn(&format!("unknown pass {:?}, ignoring", pass));
}
}
if config.emit_lto_bc {
let name = format!("{}.lto.bc", name_extra);
- let out = output_names.with_extension(name.as_slice());
+ let out = output_names.with_extension(&name);
let out = CString::from_slice(out.as_vec());
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
if config.emit_bc {
let ext = format!("{}.bc", name_extra);
- let out = output_names.with_extension(ext.as_slice());
+ let out = output_names.with_extension(&ext);
let out = CString::from_slice(out.as_vec());
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
time(config.time_passes, "codegen passes", (), |()| {
if config.emit_ir {
let ext = format!("{}.ll", name_extra);
- let out = output_names.with_extension(ext.as_slice());
+ let out = output_names.with_extension(&ext);
let out = CString::from_slice(out.as_vec());
with_codegen(tm, llmod, config.no_builtins, |cpm| {
llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
// Produce final compile outputs.
- let copy_if_one_unit = |&: ext: &str, output_type: config::OutputType, keep_numbered: bool| {
+ let copy_if_one_unit = |ext: &str, output_type: config::OutputType, keep_numbered: bool| {
// Three cases:
if sess.opts.cg.codegen_units == 1 {
// 1) Only one codegen unit. In this case it's no difficulty
}
};
- let link_obj = |&: output_path: &Path| {
+ let link_obj = |output_path: &Path| {
// Running `ld -r` on a single input is kind of pointless.
if sess.opts.cg.codegen_units == 1 {
fs::copy(&crate_output.with_extension("0.o"),
let mut tx = Some(tx);
futures.push(rx);
- thread::Builder::new().name(format!("codegen-{}", i)).spawn(move |:| {
+ thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
let diag_handler = mk_handler(true, box diag_emitter);
// Must construct cgcx inside the proc because it has non-Send
let mut llvm_c_strs = Vec::new();
let mut llvm_args = Vec::new();
{
- let mut add = |&mut : arg: &str| {
+ let mut add = |arg: &str| {
let s = CString::from_slice(arg.as_bytes());
llvm_args.push(s.as_ptr());
llvm_c_strs.push(s);
if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
// FIXME #21627 disable faulty FastISel on AArch64 (even for -O0)
- if sess.target.target.arch.as_slice() == "aarch64" { add("-fast-isel=0"); }
+ if sess.target.target.arch == "aarch64" { add("-fast-isel=0"); }
for arg in &sess.opts.cg.llvm_args {
add(&(*arg)[]);
Some(def_id) => {
result.push_str(" as ");
result.push_str(
- ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
+ &ty::item_path_str(&self.analysis.ty_cx, def_id));
},
None => {}
}
item.id);
for field in &struct_def.fields {
- self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
+ self.process_struct_field_def(field, &qualname, variant.node.id);
self.visit_ty(&*field.node.ty);
}
}
let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) {
self.sess.span_bug(span,
- format!("def_map has no key for {} in visit_expr", id).as_slice());
+ &format!("def_map has no key for {} in visit_expr", id));
}
let def = &(*def_map)[id];
let sub_span = self.span.span_for_last_ident(span);
self.fmt.use_glob_str(path.span,
sub_span,
item.id,
- name_string.as_slice(),
+ &name_string,
self.cur_scope);
self.write_sub_paths(path, true);
}
&value[]);
self.visit_ty(&**ty);
- self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
+ self.process_generic_params(ty_params, item.span, &qualname, item.id);
},
ast::ItemMac(_) => (),
_ => visit::walk_item(self, item),
if !needs_span {
self.span.sess.span_bug(span,
- format!("Called record_with_span for '{}' \
- which does not require a span", label).as_slice());
+ &format!("Called record_with_span for '{}' \
+ which does not require a span", label));
}
let values_str = match self.make_values_str(label, fields, values, span) {
pub fn snippet(&self, span: Span) -> String {
match self.sess.codemap().span_to_snippet(span) {
- Some(s) => s,
- None => String::new(),
+ Ok(s) => s,
+ Err(_) => String::new(),
}
}
}
}
- let column_score = |&: m: &[Match], col: uint| -> uint {
+ let column_score = |m: &[Match], col: uint| -> uint {
let total_score = m.iter()
.map(|row| row.pats[col])
.map(|pat| pat_score(def_map, pat))
}
};
- let column_contains_any_nonwild_patterns = |&: &col: &uint| -> bool {
+ let column_contains_any_nonwild_patterns = |&col: &uint| -> bool {
m.iter().any(|row| match row.pats[col].node {
ast::PatWild(_) => false,
_ => true
field_vals.len())
);
let mut vals = field_vals;
- vals.push_all(vals_left.as_slice());
- compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
+ vals.push_all(&vals_left);
+ compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
return;
}
_ => ()
// Use the minimum integer type we figured out above
let fields : Vec<_> = cases.iter().map(|c| {
let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
- ftys.push_all(c.tys.as_slice());
+ ftys.push_all(&c.tys);
if dtor { ftys.push(cx.tcx().types.bool); }
- mk_struct(cx, ftys.as_slice(), false, t)
+ mk_struct(cx, &ftys, false, t)
}).collect();
// This check is needed to avoid increasing the size of types when
// the alignment of the first field is smaller than the overall
// alignment of the type.
- let (_, align) = union_size_and_align(fields.as_slice());
+ let (_, align) = union_size_and_align(&fields);
let mut use_align = true;
for st in &fields {
// Get the first non-zero-sized field
let r = InlineAsmCall(bcx,
asm.as_ptr(),
constraints.as_ptr(),
- inputs.as_slice(),
+ &inputs,
output_type,
ia.volatile,
ia.alignstack,
F: FnOnce(&[&'static str]),
{
TASK_LOCAL_INSN_KEY.with(move |slot| {
- slot.borrow().as_ref().map(move |s| blk(s.as_slice()));
+ slot.borrow().as_ref().map(move |s| blk(s));
})
}
t: Ty<'tcx>,
op: ast::BinOp_)
-> Result<'blk, 'tcx> {
- let f = |&: a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
+ let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
match t.sty {
ty::ty_tup(ref tys) if tys.is_empty() => f(nil_type),
// glue, shims, etc
None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
- _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
- tcx.map.path_to_string(id)).as_slice())
+ _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
+ tcx.map.path_to_string(id)))
};
(blk.id, Some(cfg::CFG::new(tcx, &**blk)))
if let Some(id) = id {
let item = ccx.tcx().map.get(id);
if let ast_map::NodeItem(i) = item {
- if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.as_slice(), "linkage") {
+ if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
if let Some(linkage) = llvm_linkage_by_name(name.get()) {
llvm::SetLinkage(llval, linkage);
} else {
let val = match item {
ast_map::NodeItem(i) => {
let ty = ty::node_id_to_type(ccx.tcx(), i.id);
- let sym = |&:| exported_name(ccx, id, ty, &i.attrs[]);
+ let sym = || exported_name(ccx, id, ty, &i.attrs[]);
let v = match i.node {
ast::ItemStatic(_, _, ref expr) => {
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
let mut compressed = encoder::metadata_encoding_version.to_vec();
- compressed.push_all(match flate::deflate_bytes(metadata.as_slice()) {
+ compressed.push_all(&match flate::deflate_bytes(&metadata) {
Some(compressed) => compressed,
None => cx.sess().fatal("failed to compress metadata"),
- }.as_slice());
+ });
let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[]);
let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
let name = format!("rust_metadata_{}_{}",
unsafe {
let mut declared = HashSet::new();
- let iter_globals = |&: llmod| {
+ let iter_globals = |llmod| {
ValueIter {
cur: llvm::LLVMGetFirstGlobal(llmod),
step: llvm::LLVMGetNextGlobal,
}
};
- let iter_functions = |&: llmod| {
+ let iter_functions = |llmod| {
ValueIter {
cur: llvm::LLVMGetFirstFunction(llmod),
step: llvm::LLVMGetNextFunction,
let name = ffi::c_str_to_bytes(&llvm::LLVMGetValueName(val))
.to_vec();
if !declared.contains(&name) &&
- !reachable.contains(str::from_utf8(name.as_slice()).unwrap()) {
+ !reachable.contains(str::from_utf8(&name).unwrap()) {
llvm::SetLinkage(val, llvm::InternalLinkage);
}
}
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
- Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
+ Type::struct_(ccx, &coerce_to_int(ccx, size), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
- Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
+ Type::struct_(ccx, &coerce_to_int(ccx, size), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
- classify_struct(ty.field_types().as_slice(), cls, ix, off, ty.is_packed());
+ classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
- all_mem(cls.as_mut_slice());
+ all_mem(&mut cls);
return cls;
}
- classify(ty, cls.as_mut_slice(), 0, 0);
- fixup(ty, cls.as_mut_slice());
+ classify(ty, &mut cls, 0, 0);
+ fixup(ty, &mut cls);
return cls;
}
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
- Type::struct_(ccx, tys.as_slice(), false)
+ Type::struct_(ccx, &tys, false)
}
}
{
if !ty.is_reg_ty() {
let cls = classify_ty(ty);
- if is_mem_cls(cls.as_slice()) {
+ if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
- Some(llreg_ty(ccx, cls.as_slice())),
+ Some(llreg_ty(ccx, &cls)),
None,
None)
}
ty::ty_vec(unit_ty, Some(len)) => {
let llunitty = type_of::type_of(cx, unit_ty);
let llptr = ptrcast(llconst, llunitty.ptr_to());
- assert!(cx.const_globals().borrow_mut()
- .insert(llptr as int, llconst).is_none());
+ let prev_const = cx.const_globals().borrow_mut()
+ .insert(llptr as int, llconst);
+ assert!(prev_const.is_none() ||
+ prev_const == Some(llconst));
assert_eq!(abi::FAT_PTR_ADDR, 0);
assert_eq!(abi::FAT_PTR_EXTRA, 1);
llconst = C_struct(cx, &[
// the bool returned is whether this expression can be inlined into other crates
// if it's assigned to a static.
fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef {
- let map_list = |&: exprs: &[P<ast::Expr>]| {
+ let map_list = |exprs: &[P<ast::Expr>]| {
exprs.iter().map(|e| const_expr(cx, &**e).0)
.fold(Vec::new(), |mut l, val| { l.push(val); l })
};
})
}
ast::ExprVec(ref es) => {
- const_vec(cx, e, es.as_slice()).0
+ const_vec(cx, e, es).0
}
ast::ExprRepeat(ref elem, ref count) => {
let vec_ty = ty::expr_ty(cx.tcx(), e);
let mod_name = CString::from_slice(mod_name.as_bytes());
let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
- let data_layout = sess.target.target.data_layout.as_slice();
+ let data_layout = &*sess.target.target.data_layout;
let data_layout = CString::from_slice(data_layout.as_bytes());
llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
- let llvm_target = sess.target.target.llvm_target.as_slice();
+ let llvm_target = &*sess.target.target.llvm_target;
let llvm_target = CString::from_slice(llvm_target.as_bytes());
llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
(llcx, llmod)
// bodies), in which case we also just want to return the span of the
// whole expression.
let code_snippet = cx.sess().codemap().span_to_snippet(node_span);
- if let Some(code_snippet) = code_snippet {
+ if let Ok(code_snippet) = code_snippet {
let bytes = code_snippet.as_bytes();
if bytes.len() > 0 && &bytes[bytes.len()-1..] == b"}" {
let (ident, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
ast_map::NodeItem(ref item) => {
- if contains_nodebug_attribute(item.attrs.as_slice()) {
+ if contains_nodebug_attribute(&item.attrs) {
return FunctionDebugContext::FunctionWithoutDebugInfo;
}
ast_map::NodeImplItem(ref item) => {
match **item {
ast::MethodImplItem(ref method) => {
- if contains_nodebug_attribute(method.attrs.as_slice()) {
+ if contains_nodebug_attribute(&method.attrs) {
return FunctionDebugContext::FunctionWithoutDebugInfo;
}
ast_map::NodeTraitItem(ref trait_method) => {
match **trait_method {
ast::ProvidedMethod(ref method) => {
- if contains_nodebug_attribute(method.attrs.as_slice()) {
+ if contains_nodebug_attribute(&method.attrs) {
return FunctionDebugContext::FunctionWithoutDebugInfo;
}
};
let scope_map = create_scope_map(cx,
- fn_decl.inputs.as_slice(),
+ &fn_decl.inputs,
&*top_level_block,
fn_metadata,
fn_ast_id);
})
.collect();
- let discriminant_type_metadata = |&: inttype| {
+ let discriminant_type_metadata = |inttype| {
// We can reuse the type of the discriminant for all monomorphized
// instances of an enum because it doesn't depend on any type parameters.
// The def_id, uniquely identifying the enum's polytype acts as key in
UNKNOWN_LINE_NUMBER,
bytes_to_bits(discriminant_size),
bytes_to_bits(discriminant_align),
- create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
+ create_DIArray(DIB(cx), &enumerators_metadata),
discriminant_base_type_metadata)
};
match optional_length {
Some(len) => {
- output.push_str(format!("; {}", len).as_slice());
+ output.push_str(&format!("; {}", len));
}
None => { /* nothing to do */ }
};
fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
let omit_gdb_pretty_printer_section =
- attr::contains_name(ccx.tcx()
- .map
- .krate()
- .attrs
- .as_slice(),
+ attr::contains_name(&ccx.tcx()
+ .map
+ .krate()
+ .attrs,
"omit_gdb_pretty_printer_section");
!omit_gdb_pretty_printer_section &&
debug!("dest_ty={}", unsized_ty.repr(bcx.tcx()));
// Closures for extracting and manipulating the data and payload parts of
// the fat pointer.
- let info = |: bcx, _val| unsized_info(bcx,
+ let info = |bcx, _val| unsized_info(bcx,
k,
expr.id,
datum_ty,
-> DatumBlock<'blk, 'tcx, Expr> {
let tcx = bcx.tcx();
let dest_ty = ty::close_type(tcx, datum.ty);
- let base = |: bcx, val| Load(bcx, get_dataptr(bcx, val));
- let len = |: bcx, val| Load(bcx, get_len(bcx, val));
+ let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
+ let len = |bcx, val| Load(bcx, get_len(bcx, val));
into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
}
if let Some(did) = did {
let substs = Substs::new_type(ty_params, vec![]);
trans_struct(bcx,
- fields.as_slice(),
+ &fields,
None,
expr.span,
expr.id,
trans_adt(bcx,
ty,
discr,
- numbered_fields.as_slice(),
+ &numbered_fields,
optbase,
dest,
DebugLoc::At(expr_id, expr_span))
// ABIs are handled at all correctly.
fn gate_simd_ffi(tcx: &ty::ctxt, decl: &ast::FnDecl, ty: &ty::BareFnTy) {
if !tcx.sess.features.borrow().simd_ffi {
- let check = |&: ast_ty: &ast::Ty, ty: ty::Ty| {
+ let check = |ast_ty: &ast::Ty, ty: ty::Ty| {
if ty::type_is_simd(tcx, ty) {
tcx.sess.span_err(ast_ty.span,
&format!("use of SIMD type `{}` in FFI is highly experimental and \
// Array for the arguments we will pass to the rust function.
let mut llrust_args = Vec::new();
let mut next_foreign_arg_counter: c_uint = 0;
- let mut next_foreign_arg = |&mut : pad: bool| -> c_uint {
+ let mut next_foreign_arg = |pad: bool| -> c_uint {
next_foreign_arg_counter += if pad {
2
} else {
debug!("calling llrustfn = {}, t = {}",
ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx()));
let attributes = base::get_fn_llvm_attributes(ccx, t);
- let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), Some(attributes));
+ let llrust_ret_val = builder.call(llrustfn, &llrust_args, Some(attributes));
// Get the return value where the foreign fn expects it.
let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
_ => ccx.sess().bug("foreign_types_for_fn_ty called on non-function type")
};
let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
- let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs.as_slice());
+ let llsig = foreign_signature(ccx, &fn_sig, &fn_sig.inputs);
let fn_ty = cabi::compute_abi_info(ccx,
&llsig.llarg_tys[],
llsig.llret_ty,
ty.repr(ccx.tcx()),
ccx.tn().types_to_str(&llsig.llarg_tys[]),
ccx.tn().type_to_string(llsig.llret_ty),
- ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()),
+ ccx.tn().types_to_str(&fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>()),
ccx.tn().type_to_string(fn_ty.ret_ty.ty),
llsig.ret_def);
}
if tys.fn_sig.variadic {
- Type::variadic_func(llargument_tys.as_slice(), &llreturn_ty)
+ Type::variadic_func(&llargument_tys, &llreturn_ty)
} else {
Type::func(&llargument_tys[], &llreturn_ty)
}
if transmute_restriction.original_from != transmute_restriction.substituted_from {
ccx.sess().span_err(
transmute_restriction.span,
- format!("transmute called on types with potentially different sizes: \
- {} (could be {} bit{}) to {} (could be {} bit{})",
- ty_to_string(ccx.tcx(), transmute_restriction.original_from),
- from_type_size as uint,
- if from_type_size == 1 {""} else {"s"},
- ty_to_string(ccx.tcx(), transmute_restriction.original_to),
- to_type_size as uint,
- if to_type_size == 1 {""} else {"s"}).as_slice());
+ &format!("transmute called on types with potentially different sizes: \
+ {} (could be {} bit{}) to {} (could be {} bit{})",
+ ty_to_string(ccx.tcx(), transmute_restriction.original_from),
+ from_type_size as uint,
+ if from_type_size == 1 {""} else {"s"},
+ ty_to_string(ccx.tcx(), transmute_restriction.original_to),
+ to_type_size as uint,
+ if to_type_size == 1 {""} else {"s"}));
} else {
ccx.sess().span_err(
transmute_restriction.span,
- format!("transmute called on types with different sizes: \
- {} ({} bit{}) to {} ({} bit{})",
- ty_to_string(ccx.tcx(), transmute_restriction.original_from),
- from_type_size as uint,
- if from_type_size == 1 {""} else {"s"},
- ty_to_string(ccx.tcx(), transmute_restriction.original_to),
- to_type_size as uint,
- if to_type_size == 1 {""} else {"s"}).as_slice());
+ &format!("transmute called on types with different sizes: \
+ {} ({} bit{}) to {} ({} bit{})",
+ ty_to_string(ccx.tcx(), transmute_restriction.original_from),
+ from_type_size as uint,
+ if from_type_size == 1 {""} else {"s"},
+ ty_to_string(ccx.tcx(), transmute_restriction.original_to),
+ to_type_size as uint,
+ if to_type_size == 1 {""} else {"s"}));
}
}
}
// This should be caught by the intrinsicck pass
assert_eq!(in_type_size, out_type_size);
- let nonpointer_nonaggregate = |&: llkind: TypeKind| -> bool {
+ let nonpointer_nonaggregate = |llkind: TypeKind| -> bool {
use llvm::TypeKind::*;
match llkind {
Half | Float | Double | X86_FP80 | FP128 |
let simple = get_simple_intrinsic(ccx, &*foreign_item);
let llval = match (simple, name.get()) {
(Some(llfn), _) => {
- Call(bcx, llfn, llargs.as_slice(), None, call_debug_location)
+ Call(bcx, llfn, &llargs, None, call_debug_location)
}
(_, "breakpoint") => {
let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
data.principal_trait_ref_with_self_ty(tcx, object_ty)
}
_ => {
- tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
- object_ty.repr(tcx)).as_slice());
+ tcx.sess.bug(&format!("trans_object_shim() called on non-object: {}",
+ object_ty.repr(tcx)));
}
};
let function_name =
link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
let llfn =
- decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
+ decl_internal_rust_fn(ccx, method_bare_fn_ty, &function_name);
let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
RustCall => {
// unpack the tuple to extract the input type arguments:
match sig.inputs[1].sty {
- ty::ty_tup(ref tys) => tys.as_slice(),
+ ty::ty_tup(ref tys) => &**tys,
_ => {
bcx.sess().bug(
- format!("rust-call expects a tuple not {}",
- sig.inputs[1].repr(tcx)).as_slice());
+ &format!("rust-call expects a tuple not {}",
+ sig.inputs[1].repr(tcx)));
}
}
}
method_bare_fn_ty,
method_offset_in_vtable,
llobject),
- ArgVals(llargs.as_slice()),
+ ArgVals(&llargs),
dest).bcx;
finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
// an object type; this cannot happen because we
// cannot cast an unsized type into a trait object
bcx.sess().bug(
- format!("cannot get vtable for an object type: {}",
- data.repr(bcx.tcx())).as_slice());
+ &format!("cannot get vtable for an object type: {}",
+ data.repr(bcx.tcx())));
}
traits::VtableParam(..) => {
bcx.sess().bug(
// This shouldn't need to option dance.
let mut hash_id = Some(hash_id);
- let mut mk_lldecl = |&mut : abi: abi::Abi| {
+ let mut mk_lldecl = |abi: abi::Abi| {
let lldecl = if abi != abi::Rust {
foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s[])
} else {
ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
lldecl
};
- let setup_lldecl = |&: lldecl, attrs: &[ast::Attribute]| {
+ let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| {
base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
set_llvm_fn_attrs(ccx, attrs, lldecl);
let mut atys: Vec<Type> = Vec::new();
// First, munge the inputs, if this has the `rust-call` ABI.
- let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi);
+ let inputs = untuple_arguments_if_necessary(cx, &sig.inputs, abi);
// Arg 0: Output pointer.
// (if the output type is non-immediate)
}
};
- prohibit_projections(this.tcx(), assoc_bindings.as_slice());
+ prohibit_projections(this.tcx(), &assoc_bindings);
create_substs_for_ast_path(this,
rscope,
match projections {
None => {
- prohibit_projections(this.tcx(), assoc_bindings.as_slice());
+ prohibit_projections(this.tcx(), &assoc_bindings);
}
Some(ref mut v) => {
for binding in &assoc_bindings {
// FIXME(#20300) -- search where clauses, not bounds
suitable_bounds =
- traits::transitive_bounds(tcx, ty_param_def.bounds.trait_bounds.as_slice())
+ traits::transitive_bounds(tcx, &ty_param_def.bounds.trait_bounds)
.filter(|b| trait_defines_associated_type_named(this, b.def_id(), assoc_name))
.collect();
}
let region_bound = compute_region_bound(this,
rscope,
span,
- region_bounds.as_slice(),
+ ®ion_bounds,
principal_trait_ref,
builtin_bounds);
- ty::sort_bounds_list(projection_bounds.as_mut_slice());
+ ty::sort_bounds_list(&mut projection_bounds);
ty::ExistentialBounds {
region_bound: region_bound,
check_pat_enum(pcx, pat, path, subpats, expected);
}
ast::PatStruct(ref path, ref fields, etc) => {
- check_pat_struct(pcx, pat, path, fields.as_slice(), etc, expected);
+ check_pat_struct(pcx, pat, path, fields, etc, expected);
}
ast::PatTup(ref elements) => {
let element_tys: Vec<_> =
.unwrap_or_else(|| Substs::empty());
let struct_fields = ty::struct_fields(tcx, variant_def_id, &item_substs);
- check_struct_pat_fields(pcx, pat.span, fields, struct_fields.as_slice(),
+ check_struct_pat_fields(pcx, pat.span, fields, &struct_fields,
variant_def_id, etc);
}
call_expr.span,
expected,
fn_sig.output,
- fn_sig.inputs.as_slice());
+ &fn_sig.inputs);
check_argument_types(fcx,
call_expr.span,
- fn_sig.inputs.as_slice(),
+ &fn_sig.inputs,
&expected_arg_tys[],
arg_exprs,
AutorefArgs::No,
None => {
self.tcx().sess.span_bug(
self.span,
- format!("cannot upcast `{}` to `{}`",
- source_trait_ref.repr(self.tcx()),
- target_trait_def_id.repr(self.tcx())).as_slice());
+ &format!("cannot upcast `{}` to `{}`",
+ source_trait_ref.repr(self.tcx()),
+ target_trait_def_id.repr(self.tcx())));
}
}
}
})
.collect();
- self.elaborate_bounds(bounds.as_slice(), |this, poly_trait_ref, m, method_num| {
+ self.elaborate_bounds(&bounds, |this, poly_trait_ref, m, method_num| {
let trait_ref =
this.erase_late_bound_regions(&poly_trait_ref);
}
}
let cstore = &ccx.tcx.sess.cstore;
- cstore.iter_crate_data(|&mut: cnum, _| {
+ cstore.iter_crate_data(|cnum, _| {
csearch::each_top_level_item_of_crate(cstore, cnum, |dl, _, _| {
handle_external_def(&mut traits, ccx, cstore, dl)
})
check_impl_items_against_trait(ccx,
it.span,
&*impl_trait_ref,
- impl_items.as_slice());
+ impl_items);
}
None => { }
}
fn check_trait_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
generics: &ast::Generics,
item: &ast::Item) {
- if let Some(ref attr) = item.attrs.iter().find(|&: a| {
+ if let Some(ref attr) = item.attrs.iter().find(|a| {
a.check_name("rustc_on_unimplemented")
}) {
if let Some(ref istring) = attr.value_str() {
let parser = Parser::new(istring.get());
- let types = generics.ty_params.as_slice();
+ let types = &*generics.ty_params;
for token in parser {
match token {
Piece::String(_) => (), // Normal string, no need to check it
// caught in resolve.
tcx.sess.span_bug(
impl_method.span,
- format!("item `{}` is of a different kind from its trait `{}`",
- token::get_name(impl_item_ty.name()),
- impl_trait_ref.repr(tcx)).as_slice());
+ &format!("item `{}` is of a different kind from its trait `{}`",
+ token::get_name(impl_item_ty.name()),
+ impl_trait_ref.repr(tcx)));
}
}
}
// caught in resolve.
tcx.sess.span_bug(
impl_method.span,
- format!("method `{}` is not a member of trait `{}`",
- token::get_name(impl_item_ty.name()),
- impl_trait_ref.repr(tcx)).as_slice());
+ &format!("method `{}` is not a member of trait `{}`",
+ token::get_name(impl_item_ty.name()),
+ impl_trait_ref.repr(tcx)));
}
}
}
// already been caught in resolve.
tcx.sess.span_bug(
typedef.span,
- format!("item `{}` is of a different kind from its trait `{}`",
- token::get_name(typedef_ty.name()),
- impl_trait_ref.repr(tcx)).as_slice());
+ &format!("item `{}` is of a different kind from its trait `{}`",
+ token::get_name(typedef_ty.name()),
+ impl_trait_ref.repr(tcx)));
}
}
}
// caught in resolve.
tcx.sess.span_bug(
typedef.span,
- format!(
+ &format!(
"associated type `{}` is not a member of \
trait `{}`",
token::get_name(typedef_ty.name()),
- impl_trait_ref.repr(tcx)).as_slice());
+ impl_trait_ref.repr(tcx)));
}
}
}
{
let raw_ty = self.expr_ty(expr);
let raw_ty = self.infcx().shallow_resolve(raw_ty);
- let resolve_ty = |&: ty: Ty<'tcx>| self.infcx().resolve_type_vars_if_possible(&ty);
+ let resolve_ty = |ty: Ty<'tcx>| self.infcx().resolve_type_vars_if_possible(&ty);
ty::adjust_ty(self.tcx(),
expr.span,
expr.id,
}
if let Some(n) = best {
tcx.sess.span_help(field.span,
- format!("did you mean `{}`?", n).as_slice());
+ &format!("did you mean `{}`?", n));
}
}
}
}
ast::ExprMatch(ref discrim, ref arms, match_src) => {
- _match::check_match(fcx, expr, &**discrim, arms.as_slice(), expected, match_src);
+ _match::check_match(fcx, expr, &**discrim, arms, expected, match_src);
}
ast::ExprClosure(capture, ref decl, ref body) => {
closure::check_expr_closure(fcx, expr, capture, &**decl, &**body, expected);
pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) {
fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
- let name = token::intern(format!("P{}", n).as_slice());
+ let name = token::intern(&format!("P{}", n));
ty::mk_param(ccx.tcx, subst::FnSpace, n, name)
}
ObjectSafetyViolation::Method(method, MethodViolationCode::ByValueSelf) => {
tcx.sess.span_note(
span,
- format!("method `{}` has a receiver type of `Self`, \
- which cannot be used with a trait object",
- method.name.user_string(tcx)).as_slice());
+ &format!("method `{}` has a receiver type of `Self`, \
+ which cannot be used with a trait object",
+ method.name.user_string(tcx)));
}
ObjectSafetyViolation::Method(method, MethodViolationCode::StaticMethod) => {
tcx.sess.span_note(
span,
- format!("method `{}` has no receiver",
- method.name.user_string(tcx)).as_slice());
+ &format!("method `{}` has no receiver",
+ method.name.user_string(tcx)));
}
ObjectSafetyViolation::Method(method, MethodViolationCode::ReferencesSelf) => {
tcx.sess.span_note(
span,
- format!("method `{}` references the `Self` type \
- in its arguments or return type",
- method.name.user_string(tcx)).as_slice());
+ &format!("method `{}` references the `Self` type \
+ in its arguments or return type",
+ method.name.user_string(tcx)));
}
ObjectSafetyViolation::Method(method, MethodViolationCode::Generic) => {
tcx.sess.span_note(
span,
- format!("method `{}` has generic type parameters",
- method.name.user_string(tcx)).as_slice());
+ &format!("method `{}` has generic type parameters",
+ method.name.user_string(tcx)));
}
}
}
variants.iter().flat_map(|v| v.fields.iter().map(|f| f.ty)).collect();
regionck::regionck_ensure_component_tys_wf(
- fcx, item.span, field_tys.as_slice());
+ fcx, item.span, &field_tys);
});
}
// There are special rules that apply to drop.
if
fcx.tcx().lang_items.drop_trait() == Some(trait_ref.def_id) &&
- !attr::contains_name(item.attrs.as_slice(), "unsafe_destructor")
+ !attr::contains_name(&item.attrs, "unsafe_destructor")
{
match self_ty.sty {
ty::ty_struct(def_id, _) |
param_ty.user_string(self.tcx));
self.tcx.sess.span_note(
item.span,
- format!("for a limited time, you can add \
- `#![feature(old_orphan_check)]` to your crate \
- to disable this rule").as_slice());
+ &format!("for a limited time, you can add \
+ `#![feature(old_orphan_check)]` to your crate \
+ to disable this rule"));
}
}
}
ty_of_foreign_item(self, &*foreign_item, abi)
}
x => {
- self.tcx.sess.bug(format!("unexpected sort of node \
- in get_item_type_scheme(): {:?}",
- x).as_slice());
+ self.tcx.sess.bug(&format!("unexpected sort of node \
+ in get_item_type_scheme(): {:?}",
+ x));
}
}
}
write_ty_to_tcx(tcx, it.id, scheme.ty);
get_enum_variant_types(ccx,
scheme.ty,
- enum_definition.variants.as_slice(),
+ &enum_definition.variants,
generics);
},
ast::ItemImpl(_, _,
ref generics,
ref supertraits,
ref items) => {
- (unsafety, generics, supertraits, items.as_slice())
+ (unsafety, generics, supertraits, items)
}
ref s => {
tcx.sess.span_bug(
let bounds = compute_bounds(ccx,
self_param_ty.to_ty(ccx.tcx),
- bounds.as_slice(),
+ bounds,
SizedByDefault::No,
it.span);
let bounds = compute_bounds(ccx,
assoc_ty,
- assoc_type_def.bounds.as_slice(),
+ &*assoc_type_def.bounds,
SizedByDefault::Yes,
assoc_type_def.span);
let astconv::PartitionedBounds { builtin_bounds,
trait_bounds,
region_bounds } =
- astconv::partition_bounds(ccx.tcx, span, ast_bounds.as_slice());
+ astconv::partition_bounds(ccx.tcx, span, ast_bounds);
let mut projection_bounds = Vec::new();
if ty::has_attr(tcx, impl_def_id, "old_impl_check") {
tcx.sess.span_warn(
ty_param.span,
- format!("the type parameter `{}` is not constrained by the \
- impl trait, self type, or predicates",
- param_ty.user_string(tcx)).as_slice());
+ &format!("the type parameter `{}` is not constrained by the \
+ impl trait, self type, or predicates",
+ param_ty.user_string(tcx)));
} else {
span_err!(tcx.sess, ty_param.span, E0207,
"the type parameter `{}` is not constrained by the \
param_ty.user_string(tcx));
tcx.sess.span_help(
ty_param.span,
- format!("you can temporarily opt out of this rule by placing \
- the `#[old_impl_check]` attribute on the impl").as_slice());
+ &format!("you can temporarily opt out of this rule by placing \
+ the `#[old_impl_check]` attribute on the impl"));
}
}
}
use self::ParamKind::*;
use arena;
-use arena::Arena;
+use arena::TypedArena;
use middle::resolve_lifetime as rl;
use middle::subst;
use middle::subst::{ParamSpace, FnSpace, TypeSpace, SelfSpace, VecPerParamSpace};
pub fn infer_variance(tcx: &ty::ctxt) {
let krate = tcx.map.krate();
- let mut arena = arena::Arena::new();
+ let mut arena = arena::TypedArena::new();
let terms_cx = determine_parameters_to_be_inferred(tcx, &mut arena, krate);
let constraints_cx = add_constraints_from_crate(terms_cx, krate);
solve_constraints(constraints_cx);
struct TermsContext<'a, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
- arena: &'a Arena,
+ arena: &'a TypedArena<VarianceTerm<'a>>,
empty_variances: Rc<ty::ItemVariances>,
}
fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
- arena: &'a mut Arena,
+ arena: &'a mut TypedArena<VarianceTerm<'a>>,
krate: &ast::Crate)
-> TermsContext<'a, 'tcx> {
let mut terms_cx = TermsContext {
index: uint,
param_id: ast::NodeId) {
let inf_index = InferredIndex(self.inferred_infos.len());
- let term = self.arena.alloc(|| InferredTerm(inf_index));
+ let term = self.arena.alloc(InferredTerm(inf_index));
self.inferred_infos.push(InferredInfo { item_id: item_id,
kind: kind,
space: space,
let unsafe_lang_item = terms_cx.tcx.lang_items.unsafe_type();
- let covariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Covariant));
- let contravariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Contravariant));
- let invariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Invariant));
- let bivariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Bivariant));
+ let covariant = terms_cx.arena.alloc(ConstantTerm(ty::Covariant));
+ let contravariant = terms_cx.arena.alloc(ConstantTerm(ty::Contravariant));
+ let invariant = terms_cx.arena.alloc(ConstantTerm(ty::Invariant));
+ let bivariant = terms_cx.arena.alloc(ConstantTerm(ty::Bivariant));
let mut constraint_cx = ConstraintContext {
terms_cx: terms_cx,
// parameter (by inspecting parent of its binding declaration
// to see if it is introduced by a type or by a fn/impl).
- let check_result = |&: this:&ConstraintContext| -> bool {
+ let check_result = |this:&ConstraintContext| -> bool {
let tcx = this.terms_cx.tcx;
let decl_id = this.find_binding_for_lifetime(param_id);
// Currently only called on lifetimes; double-checking that.
}
_ => {
- &*self.terms_cx.arena.alloc(|| TransformTerm(v1, v2))
+ &*self.terms_cx.arena.alloc(TransformTerm(v1, v2))
}
}
}
let fields = ty::lookup_struct_fields(tcx, did);
clean::Struct {
- struct_type: match fields.as_slice() {
+ struct_type: match &*fields {
[] => doctree::Unit,
[ref f] if f.name == unnamed_field.name => doctree::Newtype,
[ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
let polarity = csearch::get_impl_polarity(tcx, did);
return Some(clean::Item {
inner: clean::ImplItem(clean::Impl {
- derived: clean::detect_derived(attrs.as_slice()),
+ derived: clean::detect_derived(&attrs),
trait_: associated_trait.clean(cx).map(|bound| {
match bound {
clean::TraitBound(polyt, _) => polyt.trait_,
use std::rc::Rc;
use std::u32;
-use std::str::Str as StrTrait; // Conflicts with Str variant
use std::old_path::Path as FsPath; // Conflicts with Path struct
use core::DocContext;
// Figure out the name of this crate
let input = &cx.input;
- let name = link::find_crate_name(None, self.attrs.as_slice(), input);
+ let name = link::find_crate_name(None, &self.attrs, input);
// Clean the crate, translating the entire libsyntax AST to one that is
// understood by rustdoc.
ModuleItem(..) => {}
_ => continue,
}
- let prim = match PrimitiveType::find(child.attrs.as_slice()) {
+ let prim = match PrimitiveType::find(&child.attrs) {
Some(prim) => prim,
None => continue,
};
_ => return
};
let attrs = inline::load_attrs(cx, tcx, did);
- PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
+ PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
})
});
ExternalCrate {
for attr in &self.attrs {
match *attr {
List(ref x, ref list) if "doc" == *x => {
- return Some(list.as_slice());
+ return Some(list);
}
_ => {}
}
for attr in &self.attrs {
match *attr {
NameValue(ref x, ref v) if "doc" == *x => {
- return Some(v.as_slice());
+ return Some(v);
}
_ => {}
}
fn name(&self) -> InternedString {
match *self {
Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
- token::intern_and_get_ident(n.as_slice())
+ token::intern_and_get_ident(n)
}
}
}
fn value_str(&self) -> Option<InternedString> {
match *self {
NameValue(_, ref v) => {
- Some(token::intern_and_get_ident(v.as_slice()))
+ Some(token::intern_and_get_ident(v))
}
_ => None,
}
let fqn = csearch::get_item_path(tcx, self.def_id);
let fqn = fqn.into_iter().map(|i| i.to_string())
.collect::<Vec<String>>();
- let path = external_path(cx, fqn.last().unwrap().as_slice(),
+ let path = external_path(cx, fqn.last().unwrap(),
Some(self.def_id), vec![], self.substs);
cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
(fqn, TypeTrait));
impl Lifetime {
pub fn get_ref<'a>(&'a self) -> &'a str {
let Lifetime(ref s) = *self;
- let s: &'a str = s.as_slice();
+ let s: &'a str = s;
return s;
}
fn clean(&self, cx: &DocContext) -> Item {
let all_inputs = &self.pe_fn_decl().inputs;
let inputs = match self.pe_explicit_self().node {
- ast::SelfStatic => all_inputs.as_slice(),
+ ast::SelfStatic => &**all_inputs,
_ => &all_inputs[1..]
};
let decl = FnDecl {
impl Clean<Item> for ast::TypeMethod {
fn clean(&self, cx: &DocContext) -> Item {
let inputs = match self.explicit_self.node {
- ast::SelfStatic => self.decl.inputs.as_slice(),
+ ast::SelfStatic => &*self.decl.inputs,
_ => &self.decl.inputs[1..]
};
let decl = FnDecl {
} else {
Vec::new().into_iter()
}.peekable();
- if names.peek().map(|s| s.as_slice()) == Some("self") {
+ if names.peek().map(|s| &**s) == Some("self") {
let _ = names.next();
}
FnDecl {
impl PrimitiveType {
fn from_str(s: &str) -> Option<PrimitiveType> {
- match s.as_slice() {
+ match s {
"isize" | "int" => Some(Isize),
"i8" => Some(I8),
"i16" => Some(I16),
for sub_attr in list {
let value = match *sub_attr {
NameValue(ref k, ref v)
- if *k == "primitive" => v.as_slice(),
+ if *k == "primitive" => v,
_ => continue,
};
match PrimitiveType::from_str(value) {
ty::ty_struct(..) => TypeStruct,
_ => TypeEnum,
};
- let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
+ let path = external_path(cx, &fqn.last().unwrap().to_string(),
None, vec![], substs);
cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
ResolvedPath {
let fqn = csearch::get_item_path(cx.tcx(), did);
let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
let (typarams, bindings) = bounds.clean(cx);
- let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
+ let path = external_path(cx, &fqn.last().unwrap().to_string(),
Some(did), bindings, principal.substs());
cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
ResolvedPath {
impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
fn clean(&self, cx: &DocContext) -> Item {
// use syntax::parse::token::special_idents::unnamed_field;
- let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
+ let kind = match self.arg_names.as_ref().map(|s| &**s) {
None | Some([]) if self.args.len() == 0 => CLikeVariant,
None | Some([]) => {
TupleVariant(self.args.clean(cx))
TypeImplItem(i) => i,
}
}).collect(),
- derived: detect_derived(self.attrs.as_slice()),
+ derived: detect_derived(&self.attrs),
polarity: Some(self.polarity.clean(cx)),
}),
}
fn to_src(&self, cx: &DocContext) -> String {
debug!("converting span {:?} to snippet", self.clean(cx));
let sn = match cx.sess().codemap().span_to_snippet(*self) {
- Some(x) => x.to_string(),
- None => "".to_string()
+ Ok(x) => x.to_string(),
+ Err(_) => "".to_string()
};
debug!("got snippet {}", sn);
sn
let krate = driver::phase_1_parse_input(&sess, cfg, &input);
- let name = link::find_crate_name(Some(&sess), krate.attrs.as_slice(),
+ let name = link::find_crate_name(Some(&sess), &krate.attrs,
&input);
- let krate = driver::phase_2_configure_and_expand(&sess, krate, name.as_slice(), None)
+ let krate = driver::phase_2_configure_and_expand(&sess, krate, &name, None)
.expect("phase_2_configure_and_expand aborted in rustdoc!");
let mut forest = ast_map::Forest::new(krate);
pub fn load_string(input: &Path) -> old_io::IoResult<Option<String>> {
let mut f = try!(old_io::File::open(input));
let d = try!(f.read_to_end());
- Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string()).ok())
+ Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
}
macro_rules! load_or_return {
pub fn load_external_files(names: &[String]) -> Option<String> {
let mut out = String::new();
for name in names {
- out.push_str(load_or_return!(name.as_slice(), None, None).as_slice());
+ out.push_str(&*load_or_return!(&name, None, None));
out.push('\n');
}
Some(out)
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *self;
- let pile_o_bits = s.as_slice();
+ let pile_o_bits = s;
let mut last = 0;
for (i, ch) in s.bytes().enumerate() {
match ch as char {
if i > 0 {
try!(f.write_str(", "))
}
- try!(f.write_str(tp.name.as_slice()));
+ try!(f.write_str(&tp.name));
if tp.bounds.len() > 0 {
- try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice())));
+ try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
}
match tp.default {
}
match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
- let bounds = bounds.as_slice();
+ let bounds = bounds;
try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
}
&clean::WherePredicate::RegionPredicate { ref lifetime,
impl fmt::Display for clean::PathSegment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(f.write_str(self.name.as_slice()));
+ try!(f.write_str(&self.name));
write!(f, "{}", self.params)
}
}
let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
let cache = cache();
- let abs_root = root(&*cache, loc.as_slice());
- let rel_root = match path.segments[0].name.as_slice() {
+ let abs_root = root(&*cache, &loc);
+ let rel_root = match &*path.segments[0].name {
"self" => Some("./".to_string()),
_ => None,
};
let amt = path.segments.len() - 1;
match rel_root {
Some(root) => {
- let mut root = String::from_str(root.as_slice());
+ let mut root = String::from_str(&root);
for seg in &path.segments[..amt] {
if "super" == seg.name ||
"self" == seg.name {
try!(write!(w, "{}::", seg.name));
} else {
- root.push_str(seg.name.as_slice());
+ root.push_str(&seg.name);
root.push_str("/");
try!(write!(w, "<a class='mod'
href='{}index.html'>{}</a>::",
- root.as_slice(),
+ root,
seg.name));
}
}
match info(&*cache) {
// This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => {
- let mut url = String::from_str(abs_root.unwrap().as_slice());
+ let mut url = String::from_str(&abs_root.unwrap());
let to_link = &fqp[..fqp.len() - 1];
for component in to_link {
- url.push_str(component.as_slice());
+ url.push_str(component);
url.push_str("/");
}
match shortty {
ItemType::Module => {
- url.push_str(fqp.last().unwrap().as_slice());
+ url.push_str(fqp.last().unwrap());
url.push_str("/index.html");
}
_ => {
url.push_str(shortty.to_static_str());
url.push_str(".");
- url.push_str(fqp.last().unwrap().as_slice());
+ url.push_str(fqp.last().unwrap());
url.push_str(".html");
}
}
try!(write!(w, "{}", last.name));
}
}
- try!(write!(w, "{}", generics.as_slice()));
+ try!(write!(w, "{}", generics));
Ok(())
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::TyParamBinder(id) => {
- f.write_str(cache().typarams[ast_util::local_def(id)].as_slice())
+ f.write_str(&cache().typarams[ast_util::local_def(id)])
}
clean::Generic(ref name) => {
- f.write_str(name.as_slice())
+ f.write_str(name)
}
clean::ResolvedPath{ did, ref typarams, ref path } => {
try!(resolved_path(f, did, path, false));
clean::BareFunction(ref decl) => {
write!(f, "{}{}fn{}{}",
UnsafetySpace(decl.unsafety),
- match decl.abi.as_slice() {
+ match &*decl.abi {
"" => " extern ".to_string(),
"\"Rust\"" => "".to_string(),
s => format!(" extern {} ", s)
}
clean::Tuple(ref typs) => {
primitive_link(f, clean::PrimitiveTuple,
- match typs.as_slice() {
+ &*match &**typs {
[ref one] => format!("({},)", one),
- many => format!("({})",
- CommaSep(many.as_slice()))
- }.as_slice())
+ many => format!("({})", CommaSep(&many)),
+ })
}
clean::Vector(ref t) => {
- primitive_link(f, clean::Slice, format!("[{}]", **t).as_slice())
+ primitive_link(f, clean::Slice, &format!("[{}]", **t))
}
clean::FixedVector(ref t, ref s) => {
primitive_link(f, clean::Slice,
- format!("[{}; {}]", **t, *s).as_slice())
+ &format!("[{}; {}]", **t, *s))
}
clean::Bottom => f.write_str("!"),
clean::RawPointer(m, ref t) => {
match **bt {
clean::Generic(_) =>
primitive_link(f, clean::Slice,
- format!("&{}{}[{}]", lt, m, **bt).as_slice()),
+ &format!("&{}{}[{}]", lt, m, **bt)),
_ => {
try!(primitive_link(f, clean::Slice,
- format!("&{}{}[", lt, m).as_slice()));
+ &format!("&{}{}[", lt, m)));
try!(write!(f, "{}", **bt));
primitive_link(f, clean::Slice, "]")
}
clean::SelfStatic => {},
clean::SelfValue => args.push_str("self"),
clean::SelfBorrowed(Some(ref lt), mtbl) => {
- args.push_str(format!("&{} {}self", *lt,
- MutableSpace(mtbl)).as_slice());
+ args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
}
clean::SelfBorrowed(None, mtbl) => {
- args.push_str(format!("&{}self",
- MutableSpace(mtbl)).as_slice());
+ args.push_str(&format!("&{}self", MutableSpace(mtbl)));
}
clean::SelfExplicit(ref typ) => {
- args.push_str(format!("self: {}", *typ).as_slice());
+ args.push_str(&format!("self: {}", *typ));
}
}
for (i, input) in d.inputs.values.iter().enumerate() {
if i > 0 || args.len() > 0 { args.push_str(", "); }
if input.name.len() > 0 {
- args.push_str(format!("{}: ", input.name).as_slice());
+ args.push_str(&format!("{}: ", input.name));
}
- args.push_str(format!("{}", input.type_).as_slice());
+ args.push_str(&format!("{}", input.type_));
}
write!(f, "({args}){arrow}", args = args, arrow = d.output)
}
let tot = cnt.total();
if tot == 0 { return Ok(()) }
- context.push(m.name.as_slice());
+ context.push(&m.name);
let path = context.connect("::");
try!(write!(f, "<tr>"));
loop {
let next = lexer.next_token();
- let snip = |&: sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
+ let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
if next.tok == token::Eof { break }
let klass = match next.tok {
token::Whitespace => {
- try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
+ try!(write!(out, "{}", Escape(&snip(next.sp))));
continue
},
token::Comment => {
try!(write!(out, "<span class='comment'>{}</span>",
- Escape(snip(next.sp).as_slice())));
+ Escape(&snip(next.sp))));
continue
},
token::Shebang(s) => {
// stringifying this token
let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
if klass == "" {
- try!(write!(out, "{}", Escape(snip.as_slice())));
+ try!(write!(out, "{}", Escape(&snip)));
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
- Escape(snip.as_slice())));
+ Escape(&snip)));
}
}
let test = origtext.lines().map(|l| {
stripped_filtered_line(l).unwrap_or(l)
}).collect::<Vec<&str>>().connect("\n");
- let krate = krate.as_ref().map(|s| s.as_slice());
- let test = test::maketest(test.as_slice(), krate, false, false);
- s.push_str(format!("<span class='rusttest'>{}</span>",
- Escape(test.as_slice())).as_slice());
+ let krate = krate.as_ref().map(|s| &**s);
+ let test = test::maketest(&test, krate, false, false);
+ s.push_str(&format!("<span class='rusttest'>{}</span>", Escape(&test)));
});
- s.push_str(highlight::highlight(text.as_slice(),
- None,
- Some("rust-example-rendered"))
- .as_slice());
+ s.push_str(&highlight::highlight(&text,
+ None,
+ Some("rust-example-rendered")));
let output = CString::from_vec(s.into_bytes());
hoedown_buffer_puts(ob, output.as_ptr());
})
let mut seen_other_tags = false;
let mut data = LangString::all_false();
- let tokens = string.split(|&: c: char|
+ let tokens = string.split(|c: char|
!(c == '_' || c == '-' || c.is_alphanumeric())
);
let Markdown(md) = *self;
// This is actually common enough to special-case
if md.len() == 0 { return Ok(()) }
- render(fmt, md.as_slice(), false)
+ render(fmt, md, false)
}
}
impl<'a> fmt::Display for MarkdownWithToc<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let MarkdownWithToc(md) = *self;
- render(fmt, md.as_slice(), true)
+ render(fmt, md, true)
}
}
#[test]
fn issue_17736() {
let markdown = "# title";
- format!("{}", Markdown(markdown.as_slice()));
+ format!("{}", Markdown(markdown));
}
#[test]
path = "";
} else {
lastpath = item.path.to_string();
- path = item.path.as_slice();
+ path = &item.path;
};
if i > 0 {
if !line.starts_with(key) {
continue
}
- if line.starts_with(
- format!("{}['{}']", key, krate).as_slice()) {
+ if line.starts_with(&format!("{}['{}']", key, krate)) {
continue
}
ret.push(line.to_string());
// Update the search index
let dst = cx.dst.join("search-index.js");
- let all_indexes = try!(collect(&dst, krate.name.as_slice(),
- "searchIndex"));
+ let all_indexes = try!(collect(&dst, &krate.name, "searchIndex"));
let mut w = try!(File::create(&dst));
try!(writeln!(&mut w, "var searchIndex = {{}};"));
try!(writeln!(&mut w, "{}", search_index));
let mut mydst = dst.clone();
for part in &remote_path[..remote_path.len() - 1] {
- mydst.push(part.as_slice());
+ mydst.push(part);
try!(mkdir(&mydst));
}
mydst.push(format!("{}.{}.js",
remote_item_type.to_static_str(),
remote_path[remote_path.len() - 1]));
- let all_implementors = try!(collect(&mydst, krate.name.as_slice(),
+ let all_implementors = try!(collect(&mydst, &krate.name,
"implementors"));
try!(mkdir(&mydst.dir_path()));
info!("emitting source files");
let dst = cx.dst.join("src");
try!(mkdir(&dst));
- let dst = dst.join(krate.name.as_slice());
+ let dst = dst.join(&krate.name);
try!(mkdir(&dst));
let mut folder = SourceCollector {
dst: dst,
if ".." == c {
f("up");
} else {
- f(c.as_slice())
+ f(c)
}
}
}
/// rendering in to the specified source destination.
fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
// See if there's documentation generated into the local directory
- let local_location = dst.join(e.name.as_slice());
+ let local_location = dst.join(&e.name);
if local_location.is_dir() {
return Local;
}
// entire crate. The other option is maintaining this mapping on a
// per-file basis, but that's probably not worth it...
self.cx
- .include_sources = match self.emit_source(item.source
- .filename
- .as_slice()) {
+ .include_sources = match self.emit_source(&item.source .filename) {
Ok(()) => true,
Err(e) => {
println!("warning: source code was requested to be rendered, \
filename.ends_with("macros>") => return Ok(()),
Err(e) => return Err(e)
};
- let contents = str::from_utf8(contents.as_slice()).unwrap();
+ let contents = str::from_utf8(&contents).unwrap();
// Remove the utf-8 BOM if any
let contents = if contents.starts_with("\u{feff}") {
let title = format!("{} -- source", cur.filename_display());
let desc = format!("Source to the Rust file `{}`.", filename);
let page = layout::Page {
- title: title.as_slice(),
+ title: &title,
ty: "source",
- root_path: root_path.as_slice(),
- description: desc.as_slice(),
+ root_path: &root_path,
+ description: &desc,
keywords: get_basic_keywords(),
};
try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
Some(&(ref fqp, ItemType::Struct)) |
Some(&(ref fqp, ItemType::Enum)) =>
Some(&fqp[..fqp.len() - 1]),
- Some(..) => Some(self.stack.as_slice()),
+ Some(..) => Some(&*self.stack),
None => None
};
((Some(*last), path), true)
}
}
- _ => ((None, Some(self.stack.as_slice())), false)
+ _ => ((None, Some(&*self.stack)), false)
};
let hidden_field = match item.inner {
clean::StructFieldItem(clean::HiddenStructField) => true,
panic!("Unexpected empty destination: {:?}", self.current);
}
let prev = self.dst.clone();
- self.dst.push(s.as_slice());
+ self.dst.push(&s);
self.root_path.push_str("../");
self.current.push(s);
this.layout.krate);
let page = layout::Page {
ty: "mod",
- root_path: this.root_path.as_slice(),
- title: title.as_slice(),
- description: desc.as_slice(),
+ root_path: &this.root_path,
+ title: &title,
+ description: &desc,
keywords: get_basic_keywords(),
};
let html_dst = &this.dst.join("stability.html");
if title.len() > 0 {
title.push_str("::");
}
- title.push_str(it.name.as_ref().unwrap().as_slice());
+ title.push_str(it.name.as_ref().unwrap());
}
title.push_str(" - Rust");
let tyname = shortty(it).to_static_str();
let keywords = make_item_keywords(it);
let page = layout::Page {
ty: tyname,
- root_path: cx.root_path.as_slice(),
- title: title.as_slice(),
- description: desc.as_slice(),
- keywords: keywords.as_slice(),
+ root_path: &cx.root_path,
+ title: &title,
+ description: &desc,
+ keywords: &keywords,
};
markdown::reset_headers();
match cache().paths.get(&it.def_id) {
Some(&(ref names, _)) => {
for name in &names[..names.len() - 1] {
- url.push_str(name.as_slice());
+ url.push_str(name);
url.push_str("/");
}
- url.push_str(item_path(it).as_slice());
- try!(layout::redirect(&mut writer, url.as_slice()));
+ url.push_str(&item_path(it));
+ try!(layout::redirect(&mut writer, &url));
}
None => {}
}
_ => false,
};
if !is_primitive {
- let cur = self.cx.current.as_slice();
+ let cur = &self.cx.current;
let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
repeat("../").take(cur.len() - i - 1)
.collect::<String>(),
- component.as_slice()));
+ component));
}
}
try!(write!(fmt, "<a class='{}' href=''>{}</a>",
- shortty(self.item), self.item.name.as_ref().unwrap().as_slice()));
+ shortty(self.item), self.item.name.as_ref().unwrap()));
// Write stability level
try!(write!(fmt, "<wbr>{}", Stability(&self.item.stability)));
match self.item.inner {
clean::ModuleItem(ref m) => {
- item_module(fmt, self.cx, self.item, m.items.as_slice())
+ item_module(fmt, self.cx, self.item, &m.items)
}
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
item_function(fmt, self.item, f),
fn full_path(cx: &Context, item: &clean::Item) -> String {
let mut s = cx.current.connect("::");
s.push_str("::");
- s.push_str(item.name.as_ref().unwrap().as_slice());
+ s.push_str(item.name.as_ref().unwrap());
return s
}
Some(ref src) => {
try!(write!(w, "<tr><td><code>{}extern crate \"{}\" as {};",
VisSpace(myitem.visibility),
- src.as_slice(),
- name.as_slice()))
+ src,
+ name))
}
None => {
try!(write!(w, "<tr><td><code>{}extern crate {};",
- VisSpace(myitem.visibility), name.as_slice()))
+ VisSpace(myitem.visibility), name))
}
}
try!(write!(w, "</code></td></tr>"));
let Initializer(s) = *self;
if s.len() == 0 { return Ok(()); }
try!(write!(f, "<code> = </code>"));
- write!(f, "<code>{}</code>", s.as_slice())
+ write!(f, "<code>{}</code>", s)
}
}
try!(write!(w, "<pre class='rust const'>{vis}const \
{name}: {typ}{init}</pre>",
vis = VisSpace(it.visibility),
- name = it.name.as_ref().unwrap().as_slice(),
+ name = it.name.as_ref().unwrap(),
typ = c.type_,
- init = Initializer(c.expr.as_slice())));
+ init = Initializer(&c.expr)));
document(w, it)
}
{name}: {typ}{init}</pre>",
vis = VisSpace(it.visibility),
mutability = MutableSpace(s.mutability),
- name = it.name.as_ref().unwrap().as_slice(),
+ name = it.name.as_ref().unwrap(),
typ = s.type_,
- init = Initializer(s.expr.as_slice())));
+ init = Initializer(&s.expr)));
document(w, it)
}
{name}{generics}{decl}{where_clause}</pre>",
vis = VisSpace(it.visibility),
unsafety = UnsafetySpace(f.unsafety),
- name = it.name.as_ref().unwrap().as_slice(),
+ name = it.name.as_ref().unwrap(),
generics = f.generics,
where_clause = WhereClause(&f.generics),
decl = f.decl));
bounds.push_str(": ");
for (i, p) in t.bounds.iter().enumerate() {
if i > 0 { bounds.push_str(" + "); }
- bounds.push_str(format!("{}", *p).as_slice());
+ bounds.push_str(&format!("{}", *p));
}
}
try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
VisSpace(it.visibility),
UnsafetySpace(t.unsafety),
- it.name.as_ref().unwrap().as_slice(),
+ it.name.as_ref().unwrap(),
t.generics,
bounds,
WhereClause(&t.generics)));
_ => "",
},
ty = shortty(it),
- name = it.name.as_ref().unwrap().as_slice(),
+ name = it.name.as_ref().unwrap(),
generics = *g,
decl = Method(selfty, d),
where_clause = WhereClause(g))
it,
Some(&s.generics),
s.struct_type,
- s.fields.as_slice(),
+ &s.fields,
"",
true));
try!(write!(w, "</pre>"));
try!(write!(w, "<tr><td id='structfield.{name}'>\
{stab}<code>{name}</code></td><td>",
stab = ConciseStability(&field.stability),
- name = field.name.as_ref().unwrap().as_slice()));
+ name = field.name.as_ref().unwrap()));
try!(document(w, field));
try!(write!(w, "</td></tr>"));
}
e: &clean::Enum) -> fmt::Result {
try!(write!(w, "<pre class='rust enum'>{}enum {}{}{}",
VisSpace(it.visibility),
- it.name.as_ref().unwrap().as_slice(),
+ it.name.as_ref().unwrap(),
e.generics,
WhereClause(&e.generics)));
if e.variants.len() == 0 && !e.variants_stripped {
try!(write!(w, " {{\n"));
for v in &e.variants {
try!(write!(w, " "));
- let name = v.name.as_ref().unwrap().as_slice();
+ let name = v.name.as_ref().unwrap();
match v.inner {
clean::VariantItem(ref var) => {
match var.kind {
v,
None,
s.struct_type,
- s.fields.as_slice(),
+ &s.fields,
" ",
false));
}
for variant in &e.variants {
try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>",
stab = ConciseStability(&variant.stability),
- name = variant.name.as_ref().unwrap().as_slice()));
+ name = variant.name.as_ref().unwrap()));
try!(document(w, variant));
match variant.inner {
clean::VariantItem(ref var) => {
try!(write!(w, "<tr><td \
id='variant.{v}.field.{f}'>\
<code>{f}</code></td><td>",
- v = variant.name.as_ref().unwrap().as_slice(),
- f = field.name.as_ref().unwrap().as_slice()));
+ v = variant.name.as_ref().unwrap(),
+ f = field.name.as_ref().unwrap()));
try!(document(w, field));
try!(write!(w, "</td></tr>"));
}
try!(write!(w, "{}{}{}",
VisSpace(it.visibility),
if structhead {"struct "} else {""},
- it.name.as_ref().unwrap().as_slice()));
+ it.name.as_ref().unwrap()));
match g {
Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
None => {}
clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
try!(write!(w, " {}{}: {},\n{}",
VisSpace(field.visibility),
- field.name.as_ref().unwrap().as_slice(),
+ field.name.as_ref().unwrap(),
*ty,
tab));
}
match i.dox {
Some(ref dox) => {
try!(write!(w, "<div class='docblock'>{}</div>",
- Markdown(dox.as_slice())));
+ Markdown(dox)));
}
None => {}
}
fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item,
t: &clean::Typedef) -> fmt::Result {
try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
- it.name.as_ref().unwrap().as_slice(),
+ it.name.as_ref().unwrap(),
t.generics,
t.type_));
fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
cur: &clean::Item, cx: &Context) -> fmt::Result {
let items = match cx.sidebar.get(short) {
- Some(items) => items.as_slice(),
+ Some(items) => items,
None => return Ok(())
};
try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
class = class,
href = if curty == "mod" {"../"} else {""},
path = if short == "mod" {
- format!("{}/index.html", name.as_slice())
+ format!("{}/index.html", name)
} else {
- format!("{}.{}.html", short, name.as_slice())
+ format!("{}.{}.html", short, name)
},
- title = Escape(doc.as_ref().unwrap().as_slice()),
- name = name.as_slice()));
+ title = Escape(doc.as_ref().unwrap()),
+ name = name));
}
try!(write!(w, "</div>"));
Ok(())
try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
}
try!(write!(fmt, "</pre>"));
- try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None, None)));
+ try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
Ok(())
}
}
fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
t: &clean::Macro) -> fmt::Result {
- try!(w.write_str(highlight::highlight(t.source.as_slice(),
+ try!(w.write_str(&highlight::highlight(&t.source,
Some("macro"),
- None).as_slice()));
+ None)));
document(w, it)
}
(0, &self.top_level)
}
Some(entry) => {
- sec_number = String::from_str(entry.sec_number
- .as_slice());
+ sec_number = String::from_str(&entry.sec_number);
sec_number.push_str(".");
(entry.level, &entry.children)
}
sec_number.push_str("0.");
}
let number = toc.count_entries_with_level(level);
- sec_number.push_str(format!("{}", number + 1).as_slice())
+ sec_number.push_str(&format!("{}", number + 1))
}
self.chain.push(TocEntry {
// get the thing we just pushed, so we can borrow the string
// out of it with the right lifetime
let just_inserted = self.chain.last_mut().unwrap();
- just_inserted.sec_number.as_slice()
+ &just_inserted.sec_number
}
}
pub fn usage(argv0: &str) {
println!("{}",
- getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
- opts().as_slice()));
+ getopts::usage(&format!("{} [options] <input>", argv0),
+ &opts()));
}
pub fn main_args(args: &[String]) -> int {
- let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
+ let matches = match getopts::getopts(args.tail(), &opts()) {
Ok(m) => m,
Err(err) => {
println!("{}", err);
}
};
if matches.opt_present("h") || matches.opt_present("help") {
- usage(args[0].as_slice());
+ usage(&args[0]);
return 0;
} else if matches.opt_present("version") {
rustc_driver::version("rustdoc", &matches);
println!("only one input file may be specified");
return 1;
}
- let input = matches.free[0].as_slice();
+ let input = &matches.free[0];
let mut libs = SearchPaths::new();
for s in &matches.opt_strs("L") {
- libs.add_path(s.as_slice());
+ libs.add_path(s);
}
let externs = match parse_externs(&matches) {
Ok(ex) => ex,
let cfgs = matches.opt_strs("cfg");
let external_html = match ExternalHtml::load(
- matches.opt_strs("html-in-header").as_slice(),
- matches.opt_strs("html-before-content").as_slice(),
- matches.opt_strs("html-after-content").as_slice()) {
+ &matches.opt_strs("html-in-header"),
+ &matches.opt_strs("html-before-content"),
+ &matches.opt_strs("html-after-content")) {
Some(eh) => eh,
None => return 3
};
};
let Output { krate, json_plugins, passes, } = out;
info!("going to format");
- match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
+ match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => {
match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
passes.into_iter().collect()) {
fn acquire_input(input: &str,
externs: core::Externs,
matches: &getopts::Matches) -> Result<Output, String> {
- match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
+ match matches.opt_str("r").as_ref().map(|s| &**s) {
Some("rust") => Ok(rust_input(input, externs, matches)),
Some("json") => json_input(input),
Some(s) => Err(format!("unknown input format: {}", s)),
// First, parse the crate and extract all relevant information.
let mut paths = SearchPaths::new();
for s in &matches.opt_strs("L") {
- paths.add_path(s.as_slice());
+ paths.add_path(s);
}
let cfgs = matches.opt_strs("cfg");
let triple = matches.opt_str("target");
let cr = Path::new(cratefile);
info!("starting to run rustc");
- let (mut krate, analysis) = std::thread::Thread::scoped(move |:| {
+ let (mut krate, analysis) = std::thread::Thread::scoped(move || {
use rustc::session::config::Input;
let cr = cr;
// FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
// straight to the Rust JSON representation.
let crate_json_str = format!("{}", json::as_json(&krate));
- let crate_json = match json::from_str(crate_json_str.as_slice()) {
+ let crate_json = match json::from_str(&crate_json_str) {
Ok(j) => j,
Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
};
let mut css = String::new();
for name in &matches.opt_strs("markdown-css") {
let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
- css.push_str(s.as_slice())
+ css.push_str(&s)
}
let input_str = load_or_return!(input, 1, 2);
Ok(f) => f
};
- let (metadata, text) = extract_leading_metadata(input_str.as_slice());
+ let (metadata, text) = extract_leading_metadata(&input_str);
if metadata.len() == 0 {
let _ = writeln!(&mut old_io::stderr(),
"invalid markdown file: expecting initial line with `% ...TITLE...`");
return 5;
}
- let title = metadata[0].as_slice();
+ let title = metadata[0];
reset_headers();
let input_str = load_or_return!(input, 1, 2);
let mut collector = Collector::new(input.to_string(), libs, externs, true);
- find_testable_code(input_str.as_slice(), &mut collector);
+ find_testable_code(&input_str, &mut collector);
test_args.insert(0, "rustdoctest".to_string());
- testing::test_main(test_args.as_slice(), collector.tests);
+ testing::test_main(&test_args, collector.tests);
0
}
&clean::NameValue(ref x, ref s)
if "doc" == *x => {
avec.push(clean::NameValue("doc".to_string(),
- unindent(s.as_slice())))
+ unindent(s)))
}
x => avec.push(x.clone())
}
match *attr {
clean::NameValue(ref x, ref s)
if "doc" == *x => {
- docstr.push_str(s.as_slice());
+ docstr.push_str(s);
docstr.push('\n');
},
_ => ()
if lines.len() >= 1 {
let mut unindented = vec![ lines[0].trim().to_string() ];
- unindented.push_all(lines.tail().iter().map(|&line| {
+ unindented.push_all(&lines.tail().iter().map(|&line| {
if line.chars().all(|c| c.is_whitespace()) {
line.to_string()
} else {
assert!(line.len() >= min_indent);
line[min_indent..].to_string()
}
- }).collect::<Vec<_>>().as_slice());
+ }).collect::<Vec<_>>());
unindented.connect("\n")
} else {
s.to_string()
#[test]
fn should_unindent() {
let s = " line1\n line2".to_string();
- let r = unindent(s.as_slice());
+ let r = unindent(&s);
assert_eq!(r, "line1\nline2");
}
#[test]
fn should_unindent_multiple_paragraphs() {
let s = " line1\n\n line2".to_string();
- let r = unindent(s.as_slice());
+ let r = unindent(&s);
assert_eq!(r, "line1\n\nline2");
}
// Line 2 is indented another level beyond the
// base indentation and should be preserved
let s = " line1\n\n line2".to_string();
- let r = unindent(s.as_slice());
+ let r = unindent(&s);
assert_eq!(r, "line1\n\n line2");
}
// #[doc = "Start way over here
// and continue here"]
let s = "line1\n line2".to_string();
- let r = unindent(s.as_slice());
+ let r = unindent(&s);
assert_eq!(r, "line1\nline2");
}
#[test]
fn should_not_ignore_first_line_indent_in_a_single_line_para() {
let s = "line1\n\n line2".to_string();
- let r = unindent(s.as_slice());
+ let r = unindent(&s);
assert_eq!(r, "line1\n\n line2");
}
}
#[cfg(all(not(target_os="windows"), not(target_os="macos")))]
fn libname(n: String) -> String {
let mut i = String::from_str("lib");
- i.push_str(n.as_slice());
+ i.push_str(&n);
i.push_str(".so");
i
}
let mut cfg = config::build_configuration(&sess);
cfg.extend(cfgs.into_iter().map(|cfg_| {
- let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
+ let cfg_ = token::intern_and_get_ident(&cfg_);
P(dummy_spanned(ast::MetaWord(cfg_)))
}));
let krate = driver::phase_1_parse_input(&sess, cfg, &input);
test_args.insert(0, "rustdoctest".to_string());
- testing::test_main(test_args.as_slice(),
+ testing::test_main(&test_args,
collector.tests.into_iter().collect());
0
}
let w1 = old_io::ChanWriter::new(tx);
let w2 = w1.clone();
let old = old_io::stdio::set_stderr(box w1);
- Thread::spawn(move |:| {
+ Thread::spawn(move || {
let mut p = old_io::ChanReader::new(rx);
let mut err = match old {
Some(old) => {
let newpath = {
let mut path = DynamicLibrary::search_path();
path.insert(0, libdir.clone());
- DynamicLibrary::create_path(path.as_slice())
+ DynamicLibrary::create_path(&path)
};
- cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
+ cmd.env(DynamicLibrary::envvar(), newpath);
match cmd.output() {
Err(e) => panic!("couldn't run the test: {}{}", e,
panic!("test executable succeeded when it should have failed");
} else if !should_fail && !out.status.success() {
panic!("test executable failed:\n{:?}",
- str::from_utf8(out.error.as_slice()));
+ str::from_utf8(&out.error));
}
}
}
match cratename {
Some(cratename) => {
if s.contains(cratename) {
- prog.push_str(format!("extern crate {};\n",
- cratename).as_slice());
+ prog.push_str(&format!("extern crate {};\n",
+ cratename));
}
}
None => {}
prog.push_str(s);
} else {
prog.push_str("fn main() {\n ");
- prog.push_str(s.replace("\n", "\n ").as_slice());
+ prog.push_str(&s.replace("\n", "\n "));
prog.push_str("\n}");
}
pub fn add_test(&mut self, test: String,
should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
let name = if self.use_headers {
- let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
+ let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
format!("{}_{}", s, self.cnt)
} else {
format!("{}_{}", self.names.connect("::"), self.cnt)
should_fail: testing::ShouldFail::No, // compiler failures are test failures
},
testfn: testing::DynTestFn(Thunk::new(move|| {
- runtest(test.as_slice(),
- cratename.as_slice(),
+ runtest(&test,
+ &cratename,
libs,
externs,
should_fail,
Ok(c) => c,
Err(e) => return Err(io_error_to_error(e))
};
- let s = match str::from_utf8(contents.as_slice()).ok() {
+ let s = match str::from_utf8(&contents).ok() {
Some(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0))
};
map.insert(Enum::Foo, 0);
let result = json::encode(&map).unwrap();
assert_eq!(&result[], r#"{"Foo":0}"#);
- let decoded: HashMap<Enum, _> = json::decode(result.as_slice()).unwrap();
+ let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
assert_eq!(map, decoded);
}
None => { break; }
};
let (ref expected_evt, ref expected_stack) = expected[i];
- if !parser.stack().is_equal_to(expected_stack.as_slice()) {
+ if !parser.stack().is_equal_to(expected_stack) {
panic!("Parser stack is not equal to {:?}", expected_stack);
}
assert_eq!(&evt, expected_evt);
#[bench]
fn bench_large(b: &mut Bencher) {
let src = big_json();
- b.iter( || { let _ = from_str(src.as_slice()); });
+ b.iter( || { let _ = from_str(&src); });
}
}
let lower = if 'A' as u32 <= c && c <= 'Z' as u32 { c + 'a' as u32 - 'A' as u32 }
else { c };
assert!((from_u32(i).unwrap()).to_string().eq_ignore_ascii_case(
- (from_u32(lower).unwrap()).to_string().as_slice()));
+ &from_u32(lower).unwrap().to_string()));
i += 1;
}
}
pub fn prepend_search_path(path: &Path) {
let mut search_path = DynamicLibrary::search_path();
search_path.insert(0, path.clone());
- let newval = DynamicLibrary::create_path(search_path.as_slice());
+ let newval = DynamicLibrary::create_path(&search_path);
env::set_var(DynamicLibrary::envvar(),
- str::from_utf8(newval.as_slice()).unwrap());
+ str::from_utf8(&newval).unwrap());
}
/// From a slice of paths, create a new vector which is suitable to be an
use libc;
use mem;
use ops::Deref;
-use slice::{self, SliceExt, AsSlice};
+use slice::{self, SliceExt};
use string::String;
use vec::Vec;
/// Create a view into this C string which includes the trailing nul
/// terminator at the end of the string.
- pub fn as_slice_with_nul(&self) -> &[libc::c_char] { self.inner.as_slice() }
+ pub fn as_slice_with_nul(&self) -> &[libc::c_char] { &self.inner }
/// Similar to the `as_slice` method, but returns a `u8` slice instead of a
/// `libc::c_char` slice.
pub fn as_bytes(&self) -> &[u8] {
- unsafe { mem::transmute(self.as_slice()) }
+ unsafe { mem::transmute(&**self) }
}
/// Equivalent to `as_slice_with_nul` except that the type returned is a
assert_eq!(s.as_bytes(), b"1234");
assert_eq!(s.as_bytes_with_nul(), b"1234\0");
unsafe {
- assert_eq!(s.as_slice(),
+ assert_eq!(&*s,
mem::transmute::<_, &[libc::c_char]>(b"1234"));
assert_eq!(s.as_slice_with_nul(),
mem::transmute::<_, &[libc::c_char]>(b"1234\0"));
// cut off the one extra digit, and depending on its value
// round the remaining ones.
if limit_digits && dig == digit_count {
- let ascii2value = |&: chr: u8| {
+ let ascii2value = |chr: u8| {
(chr as char).to_digit(radix).unwrap()
};
- let value2ascii = |&: val: uint| {
+ let value2ascii = |val: uint| {
char::from_digit(val, radix).unwrap() as u8
};
impl<R: Reader> Buffer for BufferedReader<R> {
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
if self.pos == self.cap {
- self.cap = try!(self.inner.read(self.buf.as_mut_slice()));
+ self.cap = try!(self.inner.read(&mut self.buf));
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
let a: &[u8] = &[7,8,6];
assert_eq!(a, buf);
- match reader.read(buf.as_mut_slice()) {
+ match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
assert_eq!(a, buf);
// Ensure it continues to panic in the same way.
- match reader.read(buf.as_mut_slice()) {
+ match reader.read(&mut buf) {
Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
}
use option::Option::{Some, None};
use ptr::PtrExt;
use result::Result::{Ok, Err};
-use slice::{SliceExt, AsSlice};
+use slice::SliceExt;
/// An iterator that reads a single byte on each iteration,
/// until `.read_byte()` returns `EndOfFile`.
n >>= 8;
i -= 1u;
}
- f(bytes.as_slice())
+ f(&bytes)
}
}
}
bytes.push((n >> shift) as u8);
i -= 1u;
}
- f(bytes.as_slice())
+ f(&bytes)
}
}
}
let buf = vec![0x41, 0x02, 0x00, 0x00];
let mut writer = Vec::new();
- writer.write(buf.as_slice()).unwrap();
+ writer.write(&buf).unwrap();
let mut reader = MemReader::new(writer);
let f = reader.read_be_f32().unwrap();
$b.iter(|| {
let mut i = $start_index;
while i < data.len() {
- sum += u64_from_be_bytes(data.as_slice(), i, $size);
+ sum += u64_from_be_bytes(&data, i, $size);
i += $stride;
}
});
macro_rules! error { ($e:expr, $s:expr) => (
match $e {
Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
- Err(ref err) => assert!(err.to_string().contains($s.as_slice()),
+ Err(ref err) => assert!(err.to_string().contains($s),
format!("`{}` did not contain `{}`", err, $s))
}
) }
-1|0 => panic!("shouldn't happen"),
n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
};
- assert_eq!(read_str.as_slice(), message);
+ assert_eq!(read_str, message);
}
check!(unlink(filename));
}
if cfg!(unix) {
error!(result, "no such file or directory");
}
- error!(result, format!("path={}; mode=open; access=read", filename.display()));
+ error!(result, &format!("path={}; mode=open; access=read", filename.display()));
}
#[test]
if cfg!(unix) {
error!(result, "no such file or directory");
}
- error!(result, format!("path={}", filename.display()));
+ error!(result, &format!("path={}", filename.display()));
}
#[test]
None|Some("") => panic!("really shouldn't happen.."),
Some(n) => format!("{}{}", prefix, n),
};
- assert_eq!(expected.as_slice(), read_str);
+ assert_eq!(expected, read_str);
}
check!(unlink(f));
}
error!(result, "couldn't recursively mkdir");
error!(result, "couldn't create directory");
error!(result, "mode=0700");
- error!(result, format!("path={}", file.display()));
+ error!(result, &format!("path={}", file.display()));
}
#[test]
let to = Path::new("test/other-bogus-path");
error!(copy(&from, &to),
- format!("couldn't copy path (the source path is not an \
- existing file; from={:?}; to={:?})",
- from.display(), to.display()));
+ &format!("couldn't copy path (the source path is not an \
+ existing file; from={:?}; to={:?})",
+ from.display(), to.display()));
match copy(&from, &to) {
Ok(..) => panic!(),
check!(File::create(&input).write(b"hello"));
check!(copy(&input, &out));
let contents = check!(File::open(&out).read_to_end());
- assert_eq!(contents.as_slice(), b"hello");
+ assert_eq!(contents, b"hello");
assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
}
use result::Result::{Err, Ok};
use old_io;
use old_io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
-use slice::{self, AsSlice, SliceExt};
+use slice::{self, SliceExt};
use vec::Vec;
const BUF_CAPACITY: uint = 128;
/// Acquires an immutable reference to the underlying buffer of this
/// `MemWriter`.
#[inline]
- pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+ pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
/// Unwraps this `MemWriter`, returning the underlying buffer
#[inline]
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemReader`.
#[inline]
- pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+ pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
/// Unwraps this `MemReader`, returning the underlying buffer
#[inline]
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
- assert_eq!(writer.as_slice(), b);
+ assert_eq!(writer, b);
}
#[test]
#[test]
fn test_slice_reader() {
let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
- let mut reader = &mut in_buf.as_slice();
+ let mut reader = &mut &*in_buf;
let mut buf = [];
assert_eq!(reader.read(&mut buf), Ok(0));
let mut buf = [0];
assert_eq!(reader.read(&mut buf), Ok(1));
assert_eq!(reader.len(), 7);
let b: &[_] = &[0];
- assert_eq!(buf.as_slice(), b);
+ assert_eq!(buf, b);
let mut buf = [0; 4];
assert_eq!(reader.read(&mut buf), Ok(4));
assert_eq!(reader.len(), 3);
let b: &[_] = &[1, 2, 3, 4];
- assert_eq!(buf.as_slice(), b);
+ assert_eq!(buf, b);
assert_eq!(reader.read(&mut buf), Ok(3));
let b: &[_] = &[5, 6, 7];
assert_eq!(&buf[..3], b);
assert!(reader.read(&mut buf).is_err());
- let mut reader = &mut in_buf.as_slice();
+ let mut reader = &mut &*in_buf;
assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
assert_eq!(reader.read_until(3).unwrap(), vec!(4, 5, 6, 7));
assert!(reader.read(&mut buf).is_err());
#[test]
fn test_buf_reader() {
let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
- let mut reader = BufReader::new(in_buf.as_slice());
+ let mut reader = BufReader::new(&in_buf);
let mut buf = [];
assert_eq!(reader.read(&mut buf), Ok(0));
assert_eq!(reader.tell(), Ok(0));
let b: &[_] = &[5, 6, 7];
assert_eq!(&buf[..3], b);
assert!(reader.read(&mut buf).is_err());
- let mut reader = BufReader::new(in_buf.as_slice());
+ let mut reader = BufReader::new(&in_buf);
assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
assert_eq!(reader.read_until(3).unwrap(), vec!(4, 5, 6, 7));
assert!(reader.read(&mut buf).is_err());
b.iter(|| {
let mut wr = MemWriter::new();
for _ in 0..times {
- wr.write(src.as_slice()).unwrap();
+ wr.write(&src).unwrap();
}
let v = wr.into_inner();
for _i in 0u..10 {
let mut buf = [0 as u8; 10];
rdr.read(&mut buf).unwrap();
- assert_eq!(buf.as_slice(), [5; 10].as_slice());
+ assert_eq!(buf, [5; 10]);
}
}
});
#[inline]
fn write_char(&mut self, c: char) -> IoResult<()> {
let mut buf = [0u8; 4];
- let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
+ let n = c.encode_utf8(&mut buf).unwrap_or(0);
self.write_all(&buf[..n])
}
// fall back on good
return r.read(buf);
}
- match behavior.as_mut_slice()[0] {
+ match (&mut **behavior)[0] {
GoodBehavior(0) => (),
GoodBehavior(ref mut x) => {
*x -= 1;
}
fn read_ip_addr(&mut self) -> Option<IpAddr> {
- let ipv4_addr = |&mut: p: &mut Parser| p.read_ipv4_addr();
- let ipv6_addr = |&mut: p: &mut Parser| p.read_ipv6_addr();
+ let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr();
+ let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr();
self.read_or(&mut [box ipv4_addr, box ipv6_addr])
}
fn read_socket_addr(&mut self) -> Option<SocketAddr> {
- let ip_addr = |&: p: &mut Parser| {
- let ipv4_p = |&mut: p: &mut Parser| p.read_ip_addr();
- let ipv6_p = |&mut: p: &mut Parser| {
- let open_br = |&: p: &mut Parser| p.read_given_char('[');
- let ip_addr = |&: p: &mut Parser| p.read_ipv6_addr();
- let clos_br = |&: p: &mut Parser| p.read_given_char(']');
+ let ip_addr = |p: &mut Parser| {
+ let ipv4_p = |p: &mut Parser| p.read_ip_addr();
+ let ipv6_p = |p: &mut Parser| {
+ let open_br = |p: &mut Parser| p.read_given_char('[');
+ let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
+ let clos_br = |p: &mut Parser| p.read_given_char(']');
p.read_seq_3::<char, IpAddr, char, _, _, _>(open_br, ip_addr, clos_br)
.map(|t| match t { (_, ip, _) => ip })
};
p.read_or(&mut [box ipv4_p, box ipv6_p])
};
- let colon = |&: p: &mut Parser| p.read_given_char(':');
- let port = |&: p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
+ let colon = |p: &mut Parser| p.read_given_char(':');
+ let port = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
// host, colon, port
self.read_seq_3::<IpAddr, char, u16, _, _, _>(ip_addr, colon, port)
// if the env is currently just inheriting from the parent's,
// materialize the parent's env into a hashtable.
self.env = Some(os::env_as_bytes().into_iter().map(|(k, v)| {
- (EnvKey(CString::from_slice(k.as_slice())),
- CString::from_slice(v.as_slice()))
+ (EnvKey(CString::from_slice(&k)),
+ CString::from_slice(&v))
}).collect());
self.env.as_mut().unwrap()
}
&self.program
}
fn args(&self) -> &[CString] {
- self.args.as_slice()
+ &self.args
}
fn env(&self) -> Option<&EnvMap> {
self.env.as_ref()
let (tx, rx) = channel();
match stream {
Some(stream) => {
- Thread::spawn(move |:| {
+ Thread::spawn(move || {
let mut stream = stream;
tx.send(stream.read_to_end()).unwrap();
});
fn test_process_output_output() {
let ProcessOutput {status, output, error}
= Command::new("echo").arg("hello").output().unwrap();
- let output_str = str::from_utf8(output.as_slice()).unwrap();
+ let output_str = str::from_utf8(&output).unwrap();
assert!(status.success());
assert_eq!(output_str.trim().to_string(), "hello");
fn test_wait_with_output_once() {
let prog = Command::new("echo").arg("hello").spawn().unwrap();
let ProcessOutput {status, output, error} = prog.wait_with_output().unwrap();
- let output_str = str::from_utf8(output.as_slice()).unwrap();
+ let output_str = str::from_utf8(&output).unwrap();
assert!(status.success());
assert_eq!(output_str.trim().to_string(), "hello");
for &(ref k, ref v) in &r {
// don't check windows magical empty-named variables
assert!(k.is_empty() ||
- output.contains(format!("{}={}", *k, *v).as_slice()),
+ output.contains(&format!("{}={}", *k, *v)),
"output doesn't contain `{}={}`\n{}",
k, v, output);
}
for &(ref k, ref v) in &r {
// don't check android RANDOM variables
if *k != "RANDOM".to_string() {
- assert!(output.contains(format!("{}={}",
- *k,
- *v).as_slice()) ||
- output.contains(format!("{}=\'{}\'",
- *k,
- *v).as_slice()));
+ assert!(output.contains(&format!("{}={}",
+ *k,
+ *v)) ||
+ output.contains(&format!("{}=\'{}\'",
+ *k,
+ *v)));
}
}
}
None => {}
Some(val) => {
path_val = val;
- new_env.push(("PATH", path_val.as_slice()))
+ new_env.push(("PATH", &path_val))
}
}
- let prog = env_cmd().env_set_all(new_env.as_slice()).spawn().unwrap();
+ let prog = env_cmd().env_set_all(&new_env).spawn().unwrap();
let result = prog.wait_with_output().unwrap();
- let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
+ let output = String::from_utf8_lossy(&result.output).to_string();
assert!(output.contains("RUN_TEST_NEW_ENV=123"),
"didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
fn test_add_to_env() {
let prog = env_cmd().env("RUN_TEST_NEW_ENV", "123").spawn().unwrap();
let result = prog.wait_with_output().unwrap();
- let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
+ let output = String::from_utf8_lossy(&result.output).to_string();
assert!(output.contains("RUN_TEST_NEW_ENV=123"),
"didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
let mut buf = [0, 0];
reader.read(&mut buf).unwrap();
let b: &[_] = &[0, 1];
- assert_eq!(buf.as_slice(), b);
+ assert_eq!(buf, b);
}
#[test]
impl Buffer for ZeroReader {
fn fill_buf<'a>(&'a mut self) -> old_io::IoResult<&'a [u8]> {
static DATA: [u8; 64] = [0; 64];
- Ok(DATA.as_slice())
+ Ok(&DATA)
}
fn consume(&mut self, _amt: uint) {}
fn test_null_writer() {
let mut s = NullWriter;
let buf = vec![0, 0, 0];
- s.write_all(buf.as_slice()).unwrap();
+ s.write_all(&buf).unwrap();
s.flush().unwrap();
}
fn test_zero_reader() {
let mut s = ZeroReader;
let mut buf = vec![1, 2, 3];
- assert_eq!(s.read(buf.as_mut_slice()), Ok(3));
+ assert_eq!(s.read(&mut buf), Ok(3));
assert_eq!(vec![0, 0, 0], buf);
}
fn test_null_reader() {
let mut r = NullReader;
let mut buf = vec![0];
- assert!(r.read(buf.as_mut_slice()).is_err());
+ assert!(r.read(&mut buf).is_err());
}
#[test]
v.push(SEP_BYTE);
v.push_all(filename);
// FIXME: this is slow
- self.repr = Path::normalize(v.as_slice());
+ self.repr = Path::normalize(&v);
}
None => {
self.repr = Path::normalize(filename);
}
Some(idx) if &self.repr[idx+1..] == b".." => {
let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
- v.push_all(self.repr.as_slice());
+ v.push_all(&self.repr);
v.push(SEP_BYTE);
v.push_all(filename);
// FIXME: this is slow
- self.repr = Path::normalize(v.as_slice());
+ self.repr = Path::normalize(&v);
}
Some(idx) => {
let mut v = Vec::with_capacity(idx + 1 + filename.len());
v.push_all(&self.repr[..idx+1]);
v.push_all(filename);
// FIXME: this is slow
- self.repr = Path::normalize(v.as_slice());
+ self.repr = Path::normalize(&v);
}
}
self.sepidx = self.repr.rposition_elem(&SEP_BYTE);
self.repr = Path::normalize(path);
} else {
let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
- v.push_all(self.repr.as_slice());
+ v.push_all(&self.repr);
v.push(SEP_BYTE);
v.push_all(path);
// FIXME: this is slow
- self.repr = Path::normalize(v.as_slice());
+ self.repr = Path::normalize(&v);
}
self.sepidx = self.repr.rposition_elem(&SEP_BYTE);
}
impl GenericPath for Path {
#[inline]
fn as_vec<'a>(&'a self) -> &'a [u8] {
- self.repr.as_slice()
+ &self.repr
}
fn into_vec(self) -> Vec<u8> {
fn dirname<'a>(&'a self) -> &'a [u8] {
match self.sepidx {
- None if b".." == self.repr => self.repr.as_slice(),
+ None if b".." == self.repr => &self.repr,
None => dot_static,
Some(0) => &self.repr[..1],
- Some(idx) if &self.repr[idx+1..] == b".." => self.repr.as_slice(),
+ Some(idx) if &self.repr[idx+1..] == b".." => &self.repr,
Some(idx) => &self.repr[..idx]
}
}
match self.sepidx {
None if b"." == self.repr ||
b".." == self.repr => None,
- None => Some(self.repr.as_slice()),
+ None => Some(&self.repr),
Some(idx) if &self.repr[idx+1..] == b".." => None,
Some(0) if self.repr[1..].is_empty() => None,
Some(idx) => Some(&self.repr[idx+1..])
pub fn components<'a>(&'a self) -> Components<'a> {
let v = if self.repr[0] == SEP_BYTE {
&self.repr[1..]
- } else { self.repr.as_slice() };
+ } else { &*self.repr };
let is_sep_byte: fn(&u8) -> bool = is_sep_byte; // coerce to fn ptr
let mut ret = v.split(is_sep_byte);
if v.is_empty() {
{
let path = Path::new($path);
let mo = path.display().as_cow();
- assert_eq!(mo.as_slice(), $exp);
+ assert_eq!(mo, $exp);
}
);
($path:expr, $exp:expr, filename) => (
{
let path = Path::new($path);
let mo = path.filename_display().as_cow();
- assert_eq!(mo.as_slice(), $exp);
+ assert_eq!(mo, $exp);
}
)
}
let path = Path::new("foo");
let mo = path.display().as_cow();
- assert_eq!(mo.as_slice(), "foo");
+ assert_eq!(mo, "foo");
let path = Path::new(b"\\");
let mo = path.filename_display().as_cow();
- assert_eq!(mo.as_slice(), "");
+ assert_eq!(mo, "");
}
#[test]
fn real_args() -> Vec<String> {
real_args_as_bytes().into_iter()
.map(|v| {
- String::from_utf8_lossy(v.as_slice()).into_owned()
+ String::from_utf8_lossy(&v).into_owned()
}).collect()
}
let mut rng = rand::thread_rng();
let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
.collect::<String>());
- assert!(getenv(n.as_slice()).is_none());
+ assert!(getenv(&n).is_none());
n
}
#[test]
fn test_setenv() {
let n = make_rand_name();
- setenv(n.as_slice(), "VALUE");
- assert_eq!(getenv(n.as_slice()), Some("VALUE".to_string()));
+ setenv(&n, "VALUE");
+ assert_eq!(getenv(&n), Some("VALUE".to_string()));
}
#[test]
fn test_unsetenv() {
let n = make_rand_name();
- setenv(n.as_slice(), "VALUE");
- unsetenv(n.as_slice());
- assert_eq!(getenv(n.as_slice()), None);
+ setenv(&n, "VALUE");
+ unsetenv(&n);
+ assert_eq!(getenv(&n), None);
}
#[test]
#[ignore]
fn test_setenv_overwrite() {
let n = make_rand_name();
- setenv(n.as_slice(), "1");
- setenv(n.as_slice(), "2");
- assert_eq!(getenv(n.as_slice()), Some("2".to_string()));
- setenv(n.as_slice(), "");
- assert_eq!(getenv(n.as_slice()), Some("".to_string()));
+ setenv(&n, "1");
+ setenv(&n, "2");
+ assert_eq!(getenv(&n), Some("2".to_string()));
+ setenv(&n, "");
+ assert_eq!(getenv(&n), Some("".to_string()));
}
// Windows GetEnvironmentVariable requires some extra work to make sure
i += 1;
}
let n = make_rand_name();
- setenv(n.as_slice(), s.as_slice());
+ setenv(&n, &s);
debug!("{}", s.clone());
- assert_eq!(getenv(n.as_slice()), Some(s));
+ assert_eq!(getenv(&n), Some(s));
}
#[test]
for p in &e {
let (n, v) = (*p).clone();
debug!("{}", n);
- let v2 = getenv(n.as_slice());
+ let v2 = getenv(&n);
// MingW seems to set some funky environment variables like
// "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
// from env() but not visible from getenv().
fn test_env_set_get_huge() {
let n = make_rand_name();
let s = repeat("x").take(10000).collect::<String>();
- setenv(n.as_slice(), s.as_slice());
- assert_eq!(getenv(n.as_slice()), Some(s));
- unsetenv(n.as_slice());
- assert_eq!(getenv(n.as_slice()), None);
+ setenv(&n, &s);
+ assert_eq!(getenv(&n), Some(s));
+ unsetenv(&n);
+ assert_eq!(getenv(&n), None);
}
#[test]
let n = make_rand_name();
let mut e = env();
- setenv(n.as_slice(), "VALUE");
+ setenv(&n, "VALUE");
assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
e = env();
assert!(os::homedir().is_none());
if let Some(s) = oldhome {
- setenv("HOME", s.as_slice());
+ setenv("HOME", s);
}
}
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
if let Some(s) = oldhome {
- setenv("HOME", s.as_slice());
+ setenv("HOME", &s);
}
if let Some(s) = olduserprofile {
- setenv("USERPROFILE", s.as_slice());
+ setenv("USERPROFILE", &s);
}
}
80, 81, 82, 83, 84, 85, 86, 87];
for &n in &lengths {
let mut v = repeat(0u8).take(n).collect::<Vec<_>>();
- r.fill_bytes(v.as_mut_slice());
+ r.fill_bytes(&mut v);
// use this to get nicer error messages.
for (i, &byte) in v.iter().enumerate() {
#[test]
fn test_std_rng_seeded() {
let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
- let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
- let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
+ let mut ra: StdRng = SeedableRng::from_seed(&*s);
+ let mut rb: StdRng = SeedableRng::from_seed(&*s);
assert!(order::equals(ra.gen_ascii_chars().take(100),
rb.gen_ascii_chars().take(100)));
}
#[test]
fn test_std_rng_reseed() {
let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
- let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
+ let mut r: StdRng = SeedableRng::from_seed(&*s);
let string1 = r.gen_ascii_chars().take(100).collect::<String>();
- r.reseed(s.as_slice());
+ r.reseed(&s);
let string2 = r.gen_ascii_chars().take(100).collect::<String>();
assert_eq!(string1, string2);
assert!(take() == Some(expected.clone()));
assert!(take() == None);
- (|&mut:| {
+ (|| {
}).finally(|| {
// Restore the actual global state.
match saved_value {
* waiting for the result to be received on the port.
*/
- Future::from_fn(move |:| {
+ Future::from_fn(move || {
rx.recv().unwrap()
})
}
let (tx, rx) = channel();
- Thread::spawn(move |:| {
+ Thread::spawn(move || {
// Don't panic if the other end has hung up
let _ = tx.send(blk());
});
// Ensure the borrowchecker works
match queue.peek() {
- Some(vec) => match vec.as_slice() {
+ Some(vec) => match &**vec {
// Note that `pop` is not allowed here due to borrow
[1] => {}
_ => return
}
fn spawn_in_pool(jobs: Arc<Mutex<Receiver<Thunk>>>) {
- Thread::spawn(move |:| {
+ Thread::spawn(move || {
// Will spawn a new thread on panic unless it is cancelled.
let sentinel = Sentinel::new(&jobs);
let receive = RaceBox(receive);
let t = f();
- Thread::spawn(move |:| {
+ Thread::spawn(move || {
helper(receive.0, rx, t);
let _g = self.lock.lock().unwrap();
*self.shutdown.get() = true;
self.cond.notify_one()
});
- rt::at_exit(move|:| { self.shutdown() });
+ rt::at_exit(move|| { self.shutdown() });
*self.initialized.get() = true;
}
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
- let dolock = |&:| self.lock_nonblocking();
- let doread = |&mut: nb| unsafe {
+ let dolock = || self.lock_nonblocking();
+ let doread = |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
- let dolock = |&:| self.lock_nonblocking();
- let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
+ let dolock = || self.lock_nonblocking();
+ let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
let mut addrlen: libc::socklen_t =
mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
- let dolock = |&:| self.lock_nonblocking();
+ let dolock = || self.lock_nonblocking();
let n = try!(read(fd, self.read_deadline, dolock, |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recvfrom(fd,
let dstp = &storage as *const _ as *const libc::sockaddr;
let fd = self.fd();
- let dolock = |&: | self.lock_nonblocking();
- let dowrite = |&mut: nb, buf: *const u8, len: uint| unsafe {
+ let dolock = || self.lock_nonblocking();
+ let dowrite = |nb, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::sendto(fd,
buf as *const libc::c_void,
pub fn set(stack_bounds: (uint, uint), stack_guard: uint, thread: Thread) {
THREAD_INFO.with(|c| assert!(c.borrow().is_none()));
match thread.name() {
- Some(name) => unsafe { ::sys::thread::set_name(name.as_slice()); },
+ Some(name) => unsafe { ::sys::thread::set_name(name); },
None => {}
}
THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{
impl fmt::Debug for Wtf8Buf {
#[inline]
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- self.as_slice().fmt(formatter)
+ fmt::Debug::fmt(&**self, formatter)
}
}
#[inline]
pub fn as_slice(&self) -> &Wtf8 {
- unsafe { mem::transmute(self.bytes.as_slice()) }
+ unsafe { mem::transmute(&*self.bytes) }
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// or if `new_len` is not a code point boundary.
#[inline]
pub fn truncate(&mut self, new_len: uint) {
- assert!(is_code_point_boundary(self.as_slice(), new_len));
+ assert!(is_code_point_boundary(self, new_len));
self.bytes.truncate(new_len)
}
let mut buf = [0u16; 2];
self.code_points.next().map(|code_point| {
- let n = encode_utf16_raw(code_point.value, buf.as_mut_slice())
+ let n = encode_utf16_raw(code_point.value, &mut buf)
.unwrap_or(0);
if n == 2 { self.extra = buf[1]; }
buf[0]
impl<S: Writer + Hasher> Hash<S> for Wtf8Buf {
#[inline]
fn hash(&self, state: &mut S) {
- state.write(self.bytes.as_slice());
+ state.write(&self.bytes);
0xfeu8.hash(state)
}
}
#[test]
fn code_point_to_string() {
- assert_eq!(format!("{:?}", CodePoint::from_char('a')).as_slice(), "U+0061");
- assert_eq!(format!("{:?}", CodePoint::from_char('💩')).as_slice(), "U+1F4A9");
+ assert_eq!(format!("{:?}", CodePoint::from_char('a')), "U+0061");
+ assert_eq!(format!("{:?}", CodePoint::from_char('💩')), "U+1F4A9");
}
#[test]
#[test]
fn wtf8buf_new() {
- assert_eq!(Wtf8Buf::new().bytes.as_slice(), b"");
+ assert_eq!(Wtf8Buf::new().bytes, b"");
}
#[test]
fn wtf8buf_from_str() {
- assert_eq!(Wtf8Buf::from_str("").bytes.as_slice(), b"");
- assert_eq!(Wtf8Buf::from_str("aé 💩").bytes.as_slice(),
+ assert_eq!(Wtf8Buf::from_str("").bytes, b"");
+ assert_eq!(Wtf8Buf::from_str("aé 💩").bytes,
b"a\xC3\xA9 \xF0\x9F\x92\xA9");
}
#[test]
fn wtf8buf_from_string() {
- assert_eq!(Wtf8Buf::from_string(String::from_str("")).bytes.as_slice(), b"");
- assert_eq!(Wtf8Buf::from_string(String::from_str("aé 💩")).bytes.as_slice(),
+ assert_eq!(Wtf8Buf::from_string(String::from_str("")).bytes, b"");
+ assert_eq!(Wtf8Buf::from_string(String::from_str("aé 💩")).bytes,
b"a\xC3\xA9 \xF0\x9F\x92\xA9");
}
#[test]
fn wtf8buf_from_wide() {
- assert_eq!(Wtf8Buf::from_wide(&[]).bytes.as_slice(), b"");
+ assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
assert_eq!(Wtf8Buf::from_wide(
- &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes.as_slice(),
+ &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
}
#[test]
fn wtf8buf_push_str() {
let mut string = Wtf8Buf::new();
- assert_eq!(string.bytes.as_slice(), b"");
+ assert_eq!(string.bytes, b"");
string.push_str("aé 💩");
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+ assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
}
#[test]
fn wtf8buf_push_char() {
let mut string = Wtf8Buf::from_str("aé ");
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 ");
+ assert_eq!(string.bytes, b"a\xC3\xA9 ");
string.push_char('💩');
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+ assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
}
#[test]
fn wtf8buf_push() {
let mut string = Wtf8Buf::from_str("aé ");
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 ");
+ assert_eq!(string.bytes, b"a\xC3\xA9 ");
string.push(CodePoint::from_char('💩'));
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+ assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
let mut string = Wtf8Buf::new();
string.push(c(0xD83D)); // lead
string.push(c(0xDCA9)); // trail
- assert_eq!(string.bytes.as_slice(), b"\xF0\x9F\x92\xA9"); // Magic!
+ assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
let mut string = Wtf8Buf::new();
string.push(c(0xD83D)); // lead
string.push(c(0x20)); // not surrogate
string.push(c(0xDCA9)); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
+ assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
let mut string = Wtf8Buf::new();
string.push(c(0xD800)); // lead
string.push(c(0xDBFF)); // lead
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
+ assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
let mut string = Wtf8Buf::new();
string.push(c(0xD800)); // lead
string.push(c(0xE000)); // not surrogate
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
+ assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
let mut string = Wtf8Buf::new();
string.push(c(0xD7FF)); // not surrogate
string.push(c(0xDC00)); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
let mut string = Wtf8Buf::new();
string.push(c(0x61)); // not surrogate, < 3 bytes
string.push(c(0xDC00)); // trail
- assert_eq!(string.bytes.as_slice(), b"\x61\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
let mut string = Wtf8Buf::new();
string.push(c(0xDC00)); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\xED\xB0\x80");
}
#[test]
fn wtf8buf_push_wtf8() {
let mut string = Wtf8Buf::from_str("aé");
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9");
+ assert_eq!(string.bytes, b"a\xC3\xA9");
string.push_wtf8(Wtf8::from_str(" 💩"));
- assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+ assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
fn w(value: &[u8]) -> &Wtf8 { unsafe { transmute(value) } }
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
- assert_eq!(string.bytes.as_slice(), b"\xF0\x9F\x92\xA9"); // Magic!
+ assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
string.push_wtf8(w(b" ")); // not surrogate
string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
+ assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\xA0\x80")); // lead
string.push_wtf8(w(b"\xED\xAF\xBF")); // lead
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
+ assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\xA0\x80")); // lead
string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate
- assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
+ assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate
string.push_wtf8(w(b"\xED\xB0\x80")); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes
string.push_wtf8(w(b"\xED\xB0\x80")); // trail
- assert_eq!(string.bytes.as_slice(), b"\x61\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
let mut string = Wtf8Buf::new();
string.push_wtf8(w(b"\xED\xB0\x80")); // trail
- assert_eq!(string.bytes.as_slice(), b"\xED\xB0\x80");
+ assert_eq!(string.bytes, b"\xED\xB0\x80");
}
#[test]
fn wtf8buf_truncate() {
let mut string = Wtf8Buf::from_str("aé");
string.truncate(1);
- assert_eq!(string.bytes.as_slice(), b"a");
+ assert_eq!(string.bytes, b"a");
}
#[test]
fn f(values: &[u32]) -> Wtf8Buf {
values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::<Wtf8Buf>()
};
- assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+ assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
- assert_eq!(f(&[0xD83D, 0xDCA9]).bytes.as_slice(), b"\xF0\x9F\x92\xA9"); // Magic!
- assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
- assert_eq!(f(&[0xD800, 0xDBFF]).bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
- assert_eq!(f(&[0xD800, 0xE000]).bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
- assert_eq!(f(&[0xD7FF, 0xDC00]).bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
- assert_eq!(f(&[0x61, 0xDC00]).bytes.as_slice(), b"\x61\xED\xB0\x80");
- assert_eq!(f(&[0xDC00]).bytes.as_slice(), b"\xED\xB0\x80");
+ assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
+ assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
+ assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
+ assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
+ assert_eq!(f(&[0xD7FF, 0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
+ assert_eq!(f(&[0x61, 0xDC00]).bytes, b"\x61\xED\xB0\x80");
+ assert_eq!(f(&[0xDC00]).bytes, b"\xED\xB0\x80");
}
#[test]
string
};
- assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes.as_slice(),
+ assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes,
b"a\xC3\xA9 \xF0\x9F\x92\xA9");
- assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes.as_slice(), b"\xF0\x9F\x92\xA9"); // Magic!
- assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
- assert_eq!(e(&[0xD800], &[0xDBFF]).bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
- assert_eq!(e(&[0xD800], &[0xE000]).bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
- assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
- assert_eq!(e(&[0x61], &[0xDC00]).bytes.as_slice(), b"\x61\xED\xB0\x80");
- assert_eq!(e(&[], &[0xDC00]).bytes.as_slice(), b"\xED\xB0\x80");
+ assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
+ assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
+ assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
+ assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
+ assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
+ assert_eq!(e(&[0x61], &[0xDC00]).bytes, b"\x61\xED\xB0\x80");
+ assert_eq!(e(&[], &[0xDC00]).bytes, b"\xED\xB0\x80");
}
#[test]
fn wtf8buf_show() {
let mut string = Wtf8Buf::from_str("aé 💩");
string.push(CodePoint::from_u32(0xD800).unwrap());
- assert_eq!(format!("{:?}", string).as_slice(), r#""aé 💩\u{D800}""#);
+ assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
}
#[test]
fn wtf8_show() {
let mut string = Wtf8Buf::from_str("aé 💩");
string.push(CodePoint::from_u32(0xD800).unwrap());
- assert_eq!(format!("{:?}", string.as_slice()).as_slice(), r#""aé 💩\u{D800}""#);
+ assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
}
#[test]
}
pub fn as_slice(&self) -> &Slice {
- unsafe { mem::transmute(self.inner.as_slice()) }
+ unsafe { mem::transmute(&*self.inner) }
}
pub fn into_string(self) -> Result<String, Buf> {
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
- let dolock = |&:| self.lock_nonblocking();
- let doread = |&mut: nb| unsafe {
+ let dolock = || self.lock_nonblocking();
+ let doread = |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
- let dolock = |&: | self.lock_nonblocking();
- let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
+ let dolock = || self.lock_nonblocking();
+ let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
mem::transmute::<&ProcessConfig<K,V>,&'static ProcessConfig<K,V>>(cfg)
};
- with_envp(cfg.env(), move|: envp: *const c_void| {
- with_argv(cfg.program(), cfg.args(), move|: argv: *const *const libc::c_char| unsafe {
+ with_envp(cfg.env(), move|envp: *const c_void| {
+ with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe {
let (input, mut output) = try!(sys::os::pipe());
// We may use this in the child, so perform allocations before the
// up /dev/null into that file descriptor. Otherwise, the first file
// descriptor opened up in the child would be numbered as one of the
// stdio file descriptors, which is likely to wreak havoc.
- let setup = |&: src: Option<P>, dst: c_int| {
+ let setup = |src: Option<P>, dst: c_int| {
let src = match src {
None => {
let flags = if dst == libc::STDIN_FILENO {
// Similarly to unix, we don't actually leave holes for the stdio file
// descriptors, but rather open up /dev/null equivalents. These
// equivalents are drawn from libuv's windows process spawning.
- let set_fd = |&: fd: &Option<P>, slot: &mut HANDLE,
+ let set_fd = |fd: &Option<P>, slot: &mut HANDLE,
is_stdin: bool| {
match *fd {
None => {
}
let argvec: Vec<char> = arg.chars().collect();
for i in 0u..argvec.len() {
- append_char_at(cmd, argvec.as_slice(), i);
+ append_char_at(cmd, &argvec, i);
}
if quote {
cmd.push('"');
fn test_make_command_line() {
fn test_wrapper(prog: &str, args: &[&str]) -> String {
make_command_line(&CString::from_slice(prog.as_bytes()),
- args.iter()
- .map(|a| CString::from_slice(a.as_bytes()))
- .collect::<Vec<CString>>()
- .as_slice())
+ &args.iter()
+ .map(|a| CString::from_slice(a.as_bytes()))
+ .collect::<Vec<CString>>())
}
assert_eq!(
_ => (),
};
utf16.truncate(num as uint);
- let utf8 = match String::from_utf16(utf16.as_slice()) {
+ let utf8 = match String::from_utf16(&utf16) {
Ok(utf8) => utf8.into_bytes(),
Err(..) => return Err(invalid_encoding()),
};
use option::Option::{self, Some, None};
use result::Result::{Err, Ok};
use sync::{Mutex, Condvar, Arc};
-use str::Str;
use string::String;
use rt::{self, unwind};
use old_io::{Writer, stdio};
{
let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
let their_packet = Packet(my_packet.0.clone());
- let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |: ret| unsafe {
+ let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |ret| unsafe {
*their_packet.0.get() = Some(ret);
}));
// because by the time that this function is executing we've already
// consumed at least a little bit of stack (we don't know the exact byte
// address at which our stack started).
- let main = move |:| {
+ let main = move || {
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const int;
let my_stack_top = addr as uint;
let mut output = None;
let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
- Thunk::new(move |:| {
+ Thunk::new(move || {
let _ = stdout.map(stdio::set_stdout);
let _ = stderr.map(stdio::set_stderr);
f.invoke(())
/// Get the thread's name.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn name(&self) -> Option<&str> {
- self.inner.name.as_ref().map(|s| s.as_slice())
+ self.inner.name.as_ref().map(|s| &**s)
}
}
fn test_join_success() {
match Thread::scoped(move|| -> String {
"Success!".to_string()
- }).join().as_ref().map(|s| s.as_slice()) {
+ }).join().as_ref().map(|s| &**s) {
result::Result::Ok("Success!") => (),
_ => panic!()
}
pub fn new<F>(func: F) -> Thunk<(),R>
where F : FnOnce() -> R, F : Send
{
- Thunk::with_arg(move|: ()| func())
+ Thunk::with_arg(move|()| func())
}
}
}
pub fn kind(self) -> visit::FnKind<'a> {
- let item = |: p: ItemFnParts<'a>| -> visit::FnKind<'a> {
+ let item = |p: ItemFnParts<'a>| -> visit::FnKind<'a> {
visit::FkItemFn(p.ident, p.generics, p.unsafety, p.abi)
};
- let closure = |: _: ClosureParts| {
+ let closure = |_: ClosureParts| {
visit::FkFnBlock
};
- let method = |: m: &'a ast::Method| {
+ let method = |m: &'a ast::Method| {
visit::FkMethod(m.pe_ident(), m.pe_generics(), m)
};
self.handle(item, method, closure)
!cfg_matches(diagnostic, cfgs, &*mis[0])
}
ast::MetaList(ref pred, _) => {
- diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice());
+ diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
false
},
ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),
FileLines {file: lo.file, lines: lines}
}
- pub fn span_to_snippet(&self, sp: Span) -> Option<String> {
+ pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
+ if sp.lo > sp.hi {
+ return Err(SpanSnippetError::IllFormedSpan(sp));
+ }
+
let begin = self.lookup_byte_offset(sp.lo);
let end = self.lookup_byte_offset(sp.hi);
- // FIXME #8256: this used to be an assert but whatever precondition
- // it's testing isn't true for all spans in the AST, so to allow the
- // caller to not have to panic (and it can't catch it since the CodeMap
- // isn't sendable), return None
if begin.fm.start_pos != end.fm.start_pos {
- None
+ return Err(SpanSnippetError::DistinctSources(DistinctSources {
+ begin: (begin.fm.name.clone(),
+ begin.fm.start_pos),
+ end: (end.fm.name.clone(),
+ end.fm.start_pos)
+ }));
} else {
- Some((&begin.fm.src[begin.pos.to_usize()..end.pos.to_usize()]).to_string())
+ let start = begin.pos.to_usize();
+ let limit = end.pos.to_usize();
+ if start > limit || limit > begin.fm.src.len() {
+ return Err(SpanSnippetError::MalformedForCodemap(
+ MalformedCodemapPositions {
+ name: begin.fm.name.clone(),
+ source_len: begin.fm.src.len(),
+ begin_pos: begin.pos,
+ end_pos: end.pos,
+ }));
+ }
+
+ return Ok((&begin.fm.src[start..limit]).to_string())
}
}
}
}
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub enum SpanSnippetError {
+ IllFormedSpan(Span),
+ DistinctSources(DistinctSources),
+ MalformedForCodemap(MalformedCodemapPositions),
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct DistinctSources {
+ begin: (String, BytePos),
+ end: (String, BytePos)
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct MalformedCodemapPositions {
+ name: String,
+ source_len: usize,
+ begin_pos: BytePos,
+ end_pos: BytePos
+}
+
#[cfg(test)]
mod test {
use super::*;
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
let snippet = cm.span_to_snippet(span);
- assert_eq!(snippet, Some("second line".to_string()));
+ assert_eq!(snippet, Ok("second line".to_string()));
}
#[test]
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate {
let config = krate.config.clone();
- strip_items(krate, |attrs| in_cfg(diagnostic, config.as_slice(), attrs))
+ strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs))
}
impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool {
}
ast::ItemEnum(def, generics) => {
let variants = def.variants.into_iter().filter_map(|v| {
- if !(cx.in_cfg)(v.node.attrs.as_slice()) {
+ if !(cx.in_cfg)(&v.node.attrs) {
None
} else {
Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind,
def.map(|ast::StructDef { fields, ctor_id }| {
ast::StructDef {
fields: fields.into_iter().filter(|m| {
- (cx.in_cfg)(m.node.attrs.as_slice())
+ (cx.in_cfg)(&m.node.attrs)
}).collect(),
ctor_id: ctor_id,
}
node: match node {
ast::ExprMatch(m, arms, source) => {
ast::ExprMatch(m, arms.into_iter()
- .filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
+ .filter(|a| (cx.in_cfg)(&a.attrs))
.collect(), source)
}
_ => node
fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
F: FnMut(&[ast::Attribute]) -> bool
{
- return (cx.in_cfg)(item.attrs.as_slice());
+ return (cx.in_cfg)(&item.attrs);
}
fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
F: FnMut(&[ast::Attribute]) -> bool
{
- return (cx.in_cfg)(item.attrs.as_slice());
+ return (cx.in_cfg)(&item.attrs);
}
fn trait_method_in_cfg<F>(cx: &mut Context<F>, meth: &ast::TraitItem) -> bool where
F: FnMut(&[ast::Attribute]) -> bool
{
match *meth {
- ast::RequiredMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
- ast::ProvidedMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
- ast::TypeTraitItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
+ ast::RequiredMethod(ref meth) => (cx.in_cfg)(&meth.attrs),
+ ast::ProvidedMethod(ref meth) => (cx.in_cfg)(&meth.attrs),
+ ast::TypeTraitItem(ref typ) => (cx.in_cfg)(&typ.attrs),
}
}
F: FnMut(&[ast::Attribute]) -> bool
{
match *impl_item {
- ast::MethodImplItem(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
- ast::TypeImplItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
+ ast::MethodImplItem(ref meth) => (cx.in_cfg)(&meth.attrs),
+ ast::TypeImplItem(ref typ) => (cx.in_cfg)(&typ.attrs),
}
}
macro_rules! span_fatal {
($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
__diagnostic_used!($code);
- $session.span_fatal_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+ $session.span_fatal_with_code($span, &format!($($message)*), stringify!($code))
})
}
macro_rules! span_err {
($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
__diagnostic_used!($code);
- $session.span_err_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+ $session.span_err_with_code($span, &format!($($message)*), stringify!($code))
})
}
macro_rules! span_warn {
($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
__diagnostic_used!($code);
- $session.span_warn_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+ $session.span_warn_with_code($span, &format!($($message)*), stringify!($code))
})
}
#[macro_export]
macro_rules! span_note {
($session:expr, $span:expr, $($message:tt)*) => ({
- ($session).span_note($span, format!($($message)*).as_slice())
+ ($session).span_note($span, &format!($($message)*))
})
}
#[macro_export]
macro_rules! span_help {
($session:expr, $span:expr, $($message:tt)*) => ({
- ($session).span_help($span, format!($($message)*).as_slice())
+ ($session).span_help($span, &format!($($message)*))
})
}
return DummyResult::expr(sp);
}
- let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, cx.cfg.as_slice(), &*cfg);
+ let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &*cfg);
MacExpr::new(cx.expr_bool(sp, matches_cfg))
}
};
let mut out = (*it).clone();
- if attr::cfg_matches(&cx.parse_sess.span_diagnostic, cx.cfg.as_slice(), &**cfg) {
+ if attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &**cfg) {
out.attrs.push(cx.attribute(attr.span, attr.clone()));
}
"Copy" => "Copy",
"Send" | "Sync" => {
return cx.span_err(span,
- format!("{} is an unsafe trait and it \
- should be implemented explicitly",
- *tname).as_slice())
+ &format!("{} is an unsafe trait and it \
+ should be implemented explicitly",
+ *tname))
}
ref tname => {
cx.span_bug(span,
- format!("expected built-in trait name but \
- found {}", *tname).as_slice())
+ &format!("expected built-in trait name but \
+ found {}", *tname))
}
}
},
cx.ident_of("Clone"),
cx.ident_of("clone"),
];
- let subcall = |&: field: &FieldInfo| {
+ let subcall = |field: &FieldInfo| {
let args = vec![cx.expr_addr_of(field.span, field.self_.clone())];
cx.expr_call_global(field.span, fn_path.clone(), args)
cx.ident_of("Default"),
cx.ident_of("default")
);
- let default_call = |&: span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
+ let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
// where each tuple has length = self_args.len()
let mut match_arms: Vec<ast::Arm> = variants.iter().enumerate()
.map(|(index, variant)| {
- let mk_self_pat = |&: cx: &mut ExtCtxt, self_arg_name: &str| {
+ let mk_self_pat = |cx: &mut ExtCtxt, self_arg_name: &str| {
let (p, idents) = trait_.create_enum_variant_pattern(cx, type_ident,
&**variant,
self_arg_name,
mk_ty_param(cx,
span,
*name,
- bounds.as_slice(),
+ bounds,
self_ty,
self_generics)
}
[ref state_expr] => state_expr,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`")
};
- let call_hash = |&: span, thing_expr| {
+ let call_hash = |span, thing_expr| {
let hash_path = {
let strs = vec![
cx.ident_of("std"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
- let rand_call = |&: cx: &mut ExtCtxt, span| {
+ let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
rand_ident.clone(),
vec!(rng.clone()))
id: ast::DUMMY_NODE_ID,
span: it.span,
imported_from: None,
- export: attr::contains_name(it.attrs.as_slice(), "macro_export"),
+ export: attr::contains_name(&it.attrs, "macro_export"),
use_locally: true,
body: tts,
};
// but that double-mut-borrows fld
let mut items: SmallVector<P<ast::Item>> = SmallVector::zero();
dec.expand(fld.cx, attr.span, &*attr.node.value, &**it,
- box |&mut: item| items.push(item));
+ box |item| items.push(item));
decorator_items.extend(items.into_iter()
.flat_map(|item| expand_item(item, fld).into_iter()));
assert!((shouldmatch.len() == 0) ||
(varrefs.len() > *shouldmatch.iter().max().unwrap()));
for (idx,varref) in varrefs.iter().enumerate() {
- let print_hygiene_debug_info = |&:| {
+ let print_hygiene_debug_info = || {
// good lord, you can't make a path with 0 segments, can you?
let final_varref_ident = match varref.segments.last() {
Some(pathsegment) => pathsegment.identifier,
fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
let sp = self.fmtsp;
- let count = |: c, arg| {
+ let count = |c, arg| {
let mut path = Context::rtpath(self.ecx, "Count");
path.push(self.ecx.ident_of(c));
match arg {
parse::NextArgument(ref arg) => {
// Translate the position
let pos = {
- let pos = |: c, arg| {
+ let pos = |c, arg| {
let mut path = Context::rtpath(self.ecx, "Position");
path.push(self.ecx.ident_of(c));
match arg {
// Translate the format
let fill = self.ecx.expr_lit(sp, ast::LitChar(fill));
- let align = |:name| {
+ let align = |name| {
let mut p = Context::rtpath(self.ecx, "Alignment");
p.push(self.ecx.ident_of(name));
self.ecx.path_global(sp, p)
tts: &[ast::TokenTree]) -> P<ast::Expr> {
let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
- let cfg_call = |&:| cx.expr_method_call(
+ let cfg_call = || cx.expr_method_call(
sp, cx.expr_ident(sp, id_ext("ext_cx")),
id_ext("cfg"), Vec::new());
- let parse_sess_call = |&:| cx.expr_method_call(
+ let parse_sess_call = || cx.expr_method_call(
sp, cx.expr_ident(sp, id_ext("ext_cx")),
id_ext("parse_sess"), Vec::new());
Some(&&TtToken(_, ref tok)) => tok.clone(),
Some(&&TtSequence(sp, _)) => {
cx.span_err(sp,
- format!("`${0}:{1}` is followed by a \
- sequence repetition, which is not \
- allowed for `{1}` fragments",
- name.as_str(), frag_spec.as_str())
- .as_slice());
+ &format!("`${0}:{1}` is followed by a \
+ sequence repetition, which is not \
+ allowed for `{1}` fragments",
+ name.as_str(), frag_spec.as_str())
+ );
Eof
},
// die next iteration
(&Eof, _) => return Some((sp, tok.clone())),
(_, Ok(true)) => continue,
(next, Ok(false)) => {
- cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \
- is not allowed for `{1}` fragments",
+ cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \
+ is not allowed for `{1}` fragments",
name.as_str(), frag_spec.as_str(),
- token_to_string(next)).as_slice());
+ token_to_string(next)));
continue
},
(_, Err(msg)) => {
- cx.span_err(sp, msg.as_slice());
+ cx.span_err(sp, &msg);
continue
}
}
_ => {}
}
- if attr::contains_name(i.attrs.as_slice(),
+ if attr::contains_name(&i.attrs,
"unsafe_destructor") {
self.gate_feature("unsafe_destructor",
i.span,
and not portable across platforms")
}
- let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
+ let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
"link_name") {
Some(val) => val.get().starts_with("llvm."),
_ => false
Spanned {
node: match node {
MacInvocTT(p, tts, ctxt) => {
- MacInvocTT(fld.fold_path(p), fld.fold_tts(tts.as_slice()), ctxt)
+ MacInvocTT(fld.fold_path(p), fld.fold_tts(&tts), ctxt)
}
},
span: fld.new_span(span)
Delimited {
delim: delimed.delim,
open_span: delimed.open_span,
- tts: fld.fold_tts(delimed.tts.as_slice()),
+ tts: fld.fold_tts(&delimed.tts),
close_span: delimed.close_span,
}
))
TtSequence(span, ref seq) =>
TtSequence(span,
Rc::new(SequenceRepetition {
- tts: fld.fold_tts(seq.tts.as_slice()),
+ tts: fld.fold_tts(&seq.tts),
separator: seq.separator.clone().map(|tok| fld.fold_token(tok)),
..**seq
})),
// this version doesn't care about getting comments or docstrings in.
fn fake_print_crate(s: &mut pprust::State,
krate: &ast::Crate) -> old_io::IoResult<()> {
- s.print_mod(&krate.module, krate.attrs.as_slice())
+ s.print_mod(&krate.module, &krate.attrs)
}
// change every identifier to "zz"
let pred_val = $pred;
let a_val = $a;
let b_val = $b;
- if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
+ if !(pred_val(&a_val, &b_val)) {
panic!("expected args satisfying {}, got {} and {}",
$predname, a_val, b_val);
}
impl<T: Clone> Clone for OwnedSlice<T> {
fn clone(&self) -> OwnedSlice<T> {
- OwnedSlice::from_vec(self.as_slice().to_vec())
+ OwnedSlice::from_vec(self.to_vec())
}
}
impl<T: Encodable> Encodable for OwnedSlice<T> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- self.as_slice().encode(s)
+ Encodable::encode(&**self, s)
}
}
pub fn nextnextch(&self) -> Option<char> {
let offset = self.byte_offset(self.pos).to_usize();
- let s = self.filemap.src.as_slice();
+ let s = &*self.filemap.src;
if offset >= s.len() { return None }
let str::CharRange { next, .. } = s.char_range_at(offset);
if next < s.len() {
/// add the path to the session's codemap and return the new filemap.
pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
-> Rc<FileMap> {
- let err = |&: msg: &str| {
+ let err = |msg: &str| {
match spanopt {
Some(sp) => sess.span_diagnostic.span_fatal(sp, msg),
None => sess.span_diagnostic.handler().fatal(msg),
.map(|x| (x, len as isize))
}
- let unicode_escape = |&: | -> Option<(char, isize)>
+ let unicode_escape = || -> Option<(char, isize)>
if lit.as_bytes()[2] == b'{' {
let idx = lit.find('}').expect(msg2);
let subslice = &lit[3..idx];
let mut res = String::with_capacity(lit.len());
// FIXME #8372: This could be a for-loop if it didn't borrow the iterator
- let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
+ let error = |i| format!("lexer should have rejected {} at {}", lit, i);
/// Eat everything up to a non-whitespace
fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
match c {
'\\' => {
let ch = chars.peek().unwrap_or_else(|| {
- panic!("{}", error(i).as_slice())
+ panic!("{}", error(i))
}).1;
if ch == '\n' {
} else if ch == '\r' {
chars.next();
let ch = chars.peek().unwrap_or_else(|| {
- panic!("{}", error(i).as_slice())
+ panic!("{}", error(i))
}).1;
if ch != '\n' {
},
'\r' => {
let ch = chars.peek().unwrap_or_else(|| {
- panic!("{}", error(i).as_slice())
+ panic!("{}", error(i))
}).1;
if ch != '\n' {
/// Parse a string representing a byte literal into its final form. Similar to `char_lit`
pub fn byte_lit(lit: &str) -> (u8, usize) {
- let err = |&: i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
+ let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
if lit.len() == 1 {
(lit.as_bytes()[0], 1)
let mut res = Vec::with_capacity(lit.len());
// FIXME #8372: This could be a for-loop if it didn't borrow the iterator
- let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
+ let error = |i| format!("lexer should have rejected {} at {}", lit, i);
/// Eat everything up to a non-whitespace
fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
match chars.next() {
Some((i, b'\\')) => {
let em = error(i);
- match chars.peek().expect(em.as_slice()).1 {
+ match chars.peek().expect(&em).1 {
b'\n' => eat(&mut chars),
b'\r' => {
chars.next();
- if chars.peek().expect(em.as_slice()).1 != b'\n' {
+ if chars.peek().expect(&em).1 != b'\n' {
panic!("lexer accepted bare CR");
}
eat(&mut chars);
},
Some((i, b'\r')) => {
let em = error(i);
- if chars.peek().expect(em.as_slice()).1 != b'\n' {
+ if chars.peek().expect(&em).1 != b'\n' {
panic!("lexer accepted bare CR");
}
chars.next();
let name = "<source>".to_string();
let source = "/// doc comment\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
- let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
+ let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(doc.get(), "/// doc comment");
let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
- let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
+ let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(doc.get(), "/** doc comment\n * with CRLF */");
}
let span = tts.iter().rev().next().unwrap().get_span();
match sess.span_diagnostic.cm.span_to_snippet(span) {
- Some(s) => assert_eq!(&s[], "{ body }"),
- None => panic!("could not get snippet"),
+ Ok(s) => assert_eq!(&s[], "{ body }"),
+ Err(_) => panic!("could not get snippet"),
}
}
}
/// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
pub fn parse_obsolete_closure_kind(&mut self) {
- // let lo = self.span.lo;
+ let lo = self.span.lo;
if
self.check(&token::BinOp(token::And)) &&
self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
return;
}
- // SNAP 474b324
- // Enable these obsolete errors after snapshot:
- // let span = mk_sp(lo, self.span.hi);
- // self.obsolete(span, ObsoleteSyntax::ClosureKind);
+ let span = mk_sp(lo, self.span.hi);
+ self.obsolete(span, ObsoleteSyntax::ClosureKind);
}
pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
token::Str_(s) => {
(true,
- LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
+ LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
ast::CookedStr))
}
token::StrRaw(s, n) => {
let bracket_pos = self.span.lo;
self.bump();
- let mut found_dotdot = false;
- if self.token == token::DotDot &&
- self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
- // Using expr[..], which is a mistake, should be expr[]
- self.bump();
- self.bump();
- found_dotdot = true;
- }
-
- if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
+ if self.eat(&token::CloseDelim(token::Bracket)) {
// No expression, expand to a RangeFull
// FIXME(#20516) It would be better to use a lang item or
// something for RangeFull.
let range = ExprStruct(path, vec![], None);
let ix = self.mk_expr(bracket_pos, hi, range);
let index = self.mk_index(e, ix);
- e = self.mk_expr(lo, hi, index)
+ e = self.mk_expr(lo, hi, index);
+ // Enable after snapshot.
+ // self.span_warn(e.span, "deprecated slicing syntax: `[]`");
+ // self.span_note(e.span,
+ // "use `&expr[..]` to construct a slice of the whole of expr");
} else {
let ix = self.parse_expr();
hi = self.span.hi;
e = self.mk_expr(lo, hi, index)
}
- if found_dotdot {
- self.span_err(e.span, "incorrect slicing expression: `[..]`");
- self.span_note(e.span,
- "use `&expr[]` to construct a slice of the whole of expr");
- }
}
_ => return e
}
|p| p.parse_token_tree()
);
let (sep, repeat) = self.parse_sep_and_kleene_op();
- let name_num = macro_parser::count_names(seq.as_slice());
+ let name_num = macro_parser::count_names(&seq);
return TtSequence(mk_sp(sp.lo, seq_span.hi),
Rc::new(SequenceRepetition {
tts: seq,
// with the postfix-form 'expr..'
let lo = self.span.lo;
self.bump();
- let rhs = self.parse_binops();
- let hi = rhs.span.hi;
- let ex = self.mk_range(None, Some(rhs));
+ let opt_end = if self.is_at_start_of_range_notation_rhs() {
+ let end = self.parse_binops();
+ Some(end)
+ } else {
+ None
+ };
+ let hi = self.span.hi;
+ let ex = self.mk_range(None, opt_end);
self.mk_expr(lo, hi, ex)
}
_ => {
token::Bracket => try!(word(&mut self.s, "[")),
token::Brace => try!(self.bopen()),
}
- try!(self.print_tts(tts.as_slice()));
+ try!(self.print_tts(tts));
match delim {
token::Paren => self.pclose(),
token::Bracket => word(&mut self.s, "]"),
if let &Some(ref e) = start {
try!(self.print_expr(&**e));
}
- if start.is_some() || end.is_some() {
- try!(word(&mut self.s, ".."));
- }
+ try!(word(&mut self.s, ".."));
if let &Some(ref e) = end {
try!(self.print_expr(&**e));
}
ref bounds,
..}) => {
try!(self.print_type(&**bounded_ty));
- try!(self.print_bounds(":", bounds.as_slice()));
+ try!(self.print_bounds(":", bounds));
}
&ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
ref bounds,
&format!("-{}", istr)[])
}
ast::UnsignedIntLit(ut) => {
- word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
+ word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i)))
}
ast::UnsuffixedIntLit(ast::Plus) => {
word(&mut self.s, &format!("{}", i)[])
opt_unsafety: Option<ast::Unsafety>,
abi: abi::Abi,
vis: ast::Visibility) -> IoResult<()> {
- try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
+ try!(word(&mut self.s, &visibility_qualified(vis, "")));
try!(self.print_opt_unsafety(opt_unsafety));
if abi != abi::Rust {
let test_id = ecx.ident_of("test");
// creates self::test::$name
- let test_path = |&: name| {
+ let test_path = |name| {
ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
};
// creates $name: $expr
- let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
+ let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
debug!("encoding {}", ast_util::path_name_i(&path[]));
vec![name_expr]);
let ignore_expr = ecx.expr_bool(span, test.ignore);
- let should_fail_path = |&: name| {
+ let should_fail_path = |name| {
ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldFail"), ecx.ident_of(name)])
};
let fail_expr = match test.should_fail {
result
}
One(ref v) => slice::ref_slice(v),
- Many(ref vs) => vs.as_slice()
+ Many(ref vs) => vs
}
}
visitor.visit_expr(&**subexpression)
}
ExprVec(ref subexpressions) => {
- walk_exprs(visitor, subexpressions.as_slice())
+ walk_exprs(visitor, subexpressions)
}
ExprRepeat(ref element, ref count) => {
visitor.visit_expr(&**element);
visitor.visit_expr(&**callee_expression)
}
ExprMethodCall(_, ref types, ref arguments) => {
- walk_exprs(visitor, arguments.as_slice());
+ walk_exprs(visitor, arguments);
for typ in types {
visitor.visit_ty(&**typ)
}
.strings
.get("setaf")
.unwrap()
- .as_slice(),
+ ,
&[Number(color as int)], &mut Variables::new());
if s.is_ok() {
- try!(self.out.write_all(s.unwrap().as_slice()));
+ try!(self.out.write_all(&s.unwrap()));
return Ok(true)
}
}
.strings
.get("setab")
.unwrap()
- .as_slice(),
+ ,
&[Number(color as int)], &mut Variables::new());
if s.is_ok() {
- try!(self.out.write_all(s.unwrap().as_slice()));
+ try!(self.out.write_all(&s.unwrap()));
return Ok(true)
}
}
let cap = cap_for_attr(attr);
let parm = self.ti.strings.get(cap);
if parm.is_some() {
- let s = expand(parm.unwrap().as_slice(),
+ let s = expand(parm.unwrap(),
&[],
&mut Variables::new());
if s.is_ok() {
- try!(self.out.write_all(s.unwrap().as_slice()));
+ try!(self.out.write_all(&s.unwrap()));
return Ok(true)
}
}
}
}
let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |op| {
- expand(op.as_slice(), &[], &mut Variables::new())
+ expand(op, &[], &mut Variables::new())
});
if s.is_ok() {
- return self.out.write_all(s.unwrap().as_slice())
+ return self.out.write_all(&s.unwrap())
}
Ok(())
}
let flags = Flags::new();
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags);
if res.is_err() { return res }
- output.push_all(res.unwrap().as_slice())
+ output.push_all(&res.unwrap())
} else { return Err("stack is empty".to_string()) },
':'|'#'|' '|'.'|'0'...'9' => {
let mut flags = Flags::new();
(_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if stack.len() > 0 {
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), *flags);
if res.is_err() { return res }
- output.push_all(res.unwrap().as_slice());
+ output.push_all(&res.unwrap());
// will cause state to go to Nothing
old_state = FormatPattern(*flags, *fstate);
} else { return Err("stack is empty".to_string()) },
{
let mut u8v: Vec<_> = fmt.bytes().collect();
u8v.extend(cap.as_bytes().iter().map(|&b| b));
- expand(u8v.as_slice(), params, vars)
+ expand(&u8v, params, vars)
}
let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"];
fn as_slice<'a>(&'a self) -> &'a str {
match *self {
StaticTestName(s) => s,
- DynTestName(ref s) => s.as_slice()
+ DynTestName(ref s) => s
}
}
}
match align {
PadNone => name,
PadOnLeft => {
- pad.push_str(name.as_slice());
+ pad.push_str(&name);
pad
}
PadOnRight => {
- name.push_str(pad.as_slice());
+ name.push_str(&pad);
name
}
}
test, then the test runner will ignore these tests during
normal test runs. Running with --ignored will run these
tests."#,
- usage = getopts::usage(message.as_slice(),
- optgroups().as_slice()));
+ usage = getopts::usage(&message, &optgroups()));
}
// Parses command line arguments into test options
pub fn parse_opts(args: &[String]) -> Option<OptRes> {
let args_ = args.tail();
let matches =
- match getopts::getopts(args_.as_slice(), optgroups().as_slice()) {
+ match getopts::getopts(args_, &optgroups()) {
Ok(m) => m,
Err(f) => return Some(Err(f.to_string()))
};
- if matches.opt_present("h") { usage(args[0].as_slice()); return None; }
+ if matches.opt_present("h") { usage(&args[0]); return None; }
let filter = if matches.free.len() > 0 {
Some(matches.free[0].clone())
nocapture = env::var("RUST_TEST_NOCAPTURE").is_some();
}
- let color = match matches.opt_str("color").as_ref().map(|s| s.as_slice()) {
+ let color = match matches.opt_str("color").as_ref().map(|s| &**s) {
Some("auto") | None => AutoColor,
Some("always") => AlwaysColor,
Some("never") => NeverColor,
pub fn write_run_start(&mut self, len: uint) -> old_io::IoResult<()> {
self.total = len;
let noun = if len != 1 { "tests" } else { "test" };
- self.write_plain(format!("\nrunning {} {}\n", len, noun).as_slice())
+ self.write_plain(&format!("\nrunning {} {}\n", len, noun))
}
pub fn write_test_start(&mut self, test: &TestDesc,
align: NamePadding) -> old_io::IoResult<()> {
let name = test.padded_name(self.max_name_len, align);
- self.write_plain(format!("test {} ... ", name).as_slice())
+ self.write_plain(&format!("test {} ... ", name))
}
pub fn write_result(&mut self, result: &TestResult) -> old_io::IoResult<()> {
TrIgnored => self.write_ignored(),
TrMetrics(ref mm) => {
try!(self.write_metric());
- self.write_plain(format!(": {}", mm.fmt_metrics()).as_slice())
+ self.write_plain(&format!(": {}", mm.fmt_metrics()))
}
TrBench(ref bs) => {
try!(self.write_bench());
- try!(self.write_plain(format!(": {}",
- fmt_bench_samples(bs)).as_slice()));
+ try!(self.write_plain(&format!(": {}", fmt_bench_samples(bs))));
Ok(())
}
TrIgnored => "ignored".to_string(),
TrMetrics(ref mm) => mm.fmt_metrics(),
TrBench(ref bs) => fmt_bench_samples(bs)
- }, test.name.as_slice());
+ }, test.name);
o.write_all(s.as_bytes())
}
}
for &(ref f, ref stdout) in &self.failures {
failures.push(f.name.to_string());
if stdout.len() > 0 {
- fail_out.push_str(format!("---- {} stdout ----\n\t",
- f.name.as_slice()).as_slice());
- let output = String::from_utf8_lossy(stdout.as_slice());
- fail_out.push_str(output.as_slice());
+ fail_out.push_str(&format!("---- {} stdout ----\n\t", f.name));
+ let output = String::from_utf8_lossy(stdout);
+ fail_out.push_str(&output);
fail_out.push_str("\n");
}
}
if fail_out.len() > 0 {
try!(self.write_plain("\n"));
- try!(self.write_plain(fail_out.as_slice()));
+ try!(self.write_plain(&fail_out));
}
try!(self.write_plain("\nfailures:\n"));
failures.sort();
for name in &failures {
- try!(self.write_plain(format!(" {}\n",
- name.as_slice()).as_slice()));
+ try!(self.write_plain(&format!(" {}\n", name)));
}
Ok(())
}
}
let s = format!(". {} passed; {} failed; {} ignored; {} measured\n\n",
self.passed, self.failed, self.ignored, self.measured);
- try!(self.write_plain(s.as_slice()));
+ try!(self.write_plain(&s));
return Ok(success);
}
}
TrOk => st.passed += 1,
TrIgnored => st.ignored += 1,
TrMetrics(mm) => {
- let tname = test.name.as_slice();
+ let tname = test.name;
let MetricMap(mm) = mm;
for (k,v) in &mm {
st.metrics
- .insert_metric(format!("{}.{}",
- tname,
- k).as_slice(),
+ .insert_metric(&format!("{}.{}",
+ tname,
+ k),
v.value,
v.noise);
}
match tests.iter().max_by(|t|len_if_padded(*t)) {
Some(t) => {
let n = t.desc.name.as_slice();
- st.max_name_len = n.len();
+ st.max_name_len = n.as_slice().len();
},
None => {}
}
let args = vec!("progname".to_string(),
"filter".to_string(),
"--ignored".to_string());
- let opts = match parse_opts(args.as_slice()) {
+ let opts = match parse_opts(&args) {
Some(Ok(o)) => o,
_ => panic!("Malformed arg in parse_ignored_flag")
};
fn percentile(&self, pct: T) -> T {
let mut tmp = self.to_vec();
- local_sort(tmp.as_mut_slice());
- percentile_of_sorted(tmp.as_slice(), pct)
+ local_sort(&mut tmp);
+ percentile_of_sorted(&tmp, pct)
}
fn quartiles(&self) -> (T,T,T) {
let mut tmp = self.to_vec();
- local_sort(tmp.as_mut_slice());
+ local_sort(&mut tmp);
let first = FromPrimitive::from_uint(25).unwrap();
- let a = percentile_of_sorted(tmp.as_slice(), first);
+ let a = percentile_of_sorted(&tmp, first);
let secound = FromPrimitive::from_uint(50).unwrap();
- let b = percentile_of_sorted(tmp.as_slice(), secound);
+ let b = percentile_of_sorted(&tmp, secound);
let third = FromPrimitive::from_uint(75).unwrap();
- let c = percentile_of_sorted(tmp.as_slice(), third);
+ let c = percentile_of_sorted(&tmp, third);
(a,b,c)
}
/// See: http://en.wikipedia.org/wiki/Winsorising
pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {
let mut tmp = samples.to_vec();
- local_sort(tmp.as_mut_slice());
- let lo = percentile_of_sorted(tmp.as_slice(), pct);
+ local_sort(&mut tmp);
+ let lo = percentile_of_sorted(&tmp, pct);
let hundred: T = FromPrimitive::from_uint(100).unwrap();
- let hi = percentile_of_sorted(tmp.as_slice(), hundred-pct);
+ let hi = percentile_of_sorted(&tmp, hundred-pct);
for samp in samples {
if *samp > hi {
*samp = hi
#[inline]
fn trim_left(&self) -> &str {
- self.trim_left_matches(|&: c: char| c.is_whitespace())
+ self.trim_left_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_right(&self) -> &str {
- self.trim_right_matches(|&: c: char| c.is_whitespace())
+ self.trim_right_matches(|c: char| c.is_whitespace())
}
}
let mut buf = [0u16; 2];
self.chars.next().map(|ch| {
- let n = CharExt::encode_utf16(ch, buf.as_mut_slice()).unwrap_or(0);
+ let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0);
if n == 2 { self.extra = buf[1]; }
buf[0]
})
#endif
#endif
-#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) || defined(__DragonFly__) || defined(__OpenBSD__)
+#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) \
+ || defined(__DragonFly__) || defined(__OpenBSD__)
extern char **environ;
#endif
/* get realpath if possible */
if ((argv[0] != NULL) && ((*argv[0] == '.') || (*argv[0] == '/')
- || (strstr(argv[0], "/") != NULL)))
+ || (strstr(argv[0], "/") != NULL)))
self = realpath(argv[0], NULL);
else
+S 2015-02-04 ac134f7
+ freebsd-x86_64 483e37a02a7ebc12a872e3146145e342ba4a5c04
+ linux-i386 8af64e5df839cc945399484380a8b2ebe05a6751
+ linux-x86_64 9f485d79c1f0d273ed864eddadb1707f3e2df489
+ macos-i386 800f86abd589a1d46c37a8700211c7ba6b05decb
+ macos-x86_64 b9961faccf79dcfdc0b7a6909bef8b6769798d08
+ winnt-i386 2c56a7573f8d0f78271dab1c8e29d3ced7a44ed8
+ winnt-x86_64 f1736f47de2a6fad1ff881e51c176f71db5dc2a5
+
S 2015-01-31 474b324
freebsd-x86_64 c5b55eb488790ff8425d74afa3b37c49517bc55f
linux-i386 319f2f3573c058cb2c4dfc75faaf8ea3ae86ef11
#![crate_type = "rlib"]
pub fn inner<F>(f: F) -> F {
- (move |:| f)()
+ (move || f)()
}
pub fn foo<T>() {
fn death() -> int { panic!() }
- debug!("{}", (|&:|{ death() })());
+ debug!("{}", (||{ death() })());
}
let attr = ecx.attribute(sp, self.args.clone());
let src = pprust::attribute_to_string(&attr);
- let interned = token::intern_and_get_ident(src.as_slice());
+ let interned = token::intern_and_get_ident(&src);
MacExpr::new(ecx.expr_str(sp, interned))
}
}
}
};
- let mut text = text.as_slice();
+ let mut text = &*text;
let mut total = 0u;
while !text.is_empty() {
match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
impl read for bool {
fn readMaybe(s: String) -> Option<bool> {
- match s.as_slice() {
+ match &*s {
"true" => Some(true),
"false" => Some(false),
_ => None
#[inline]
pub fn has_closures() -> uint {
let x = 1u;
- let mut f = move |&mut:| x;
+ let mut f = move || x;
let y = 1u;
- let g = |:| y;
+ let g = || y;
f() + g()
}
pub fn has_generic_closures<T: Add<Output=T> + Copy>(x: T, y: T) -> T {
- let mut f = move |&mut:| x;
- let g = |:| y;
+ let mut f = move || x;
+ let g = || y;
f() + g()
}
fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let n_keys = {
if args.len() == 2 {
args[1].parse::<uint>().unwrap()
{
println!(" Random integers:");
let mut map: BTreeMap<uint,uint> = BTreeMap::new();
- vector(&mut map, n_keys, rand.as_slice());
+ vector(&mut map, n_keys, &rand);
}
// FIXME: #9970
{
println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
- vector(&mut map, n_keys, rand.as_slice());
+ vector(&mut map, n_keys, &rand);
}
}
fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let num_keys = {
if args.len() == 2 {
args[1].parse::<uint>().unwrap()
macro_rules! bench {
($id:ident) =>
- (maybe_run_test(argv.as_slice(),
+ (maybe_run_test(&argv,
stringify!($id).to_string(),
$id))
}
v.extend(rv.into_iter());
} else {
let mut rv = rv.clone();
- rv.push_all(v.as_slice());
+ rv.push_all(&v);
v = rv;
}
i += 1;
let rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
if r.gen() {
let mut t = v.clone();
- t.push_all(rv.as_slice());
+ t.push_all(&rv);
v = t;
}
else {
let mut t = rv.clone();
- t.push_all(v.as_slice());
+ t.push_all(&v);
v = t;
}
i += 1;
for i in 0u..1500 {
let mut rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
if r.gen() {
- v.push_all(rv.as_slice());
+ v.push_all(&rv);
}
else {
swap(&mut v, &mut rv);
- v.push_all(rv.as_slice());
+ v.push_all(&rv);
}
}
}
let mut v : Vec<u8> = Vec::new();
for _ in 0u..20000 {
v.push('b' as u8);
- if str::from_utf8(v.as_slice()).is_err() {
+ if str::from_utf8(&v).is_err() {
panic!("from_utf8 panicked");
}
}
let mut v : Vec<u8> = Vec::new();
for _ in 0u..5000 {
v.push_all(s.as_bytes());
- if str::from_utf8(v.as_slice()).is_err() {
+ if str::from_utf8(&v).is_err() {
panic!("from_utf8 panicked");
}
}
};
println!("{:?}", args);
- run(args.as_slice());
+ run(&args);
}
};
println!("{:?}", args);
- run(args.as_slice());
+ run(&args);
}
fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let n = if args.len() == 3 {
args[1].parse::<uint>().unwrap()
} else {
fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let n = if args.len() == 2 {
args[1].parse::<uint>().unwrap()
} else {
fn main() {
let args = std::os::args();
- let args = args.as_slice();
+ let args = args;
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
let mut out = String::new();
for col in &set {
out.push(' ');
- out.push_str(format!("{:?}", col).as_slice());
+ out.push_str(&format!("{:?}", col));
}
out
}
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
- std::os::args().as_slice()
+ std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600u)
}
fn main() {
- let n = std::os::args().as_slice()
+ let n = std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(2i32);
let mut buf = repeat(0u8).take(alu_len + LINE_LEN).collect::<Vec<_>>();
let alu: &[u8] = self.alu.as_bytes();
- copy_memory(buf.as_mut_slice(), alu);
+ copy_memory(&mut buf, alu);
let buf_len = buf.len();
copy_memory(&mut buf[alu_len..buf_len],
&alu[..LINE_LEN]);
fn nextc(&mut self) -> u8 {
let r = self.rng(1.0);
- for a in &self.lookup[] {
+ for a in &self.lookup[..] {
if a.p >= r {
return a.c;
}
fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let n = if args.len() > 1 {
args[1].parse::<uint>().unwrap()
} else {
out.write_line(">TWO IUB ambiguity codes").unwrap();
let iub = sum_and_scale(&IUB);
- let mut random = RandomFasta::new(&mut out, iub.as_slice());
+ let mut random = RandomFasta::new(&mut out, &iub);
random.make(n * 3).unwrap();
random.out.write_line(">THREE Homo sapiens frequency").unwrap();
let homo_sapiens = sum_and_scale(&HOMO_SAPIENS);
- random.lookup = make_lookup(homo_sapiens.as_slice());
+ random.lookup = make_lookup(&homo_sapiens);
random.make(n * 5).unwrap();
random.out.write_str("\n").unwrap();
fn run<W: Writer>(writer: &mut W) -> std::old_io::IoResult<()> {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
let n = if os::getenv("RUST_BENCH").is_some() {
25000000
} else if args.len() <= 1u {
let mut buffer = String::new();
for &(ref k, v) in &pairs_sorted {
- buffer.push_str(format!("{:?} {:0.3}\n",
- k.to_ascii_uppercase(),
- v).as_slice());
+ buffer.push_str(&format!("{:?} {:0.3}\n",
+ k.to_ascii_uppercase(),
+ v));
}
return buffer
line = from_parent.recv().unwrap();
if line == Vec::new() { break; }
- carry.push_all(line.as_slice());
- carry = windows_with_carry(carry.as_slice(), sz, |window| {
+ carry.push_all(&line);
+ carry = windows_with_carry(&carry, sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
- vector.as_mut_slice().sort();
+ vector.sort();
let mut total_count = 0;
for &(count, _) in &vector {
for &(count, key) in vector.iter().rev() {
println!("{} {:.3}",
- key.unpack(frame).as_slice(),
+ key.unpack(frame),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
let nb_freqs: Vec<_> = (1u..3).map(|i| {
let input = input.clone();
- (i, Thread::scoped(move|| generate_frequencies(input.as_slice(), i)))
+ (i, Thread::scoped(move|| generate_frequencies(&input, i)))
}).collect();
let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
- Thread::scoped(move|| generate_frequencies(input.as_slice(), occ.len()))
+ Thread::scoped(move|| generate_frequencies(&input, occ.len()))
}).collect();
for (i, freq) in nb_freqs {
Thread::scoped(move|| {
let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8);
- let init_r_slice = vec_init_r.as_slice();
+ let init_r_slice = vec_init_r;
let start = i * chunk_size;
let end = if i == (WORKERS - 1) {
};
for &init_i in &vec_init_i[start..end] {
- write_line(init_i, init_r_slice, &mut res);
+ write_line(init_i, &init_r_slice, &mut res);
}
res
try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h));
for res in data {
- try!(out.write(res.join().ok().unwrap().as_slice()));
+ try!(out.write(&res.join().ok().unwrap()));
}
out.flush()
}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in 0..steps {
- let mut b_slice = bodies.as_mut_slice();
+ let mut b_slice: &mut [_] = bodies;
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
let argv = argv.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let opt_args = &argv[1..argv.len()];
- match getopts::getopts(opt_args, opts.as_slice()) {
+ match getopts::getopts(opt_args, &opts) {
Ok(ref m) => {
return Config {stress: m.opt_present("stress")}
}
fn main() {
let mut data = read_to_end(&mut stdin_raw()).unwrap();
let tables = &Tables::new();
- parallel(mut_dna_seqs(data.as_mut_slice()), |&: seq| reverse_complement(seq, tables));
- stdout_raw().write(data.as_mut_slice()).unwrap();
+ parallel(mut_dna_seqs(&mut data), |seq| reverse_complement(seq, tables));
+ stdout_raw().write(&data).unwrap();
}
let mut v = u.clone();
let mut tmp = v.clone();
for _ in 0u..10 {
- mult_AtAv(u.as_slice(), v.as_mut_slice(), tmp.as_mut_slice());
- mult_AtAv(v.as_slice(), u.as_mut_slice(), tmp.as_mut_slice());
+ mult_AtAv(&u, &mut v, &mut tmp);
+ mult_AtAv(&v, &mut u, &mut tmp);
}
- (dot(u.as_slice(), v.as_slice()) / dot(v.as_slice(), v.as_slice())).sqrt()
+ (dot(&u, &v) / dot(&v, &v)).sqrt()
}
fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) {
.take(10).collect::<Vec<_>>();
for line in reader.lines() {
let line = line.unwrap();
- let comps: Vec<&str> = line.as_slice()
+ let comps: Vec<&str> = line
.trim()
.split(',')
.collect();
fn main() {
let nyan : cat = cat(52us, 99);
- nyan.speak = |&:| println!("meow"); //~ ERROR attempted to take value of method
+ nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method
}
}
fn main() {
- let foo = |&:| false;
+ let foo = || false;
use bar::foo;
//~^ ERROR imports are not allowed after non-item statements
assert_eq!(foo(), false);
let mut p = vec!(1);
borrow(
- p.as_slice(),
+ &p,
|| p[0] = 5); //~ ERROR cannot borrow `p` as mutable
}
// Legal because the scope of the borrow does not include the
// modification:
let mut p = vec!(1);
- borrow(p.as_slice(), ||{});
+ borrow(&p, ||{});
p[0] = 5;
}
}
fn main() {
- let x = defer(vec!("Goodbye", "world!").as_slice());
+ let x = defer(&vec!("Goodbye", "world!"));
//~^ ERROR borrowed value does not live long enough
x.x[0];
}
}
fn test6() {
- let mut f = |&mut:| {};
- (|&mut:| {
+ let mut f = || {};
+ (|| {
f();
})();
}
fn test7() {
fn foo<F>(_: F) where F: FnMut(Box<FnMut(isize)>, isize) {}
- let mut f = |&mut: g: Box<FnMut(isize)>, b: isize| {};
+ let mut f = |g: Box<FnMut(isize)>, b: isize| {};
f(box |a| {
foo(f);
//~^ ERROR cannot move `f` into closure because it is borrowed
fn a() {
let mut x = 3;
- let c1 = |&mut:| x = 4;
- let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x`
+ let c1 = || x = 4;
+ let c2 = || x * 5; //~ ERROR cannot borrow `x`
}
fn b() {
let mut x = 3;
- let c1 = |&mut:| set(&mut x);
- let c2 = |&mut:| get(&x); //~ ERROR cannot borrow `x`
+ let c1 = || set(&mut x);
+ let c2 = || get(&x); //~ ERROR cannot borrow `x`
}
fn c() {
let mut x = 3;
- let c1 = |&mut:| set(&mut x);
- let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x`
+ let c1 = || set(&mut x);
+ let c2 = || x * 5; //~ ERROR cannot borrow `x`
}
fn d() {
let mut x = 3;
- let c2 = |&mut:| x * 5;
+ let c2 = || x * 5;
x = 5; //~ ERROR cannot assign
}
fn e() {
let mut x = 3;
- let c1 = |&mut:| get(&x);
+ let c1 = || get(&x);
x = 5; //~ ERROR cannot assign
}
fn f() {
let mut x = box 3;
- let c1 = |&mut:| get(&*x);
+ let c1 = || get(&*x);
*x = 5; //~ ERROR cannot assign
}
}
let mut x = box Foo { f: box 3 };
- let c1 = |&mut:| get(&*x.f);
+ let c1 = || get(&*x.f);
*x.f = 5; //~ ERROR cannot assign to `*x.f`
}
}
let mut x = box Foo { f: box 3 };
- let c1 = |&mut:| get(&*x.f);
- let c2 = |&mut:| *x.f = 5; //~ ERROR cannot borrow `x` as mutable
+ let c1 = || get(&*x.f);
+ let c2 = || *x.f = 5; //~ ERROR cannot borrow `x` as mutable
}
fn main() {
}
fn a(x: &isize) {
- let c1 = |&mut:| set(&mut *x);
+ let c1 = || set(&mut *x);
//~^ ERROR cannot borrow
- let c2 = |&mut:| set(&mut *x);
+ let c2 = || set(&mut *x);
//~^ ERROR cannot borrow
//~| ERROR closure requires unique access
}
#![feature(box_syntax)]
+fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
+
fn a() {
let mut x = 3;
- let c1 = |&mut:| x = 4;
- let c2 = |&mut:| x = 5; //~ ERROR cannot borrow `x` as mutable more than once
+ let c1 = to_fn_mut(|| x = 4);
+ let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
}
fn set(x: &mut isize) {
fn b() {
let mut x = 3;
- let c1 = |&mut:| set(&mut x);
- let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once
+ let c1 = to_fn_mut(|| set(&mut x));
+ let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
}
fn c() {
let mut x = 3;
- let c1 = |&mut:| x = 5;
- let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once
+ let c1 = to_fn_mut(|| x = 5);
+ let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
}
fn d() {
let mut x = 3;
- let c1 = |&mut:| x = 5;
- let c2 = |&mut:| { let _y = |&mut:| set(&mut x); }; // (nested closure)
+ let c1 = to_fn_mut(|| x = 5);
+ let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
}
}
let mut x = box Foo { f: box 3 };
- let c1 = |&mut:| set(&mut *x.f);
- let c2 = |&mut:| set(&mut *x.f);
+ let c1 = to_fn_mut(|| set(&mut *x.f));
+ let c2 = to_fn_mut(|| set(&mut *x.f));
//~^ ERROR cannot borrow `x` as mutable more than once
}
let mut this = &mut Foo {
x: 1,
};
- let mut r = |&mut:| {
+ let mut r = || {
let p = &this.x;
&mut this.x; //~ ERROR cannot borrow
};
}
fn a(x: &mut isize) {
- let c1 = |&mut:| get(x);
- let c2 = |&mut:| get(x);
+ let c1 = || get(x);
+ let c2 = || get(x);
}
fn b(x: &mut isize) {
- let c1 = |&mut:| get(x);
- let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x`
+ let c1 = || get(x);
+ let c2 = || set(x); //~ ERROR closure requires unique access to `x`
}
fn c(x: &mut isize) {
- let c1 = |&mut:| get(x);
- let c2 = |&mut:| { get(x); set(x); }; //~ ERROR closure requires unique access to `x`
+ let c1 = || get(x);
+ let c2 = || { get(x); set(x); }; //~ ERROR closure requires unique access to `x`
}
fn d(x: &mut isize) {
- let c1 = |&mut:| set(x);
- let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x`
+ let c1 = || set(x);
+ let c2 = || set(x); //~ ERROR closure requires unique access to `x`
}
fn e(x: &mut isize) {
- let c1 = |&mut:| x = panic!(); //~ ERROR closure cannot assign to immutable local variable
+ let c1 = || x = panic!(); //~ ERROR closure cannot assign to immutable local variable
}
fn main() {
fn main() {
let mut ptr = box Foo { x: 0 };
- let mut test = |&mut: foo: &Foo| {
+ let mut test = |foo: &Foo| {
ptr = box Foo { x: ptr.x + 1 };
};
test(&*ptr); //~ ERROR cannot borrow `*ptr`
// except according to those terms.
fn main() {
- let j = |&:| -> isize {
+ let j = || -> isize {
let i: isize;
i //~ ERROR use of possibly uninitialized variable: `i`
};
// except according to those terms.
fn main() {
- let f = |&:| -> isize {
+ let f = || -> isize {
let i: isize;
i //~ ERROR use of possibly uninitialized variable: `i`
};
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
- let x: &[Foo] = x.as_slice();
+ let x: &[Foo] = &x;
match x {
[_, tail..] => {
match tail {
fn main() {
let v = vec!(1, 2, 3);
- write(v.as_mut_slice()); //~ ERROR cannot borrow
+ write(&mut v); //~ ERROR cannot borrow
}
type Output = isize;
fn index<'a>(&'a self, z: &String) -> &'a isize {
- if z.as_slice() == "x" {
+ if *z == "x" {
&self.x
} else {
&self.y
type Output = isize;
fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
- if z.as_slice() == "x" {
+ if *z == "x" {
&mut self.x
} else {
&mut self.y
type Output = isize;
fn index<'a>(&'a self, z: &String) -> &'a isize {
- if z.as_slice() == "x" {
+ if *z == "x" {
&self.x
} else {
&self.y
type Output = isize;
fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
- if z.as_slice() == "x" {
+ if *z == "x" {
&mut self.x
} else {
&mut self.y
fn bar() {
// Original borrow ends at end of closure
- |&:| {
+ || {
let mut x = 1us;
let y = &mut x;
let z = &mut x; //~ ERROR cannot borrow
fn a<'a>() -> &'a [isize] {
let vec = vec!(1, 2, 3, 4);
- let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+ let vec: &[isize] = &vec; //~ ERROR does not live long enough
let tail = match vec {
[_, tail..] => tail,
_ => panic!("a")
fn b<'a>() -> &'a [isize] {
let vec = vec!(1, 2, 3, 4);
- let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+ let vec: &[isize] = &vec; //~ ERROR does not live long enough
let init = match vec {
[init.., _] => init,
_ => panic!("b")
fn c<'a>() -> &'a [isize] {
let vec = vec!(1, 2, 3, 4);
- let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+ let vec: &[isize] = &vec; //~ ERROR does not live long enough
let slice = match vec {
[_, slice.., _] => slice,
_ => panic!("c")
fn a() {
let mut v = vec!(1, 2, 3);
- let vb: &mut [isize] = v.as_mut_slice();
+ let vb: &mut [isize] = &mut v;
match vb {
[_a, tail..] => {
v.push(tail[0] + tail[1]); //~ ERROR cannot borrow
fn b() {
let mut vec = vec!(box 1, box 2, box 3);
- let vec: &mut [Box<isize>] = vec.as_mut_slice();
+ let vec: &mut [Box<isize>] = &mut vec;
match vec {
[_b..] => {
vec[0] = box 4; //~ ERROR cannot assign
fn c() {
let mut vec = vec!(box 1, box 2, box 3);
- let vec: &mut [Box<isize>] = vec.as_mut_slice();
+ let vec: &mut [Box<isize>] = &mut vec;
match vec {
[_a, //~ ERROR cannot move out
_b..] => { //~^ NOTE attempting to move value to here
fn d() {
let mut vec = vec!(box 1, box 2, box 3);
- let vec: &mut [Box<isize>] = vec.as_mut_slice();
+ let vec: &mut [Box<isize>] = &mut vec;
match vec {
[_a.., //~ ERROR cannot move out
_b] => {} //~ NOTE attempting to move value to here
fn e() {
let mut vec = vec!(box 1, box 2, box 3);
- let vec: &mut [Box<isize>] = vec.as_mut_slice();
+ let vec: &mut [Box<isize>] = &mut vec;
match vec {
[_a, _b, _c] => {} //~ ERROR cannot move out
//~^ NOTE attempting to move value to here
fn a<'a>() -> &'a isize {
let vec = vec!(1, 2, 3, 4);
- let vec: &[isize] = vec.as_slice(); //~ ERROR `vec` does not live long enough
+ let vec: &[isize] = &vec; //~ ERROR `vec` does not live long enough
let tail = match vec {
[_a, tail..] => &tail[0],
_ => panic!("foo")
fn main() {
let x = 1;
- to_fn_once(move|:| { x = 2; });
+ to_fn_once(move|| { x = 2; });
//~^ ERROR: cannot assign to immutable captured outer variable
let s = std::old_io::stdin();
- to_fn_once(move|:| { s.read_to_end(); });
+ to_fn_once(move|| { s.read_to_end(); });
//~^ ERROR: cannot borrow immutable captured outer variable
}
fn main() {
let string = "world!";
- let f = |&: s: &str| println!("{}{}", s, string);
+ let f = |s: &str| println!("{}{}", s, string);
call_bare(f) //~ ERROR mismatched types
}
#![deny(unreachable_code)]
fn main() {
- let x = |:| panic!();
+ let x = || panic!();
x();
std::io::println("Foo bar"); //~ ERROR: unreachable statement
}
fn has_uniq(x: String) {
wants_uniq(x);
- wants_slice(x.as_slice());
+ wants_slice(&*x);
}
fn has_slice(x: &str) {
wants_uniq(x); //~ ERROR mismatched types
- wants_slice(x);
+ wants_slice(x.as_slice());
}
fn main() {
fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {}
fn main() {
- let _: () = (box |:_: isize| {}) as Box<FnOnce(isize)>;
+ let _: () = (box |_: isize| {}) as Box<FnOnce(isize)>;
//~^ ERROR object-safe
//~| ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnOnce(isize)>`
//~| expected ()
//~| found box
- let _: () = (box |&:_: isize, isize| {}) as Box<Fn(isize, isize)>;
+ let _: () = (box |_: isize, isize| {}) as Box<Fn(isize, isize)>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::Fn(isize, isize)>`
//~| expected ()
//~| found box
- let _: () = (box |&mut:| -> isize unimplemented!()) as Box<FnMut() -> isize>;
+ let _: () = (box || -> isize unimplemented!()) as Box<FnMut() -> isize>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnMut() -> isize>`
}
fn g() {
- let _frob = |&: q: Box<isize>| { *q = 2; }; //~ ERROR cannot assign
+ let _frob = |q: Box<isize>| { *q = 2; }; //~ ERROR cannot assign
}
pub fn main() {
let v: Vec<isize> = vec!(0, 1, 2, 3, 4, 5);
let s: String = "abcdef".to_string();
- v.as_slice()[3us];
- v.as_slice()[3];
- v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
+ v[3us];
+ v[3];
+ v[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
//~^ ERROR the trait `core::ops::Index<u8>` is not implemented
- v.as_slice()[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
+ v[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
//~^ ERROR the trait `core::ops::Index<i8>` is not implemented
- v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
+ v[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
//~^ ERROR the trait `core::ops::Index<u32>` is not implemented
- v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
+ v[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
//~^ ERROR the trait `core::ops::Index<i32>` is not implemented
s.as_bytes()[3us];
s.as_bytes()[3];
fn main() {
let x = box 1;
- let f = move|:| {
+ let f = move|| {
let _a = x;
drop(x);
//~^ ERROR: use of moved value: `x`
fn main() {
let mut ptr = box Foo { x: 0 };
- let mut test = |&mut: foo: &Foo| {
+ let mut test = |foo: &Foo| {
println!("access {}", foo.x);
ptr = box Foo { x: ptr.x + 1 };
println!("access {}", foo.x);
fn main() {
let mut c = for_stdin();
let mut v = Vec::new();
- c.read_to(v.as_mut_slice());
+ c.read_to(v);
}
fn main() {
let mut v = vec!(1);
- let mut f = |&mut:| v.push(2);
+ let mut f = || v.push(2);
let _w = v; //~ ERROR: cannot move out of `v`
f();
fn main() {
let sl = vec![1,2,3];
- let v: isize = match sl.as_slice() {
+ let v: isize = match &*sl {
[] => 0,
[a,b,c] => 3,
[a, rest..] => a,
fn main() {
let name = "Foo";
- let x = Some(&[name.as_slice()]);
+ let x = Some(&[name]);
let msg = foo(x);
//~^ ERROR mismatched types
//~| expected `core::option::Option<&[&str]>`
// wrong arity.
fn _foo<F: Fn()> (f: F) {
- |&: t| f(t); //~ ERROR E0057
+ |t| f(t); //~ ERROR E0057
}
fn main() {}
fn main() {
let foo = B;
- let closure = |:| foo; //~ ERROR unable to infer enough type information
+ let closure = || foo; //~ ERROR unable to infer enough type information
}
#![feature(box_syntax)]
fn main() {
- (|&:| box *[0us].as_slice())();
+ (|| box *[0us].as_slice())();
//~^ ERROR cannot move out of borrowed content
//~^^ ERROR cannot move a value of type [usize]
}
impl Debug for Player {
fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
formatter.write_str("Player{ name:");
- formatter.write_str(self.name.as_slice());
+ formatter.write_str(&self.name);
formatter.write_str(" }");
Ok(())
}
}
}
fn main() {
- ["hi"].bind(|&mut: x| [x] );
+ ["hi"].bind(|x| [x] );
//~^ ERROR type `[&str; 1]` does not implement any method in scope named `bind`
}
fn main() {
let needlesArr: Vec<char> = vec!('a', 'f');
- needlesArr.iter().fold(|&: x, y| {
+ needlesArr.iter().fold(|x, y| {
});
//~^^ ERROR this function takes 2 parameters but 1 parameter was supplied
//
trait A {
fn a(&self) {
- |&:| self.b()
+ || self.b()
//~^ ERROR type `&Self` does not implement any method in scope named `b`
//~| ERROR mismatched types
//~| expected `()`
fn id<T>(t: T) -> T { t }
fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
- id(box |&mut:| *v) //~ ERROR cannot infer
+ id(box || *v) //~ ERROR cannot infer
}
fn main() {
// Regression test for issue #5239
fn main() {
- let x = |&: ref x: isize| -> isize { x += 1; };
+ let x = |ref x: isize| -> isize { x += 1; };
//~^ ERROR binary assignment operation `+=` cannot be applied to type `&isize`
}
fn main() {
let x : Box<usize> = box 9;
- let sq = |:| { *x * *x };
+ let sq = || { *x * *x };
twice(x); //~ ERROR: cannot move out of
invoke(sq);
pub fn remove_package_from_database() {
let mut lines_to_use: Vec<&CrateId> = Vec::new();
- let push_id = |&mut: installed_id: &CrateId| {
+ let push_id = |installed_id: &CrateId| {
lines_to_use.push(installed_id);
//~^ ERROR cannot infer an appropriate lifetime for automatic coercion due to
// conflicting requirements
_ => {}
}
- let x = |&: mut y: isize| 10; //~ ERROR: variable does not need to be mutable
+ let x = |mut y: isize| 10; //~ ERROR: variable does not need to be mutable
fn what(mut foo: isize) {} //~ ERROR: variable does not need to be mutable
// positive cases
_ => {}
}
- let x = |&mut: mut y: isize| y = 32;
+ let x = |mut y: isize| y = 32;
fn nothing(mut foo: isize) { foo = 37; }
// leading underscore should avoid the warning, just like the
if maybestr.is_none() {
"(none)"
} else {
- let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+ let s: &'a str = maybestr.as_ref().unwrap();
s
}
}
pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {
if maybestr.is_some() {
- let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+ let s: &'a str = maybestr.as_ref().unwrap();
s
} else {
"(none)"
if maybestr.is_none() {
"(none)"
} else {
- let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+ let s: &'a str = maybestr.as_ref().unwrap();
s //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting
}
}
pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
if maybestr.is_some() {
- let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+ let s: &'a str = maybestr.as_ref().unwrap();
s //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting
} else {
"(none)"
pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
Some(ref s) => {
- let s: &'a str = s.as_slice();
+ let s: &'a str = s;
s
}
None => "(none)",
match *maybestr {
None => "(none)",
Some(ref s) => {
- let s: &'a str = s.as_slice();
+ let s: &'a str = s;
s
}
}
match *maybestr {
None => "(none)",
Some(ref s) => {
- let s: &'a str = s.as_slice();
+ let s: &'a str = s;
s
//~^ ERROR cannot infer an appropriate lifetime
}
pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
match *maybestr {
Some(ref s) => {
- let s: &'a str = s.as_slice();
+ let s: &'a str = s;
s
//~^ ERROR cannot infer an appropriate lifetime
}
fn main() {
let x: Vec<(isize, isize)> = Vec::new();
- let x: &[(isize, isize)] = x.as_slice();
+ let x: &[(isize, isize)] = &x;
match x {
[a, (2, 3), _] => (),
[(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern
let x: Vec<String> = vec!["foo".to_string(),
"bar".to_string(),
"baz".to_string()];
- let x: &[String] = x.as_slice();
+ let x: &[String] = &x;
match x {
[a, _, _, ..] => { println!("{}", a); }
[_, _, _, _, _] => { } //~ ERROR unreachable pattern
}
let x: Vec<char> = vec!('a', 'b', 'c');
- let x: &[char] = x.as_slice();
+ let x: &[char] = &x;
match x {
['a', 'b', 'c', _tail..] => {}
['a', 'b', 'c'] => {} //~ ERROR unreachable pattern
fn f120() {
let mut x = vec!("hi".to_string(), "ho".to_string());
- x.as_mut_slice().swap(0, 1);
+ x.swap(0, 1);
touch(&x[0]);
touch(&x[1]);
}
(t::b, t::b) => {}
}
let vec = vec!(Some(42), None, Some(21));
- let vec: &[Option<isize>] = vec.as_slice();
+ let vec: &[Option<isize>] = &vec;
match vec { //~ ERROR non-exhaustive patterns: `[]` not covered
[Some(..), None, tail..] => {}
[Some(..), Some(..), tail..] => {}
[None] => {}
}
let vec = vec!(1);
- let vec: &[isize] = vec.as_slice();
+ let vec: &[isize] = &vec;
match vec {
[_, tail..] => (),
[] => ()
}
let vec = vec!(0.5f32);
- let vec: &[f32] = vec.as_slice();
+ let vec: &[f32] = &vec;
match vec { //~ ERROR non-exhaustive patterns: `[_, _, _, _]` not covered
[0.1, 0.2, 0.3] => (),
[0.1, 0.2] => (),
[] => ()
}
let vec = vec!(Some(42), None, Some(21));
- let vec: &[Option<isize>] = vec.as_slice();
+ let vec: &[Option<isize>] = &vec;
match vec {
[Some(..), None, tail..] => {}
[Some(..), Some(..), tail..] => {}
let foo = Foo { bar: [1u8, 2, 3, 4, 5], baz: 10i32 };
unsafe {
let oof: Oof<[u8; 5], i32> = mem::transmute(foo);
- println!("{:?} {:?}", &oof.rab[], oof.zab);
+ println!("{:?} {:?}", &oof.rab[..], oof.zab);
}
}
// except according to those terms.
fn main() {
- let f = |&: 3: isize| println!("hello");
+ let f = |3: isize| println!("hello");
//~^ ERROR refutable pattern in function argument: `_` not covered
f(4);
}
// except according to those terms.
fn call_rec<F>(mut f: F) -> usize where F: FnMut(usize) -> usize {
- (|&mut: x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f`
+ (|x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f`
}
fn main() {}
{
let c = 1;
let c_ref = &c; //~ ERROR `c` does not live long enough
- f = move |&mut: a: isize, b: isize| { a + b + *c_ref };
+ f = move |a: isize, b: isize| { a + b + *c_ref };
}
}
impl dog {
pub fn chase_cat(&mut self) {
- let _f = |&:| {
+ let _f = || {
let p: &'static mut usize = &mut self.food; //~ ERROR cannot infer
*p = 3us;
};
fn main() {
let mut x: Option<&isize> = None;
- with_int(&mut |&mut: y| x = Some(y)); //~ ERROR cannot infer
+ with_int(&mut |y| x = Some(y)); //~ ERROR cannot infer
}
fn main () {
let f : argparse::Flag = argparse::flag("flag", "My flag");
let updated_flag = f.set_desc("My new flag");
- assert_eq!(updated_flag.desc.as_slice(), "My new flag");
+ assert_eq!(updated_flag.desc, "My new flag");
}
fn main() {
let line = String::new();
- match [line.as_slice()] { //~ ERROR `line` does not live long enough
+ match [&*line] { //~ ERROR `line` does not live long enough
[ word ] => { assert_send(word); }
}
}
// Unboxed closure case
{
let mut x = 0us;
- let mut f = |&mut:| &mut x; //~ ERROR cannot infer
+ let mut f = || &mut x; //~ ERROR cannot infer
let x = f();
let y = f();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// Test slicing expr[..] is an error and gives a helpful error message.
+// Test slicing &expr[] is deprecated and gives a helpful error message.
+//
+// ignore-test
struct Foo;
fn main() {
let x = Foo;
- &x[..]; //~ ERROR incorrect slicing expression: `[..]`
- //~^ NOTE use `&expr[]` to construct a slice of the whole of expr
+ &x[]; //~ WARNING deprecated slicing syntax: `[]`
+ //~^ NOTE use `&expr[..]` to construct a slice of the whole of expr
+ //~^^ ERROR cannot index a value of type `Foo`
}
fn main() {
let x = Foo;
- &x[]; //~ ERROR cannot index a value of type `Foo`
+ &x[..]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..]; //~ ERROR cannot index a value of type `Foo`
&x[..Foo]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo`
fn main() {
let person = "Fred".to_string();
- let person: &str = person.as_slice(); //~ ERROR `person` does not live long enough
+ let person: &str = &person; //~ ERROR `person` does not live long enough
let s: Box<Trait<&'static str>> = box Struct { person: person };
}
fn main() {
let x = 0us;
- move |&mut:| x = 1; //~ ERROR cannot assign
- move |&mut:| set(&mut x); //~ ERROR cannot borrow
- move |:| x = 1; //~ ERROR cannot assign
- move |:| set(&mut x); //~ ERROR cannot borrow
- |&mut:| x = 1; //~ ERROR cannot assign
+ move || x = 1; //~ ERROR cannot assign
+ move || set(&mut x); //~ ERROR cannot borrow
+ move || x = 1; //~ ERROR cannot assign
+ move || set(&mut x); //~ ERROR cannot borrow
+ || x = 1; //~ ERROR cannot assign
// FIXME: this should be `cannot borrow` (issue #18330)
- |&mut:| set(&mut x); //~ ERROR cannot assign
- |:| x = 1; //~ ERROR cannot assign
+ || set(&mut x); //~ ERROR cannot assign
+ || x = 1; //~ ERROR cannot assign
// FIXME: this should be `cannot borrow` (issue #18330)
- |:| set(&mut x); //~ ERROR cannot assign
+ || set(&mut x); //~ ERROR cannot assign
}
fn main() {
let _f = {
let x = 0us;
- |:| x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
+ || x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
};
}
fn main() {
let mut x = 0us;
- let f = |:| x += 1;
+ let f = || x += 1;
let _y = x; //~ ERROR cannot use `x` because it was mutably borrowed
}
}
pub fn main() {
- doit(0, &|&: x, y| {
+ doit(0, &|x, y| {
x.set(y); //~ ERROR cannot infer
});
}
use std::ops::FnMut;
pub fn main() {
- let mut f = |&mut: x: isize, y: isize| -> isize { x + y };
+ let mut f = |x: isize, y: isize| -> isize { x + y };
let z = f(1us, 2); //~ ERROR mismatched types
println!("{}", z);
}
fn main() {
let mut x = 1;
//~^ ERROR: variable does not need to be mutable
- move|:| { println!("{}", x); };
+ move|| { println!("{}", x); };
}
fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) {
- let closure = |&: x, y| {
+ let closure = |x, y| {
zzz(); // #break
(y, x)
};
// Nothing to do here really, just make sure it compiles. See issue #8513.
fn main() {
- let _ = |&:|();
+ let _ = ||();
let _ = (1u..3).map(|_| 5);
}
zzz(); // #break
sentinel();
- let closure = |&: x: int| {
+ let closure = |x: int| {
zzz(); // #break
sentinel();
zzz(); // #break
sentinel();
- let unique_closure = |: x:int| {
+ let unique_closure = |x:int| {
zzz(); // #break
sentinel();
fn main() {
let x = C { θ: 0 };
- (|&: c: C| c.θ )(x);
+ (|c: C| c.θ )(x);
}
let fixed_size_vec2 = ([0u, 1u, 2u], 0i16);
let vec1 = vec![0u, 2u, 3u];
- let slice1 = vec1.as_slice();
+ let slice1 = &*vec1;
let vec2 = vec![Mod1::Variant2_2(Struct1)];
- let slice2 = vec2.as_slice();
+ let slice2 = &*vec2;
// Trait Objects
let box_trait = (box 0) as Box<Trait1>;
// how that maps to rustc's internal representation of these forms.
// Once closures have reached their 1.0 form, the tests below should
// probably be expanded.
- let closure1 = (|&: x:isize| {}, 0u);
- let closure2 = (|&: x:i8, y: f32| { (x as f32) + y }, 0u);
+ let closure1 = (|x:isize| {}, 0u);
+ let closure2 = (|x:i8, y: f32| { (x as f32) + y }, 0u);
zzz(); // #break
}
let struct_ref = &a_struct;
let owned = box 6;
- let mut closure = |&mut:| {
+ let mut closure = || {
let closure_local = 8;
- let mut nested_closure = |&mut:| {
+ let mut nested_closure = || {
zzz(); // #break
variable = constant + a_struct.a + struct_ref.a + *owned + closure_local;
};
let owned = box 5;
- let closure = move |:| {
+ let closure = move || {
zzz(); // #break
do_something(&constant, &a_struct.a, &*owned);
};
// The `self` argument of the following closure should be passed by value
// to FnOnce::call_once(self, args), which gets translated a bit differently
// than the regular case. Let's make sure this is supported too.
- let immedate_env = move |:| {
+ let immedate_env = move || {
zzz(); // #break
return constant2;
};
let owned = box 6;
{
- let mut first_closure = |&mut:| {
+ let mut first_closure = || {
zzz(); // #break
variable = constant + a_struct.a + struct_ref.a + *owned;
};
}
{
- let mut second_closure = |&mut:| {
+ let mut second_closure = || {
zzz(); // #break
variable = constant + a_struct.a + struct_ref.a + *owned;
};
idx as uint);
// This should panic.
- println!("ov3 0x%x", x.as_slice()[idx]);
+ println!("ov3 0x%x", x[idx]);
}
#[cfg(any(target_arch="x86_64", target_arch = "aarch64"))]
fn main() {
// This version just panics anyways, for symmetry on 64-bit hosts.
let x = vec!(1u,2u,3u);
- error!("ov3 0x%x", x.as_slice()[200]);
+ error!("ov3 0x%x", x[200]);
}
+// ignore-license
int foo() { return 0; }
+// ignore-license
int foo() { return 0; }
+// ignore-license
void foo();
int main() {
+// ignore-license
void foo();
int main() {
+// ignore-license
int foo() { return 0; }
+// ignore-license
int foo() { return 0; }
fn main() {
let args = os::args();
- let rustc = args[1].as_slice();
- let tmpdir = Path::new(args[2].as_slice());
+ let rustc = &args[1];
+ let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("broken.rs");
let _ = File::create(&main_file).unwrap()
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
- .arg(format!("{} {}",
- rustc,
- main_file.as_str()
- .unwrap()).as_slice())
+ .arg(&format!("{} {}",
+ rustc,
+ main_file.as_str()
+ .unwrap()))
.output().unwrap();
- let err = String::from_utf8_lossy(result.error.as_slice());
+ let err = String::from_utf8_lossy(&result.error);
// positive test so that this test will be updated when the
// compiler changes.
+// ignore-license
#include <stdint.h>
typedef struct TestStruct {
- uint8_t x;
- int32_t y;
+ uint8_t x;
+ int32_t y;
} TestStruct;
typedef int callback(TestStruct s);
uint32_t call(callback *c) {
- TestStruct s;
- s.x = 'a';
- s.y = 3;
+ TestStruct s;
+ s.x = 'a';
+ s.y = 3;
- return c(s);
+ return c(s);
}
+// ignore-license
#include <stdint.h>
uint32_t foo();
uint32_t bar();
uint32_t add() {
- return foo() + bar();
+ return foo() + bar();
}
+// ignore-license
// Pragma needed cause of gcc bug on windows: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991
#pragma pack(1)
struct __attribute__((packed)) Foo {
+// ignore-license
#include <stdio.h>
#include <stdint.h>
+// ignore-license
void foo();
void bar() { foo(); }
+// ignore-license
void foo() {}
+// ignore-license
void some_c_symbol() {}
+// ignore-license
void foo() {}
panic!("expected rustc path");
}
- let tmpdir = Path::new(args[1].as_slice());
+ let tmpdir = Path::new(&args[1]);
- let mut sysroot = Path::new(args[3].as_slice());
+ let mut sysroot = Path::new(&args[3]);
sysroot.pop();
sysroot.pop();
+// ignore-license
int should_return_one() { return 1; }
+// ignore-license
int should_return_one() { return 0; }
+// ignore-license
#include <stdint.h>
extern int32_t BAZ;
+// ignore-license
void foo();
int main() {
+// ignore-license
void bar() {}
+// ignore-license
void bar() {}
+// ignore-license
extern void foo();
void bar() { foo(); }
+// ignore-license
void foo() {}
fn Method(&self, x: u32) -> u32;
fn prov(&self, x: u32) -> u32 {
- println(x.to_string().as_slice());
+ println(&x.to_string());
42
}
fn provided_method(&self) -> u32 {
impl SomeTrait for some_fields {
fn Method(&self, x: u32) -> u32 {
- println(x.to_string().as_slice());
+ println(&x.to_string());
self.field1
}
}
impl some_fields {
fn stat(x: u32) -> u32 {
- println(x.to_string().as_slice());
+ println(&x.to_string());
42
}
fn stat2(x: &some_fields) -> u32 {
fn matchSomeEnum(val: SomeEnum) {
match val {
- SomeEnum::Ints(int1, int2) => { println((int1+int2).to_string().as_slice()); }
- SomeEnum::Floats(float1, float2) => { println((float2*float1).to_string().as_slice()); }
+ SomeEnum::Ints(int1, int2) => { println(&(int1+int2).to_string()); }
+ SomeEnum::Floats(float1, float2) => { println(&(float2*float1).to_string()); }
SomeEnum::Strings(_, _, s3) => { println(s3); }
SomeEnum::MyTypes(mt1, mt2) => {
- println((mt1.field1 - mt2.field1).to_string().as_slice());
+ println(&(mt1.field1 - mt2.field1).to_string());
}
}
}
fn matchSomeStructEnum(se: SomeStructEnum) {
match se {
- SomeStructEnum::EnumStruct{a:a, ..} => println(a.to_string().as_slice()),
- SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(f_2.field1.to_string().as_slice()),
- SomeStructEnum::EnumStruct3{f1, ..} => println(f1.field1.to_string().as_slice()),
+ SomeStructEnum::EnumStruct{a:a, ..} => println(&a.to_string()),
+ SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(&f_2.field1.to_string()),
+ SomeStructEnum::EnumStruct3{f1, ..} => println(&f1.field1.to_string()),
}
}
fn matchSomeStructEnum2(se: SomeStructEnum) {
use SomeStructEnum::*;
match se {
- EnumStruct{a: ref aaa, ..} => println(aaa.to_string().as_slice()),
- EnumStruct2{f1, f2: f2} => println(f1.field1.to_string().as_slice()),
- EnumStruct3{f1, f3: SomeEnum::Ints(_, _), f2} => println(f1.field1.to_string().as_slice()),
+ EnumStruct{a: ref aaa, ..} => println(&aaa.to_string()),
+ EnumStruct2{f1, f2: f2} => println(&f1.field1.to_string()),
+ EnumStruct3{f1, f3: SomeEnum::Ints(_, _), f2} => println(&f1.field1.to_string()),
_ => {},
}
}
fn hello<X: SomeTrait>((z, a) : (u32, String), ex: X) {
SameDir2::hello(43);
- println(yy.to_string().as_slice());
+ println(&yy.to_string());
let (x, y): (u32, u32) = (5, 3);
- println(x.to_string().as_slice());
- println(z.to_string().as_slice());
+ println(&x.to_string());
+ println(&z.to_string());
let x: u32 = x;
- println(x.to_string().as_slice());
+ println(&x.to_string());
let x = "hello";
println(x);
s4.provided_method();
s2.prov(45);
- let closure = |&: x: u32, s: &SomeTrait| {
+ let closure = |x: u32, s: &SomeTrait| {
s.Method(23);
return x + y;
};
let s3: some_fields = some_fields{ field1: 55};
let s4: msalias::nested_struct = sub::sub2::nested_struct{ field2: 55};
let s4: msalias::nested_struct = sub2::nested_struct{ field2: 55};
- println(s2.field1.to_string().as_slice());
+ println(&s2.field1.to_string());
let s5: MyType = box some_fields{ field1: 55};
let s = SameDir::SameStruct{name: "Bob".to_string()};
let s = SubDir::SubStruct{name:"Bob".to_string()};
fn main() {
let args = os::args();
- let rustc = args[1].as_slice();
- let tmpdir = Path::new(args[2].as_slice());
+ let rustc = &args[1];
+ let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
- .arg(format!("{} {}",
- rustc,
- main_file.as_str()
- .unwrap()).as_slice())
+ .arg(&format!("{} {}",
+ rustc,
+ main_file.as_str()
+ .unwrap()))
.output().unwrap();
- let err = String::from_utf8_lossy(result.error.as_slice());
+ let err = String::from_utf8_lossy(&result.error);
// positive test so that this test will be updated when the
// compiler changes.
fn main() {
let args = os::args();
- let rustc = args[1].as_slice();
- let tmpdir = Path::new(args[2].as_slice());
+ let rustc = &args[1];
+ let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("span_main.rs");
for _ in 0u..100 {
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
- .arg(format!("{} {}",
- rustc,
- main_file.as_str()
- .unwrap()).as_slice())
+ .arg(&format!("{} {}",
+ rustc,
+ main_file.as_str()
+ .unwrap()))
.output().unwrap();
- let err = String::from_utf8_lossy(result.error.as_slice());
+ let err = String::from_utf8_lossy(&result.error);
// the span should end the line (e.g no extra ~'s)
let expected_span = format!("^{}\n", repeat("~").take(n - 1)
.collect::<String>());
- assert!(err.contains(expected_span.as_slice()));
+ assert!(err.contains(&expected_span));
}
// Test multi-column characters and tabs
assert_eq!(length(x.clone()), x.len());
// Call a parameterized function, with type arguments that require
// a borrow
- assert_eq!(length::<int, &[int]>(x.as_slice()), x.len());
+ assert_eq!(length::<int, &[int]>(&*x), x.len());
// Now try it with a type that *needs* to be borrowed
let z = [0,1,2,3];
where A: MyEq<B>, Lhs: Deref<Target=[A]>
{
fn eq(&self, other: &[B; 0]) -> bool {
- MyEq::eq(&**self, other.as_slice())
+ MyEq::eq(&**self, other)
}
}
let mut rbml_w = EBwriter::Encoder::new(&mut wr);
a1.encode(&mut rbml_w);
- let d: serialize::rbml::Doc<'a> = EBDoc::new(&wr[]);
+ let d: serialize::rbml::Doc<'a> = EBDoc::new(&wr);
let mut decoder: EBReader::Decoder<'a> = EBreader::Decoder::new(d);
let a2: A = Decodable::decode(&mut decoder);
assert!(*a1 == a2);
let p = template.clone().arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
- let s = str::from_utf8(out.error.as_slice()).unwrap();
+ let s = str::from_utf8(&out.error).unwrap();
assert!(s.contains("stack backtrace") && s.contains("foo::h"),
"bad output: {}", s);
let p = template.clone().arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
- let s = str::from_utf8(out.error.as_slice()).unwrap();
+ let s = str::from_utf8(&out.error).unwrap();
assert!(!s.contains("stack backtrace") && !s.contains("foo::h"),
"bad output2: {}", s);
let p = template.clone().arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
- let s = str::from_utf8(out.error.as_slice()).unwrap();
+ let s = str::from_utf8(&out.error).unwrap();
// loosened the following from double::h to double:: due to
// spurious failures on mac, 32bit, optimized
assert!(s.contains("stack backtrace") && s.contains("double::"),
.env("RUST_BACKTRACE", "1").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
- let s = str::from_utf8(out.error.as_slice()).unwrap();
+ let s = str::from_utf8(&out.error).unwrap();
let mut i = 0;
for _ in 0..2 {
i += s[i + 10..].find_str("stack backtrace").unwrap() + 10;
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() >= 2 && args[1].as_slice() == "fail" {
+ let args = args;
+ if args.len() >= 2 && args[1] == "fail" {
foo();
- } else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
+ } else if args.len() >= 2 && args[1] == "double-fail" {
double();
} else {
- runtest(args[0].as_slice());
+ runtest(&args[0]);
}
}
}
fn g(mut x: String, y: String) -> String {
- x.push_str(y.as_slice());
+ x.push_str(&y);
x
}
fn main() {
call_f(f);
- assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()).as_slice(),
+ assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
"foobar");
}
pub fn main() {
fn f() -> int { return 7; }
assert_eq!(force(f), 7);
- let g = {|&:|force(f)};
+ let g = {||force(f)};
assert_eq!(g(), 7);
}
assert_eq!(!false, true);
let s = false.to_string();
- assert_eq!(s.as_slice(), "false");
+ assert_eq!(s, "false");
let s = true.to_string();
- assert_eq!(s.as_slice(), "true");
+ assert_eq!(s, "true");
assert!(true > false);
assert!(!(false > true));
match x {
F {f: ref mut v} => {
- impure(v.as_slice());
+ impure(v);
}
}
}
fn a() -> i32 {
let mut x = 3i32;
x += 1;
- let c1 = |&:| x * 4;
- let c2 = |&:| x * 5;
+ let c1 = || x * 4;
+ let c2 = || x * 5;
c1() * c2() * x
}
fn b() -> i32 {
let mut x = 3i32;
x += 1;
- let c1 = |&:| get(&x);
- let c2 = |&:| get(&x);
+ let c1 = || get(&x);
+ let c2 = || get(&x);
c1() * c2() * x
}
fn c() -> i32 {
let mut x = 3i32;
x += 1;
- let c1 = |&:| x * 5;
- let c2 = |&:| get(&x);
+ let c1 = || x * 5;
+ let c2 = || get(&x);
c1() * c2() * x
}
pub fn main() {
let bar = box 3;
- let h = |:| -> int *bar;
+ let h = || -> int *bar;
assert_eq!(h(), 3);
}
}
fn has_mut_vec(v: Vec<int> ) -> int {
- want_slice(v.as_slice())
+ want_slice(&v)
}
pub fn main() {
// except according to those terms.
fn foo(s: &String) -> bool {
- match s.as_slice() {
+ match &**s {
"kitty" => true,
_ => false
}
fn main() {
let mut sum = 0u;
let elems = [ 1u, 2, 3, 4, 5 ];
- each(&elems, |&mut: val: &uint| sum += *val);
+ each(&elems, |val: &uint| sum += *val);
assert_eq!(sum, 15);
}
pub fn fails() {
let x = 2;
let mut y = Vec::new();
- y.push(box Conzabble::Bickwick(do_it(get_bar(x).as_slice())));
+ y.push(box Conzabble::Bickwick(do_it(&get_bar(x))));
}
pub fn main() {
pub fn main() {
let args = os::args();
- let args = args.as_slice();
+ let args = args;
// Here, the rvalue `"signal".to_string()` requires cleanup. Older versions
// of the code had a problem that the cleanup scope for this
// expression was never evaluated, we wound up trying to clean
// uninitialized memory.
- if args.len() >= 2 && args[1].as_slice() == "signal" {
+ if args.len() >= 2 && args[1] == "signal" {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
}
// Test a rather underspecified example:
pub fn main() {
- let f = {|&: i| i};
+ let f = {|i| i};
assert_eq!(f(2), 2);
assert_eq!(f(5), 5);
}
fn use_slice_mut(_: &mut [u8]) {}
fn use_vec(mut v: Vec<u8>) {
- use_slice_mut(&mut v[]); // what you have to write today
- use_slice_mut(&mut v); // what you'd be able to write
+ use_slice_mut(&mut v[..]); // what you have to write today
+ use_slice_mut(&mut v); // what you'd be able to write
use_slice_mut(&mut &mut &mut v);
- use_slice(&v[]); // what you have to write today
+ use_slice(&v[..]); // what you have to write today
use_slice(&v); // what you'd be able to write
use_slice(&&&&&&v);
use_slice(&mut &&&&&v);
}
fn use_vec_ref(v: &Vec<u8>) {
- use_slice(&v[]); // what you have to write today
+ use_slice(&v[..]); // what you have to write today
use_slice(v); // what you'd be able to write
use_slice(&&&&&&v);
use_slice(&mut &&&&&v);
pub fn main() {
let mut the_vec = vec!(1u, 2, 3, 100);
- assert_eq!(the_vec.clone(), bar(the_vec.as_mut_slice()));
- assert_eq!(the_vec.clone(), bip(the_vec.as_slice()));
+ assert_eq!(the_vec.clone(), bar(&mut the_vec));
+ assert_eq!(the_vec.clone(), bip(&the_vec));
}
pub fn main() {
let mut the_vec = vec!(1, 2, 3, 100);
- bar(the_vec.as_mut_slice());
+ bar(&mut the_vec);
assert_eq!(the_vec, vec!(100, 3, 2, 1));
}
pub fn main() {
let mut the_vec = vec!(1, 2, 3, 100);
- bar(the_vec.as_mut_slice());
+ bar(&mut the_vec);
assert_eq!(the_vec, vec!(100, 3, 2, 1));
}
fn main() {
let obj = A { foo: box [true, false] };
let s = json::encode(&obj).unwrap();
- let obj2: A = json::decode(s.as_slice()).unwrap();
+ let obj2: A = json::decode(&s).unwrap();
assert!(obj.foo == obj2.foo);
}
bar: RefCell::new( A { baz: 2 } )
};
let s = json::encode(&obj).unwrap();
- let obj2: B = json::decode(s.as_slice()).unwrap();
+ let obj2: B = json::decode(&s).unwrap();
assert!(obj.foo.get() == obj2.foo.get());
assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz);
}
let mut w = Vec::new();
let mut e = Encoder::new(&mut w);
obj.encode(&mut e);
- let doc = rbml::Doc::new(&w[]);
+ let doc = rbml::Doc::new(&w);
let mut dec = Decoder::new(doc);
let obj2 = Decodable::decode(&mut dec);
assert!(obj == obj2);
}
pub fn main() {
- let wrapped = {|&:|wrapper3(chan::chan_t)};
+ let wrapped = {||wrapper3(chan::chan_t)};
wrapped();
}
// except according to those terms.
pub fn main() {
- let f = |&: (x, y): (int, int)| {
+ let f = |(x, y): (int, int)| {
assert_eq!(x, 1);
assert_eq!(y, 2);
};
pub fn main() {
// We should be able to type infer inside of ||s.
- let _f = |&:| {
+ let _f = || {
let i = 10;
};
}
pub fn main() {
let x = [1; 100];
let mut y = 0;
- for i in &x[] {
+ for i in &x[..] {
if y > 10 {
break;
}
let y = [2; 100];
let mut p = 0;
let mut q = 0;
- for i in &x[] {
- for j in &y[] {
+ for i in &x[..] {
+ for j in &y[..] {
p += *j;
}
q += *i + p;
pub fn main() {
let x = [1; 100];
let mut y = 0;
- for i in &x[] {
+ for i in &x[..] {
y += *i
}
assert!(y == 100);
let args = Vec::new();
let opts = vec!(optopt("b", "", "something", "SMTHNG"));
- match getopts(args.as_slice(), opts.as_slice()) {
+ match getopts(&args, &opts) {
Ok(ref m) =>
assert!(!m.opt_present("b")),
Err(ref f) => panic!("{}", *f)
ctrl_proto::mapper_done => { num_mappers -= 1; }
ctrl_proto::find_reducer(k, cc) => {
let mut c;
- match reducers.get(&str::from_utf8(
- k.as_slice()).unwrap().to_string()) {
+ match reducers.get(&str::from_utf8(&k).unwrap().to_string()) {
Some(&_c) => { c = _c; }
None => { c = 0; }
}
// cause a compilation error. Issue #18772.
fn adder(y: int) -> Box<Fn(int) -> int + 'static> {
- box move |&: x| y + x
+ box move |x| y + x
}
fn main() {}
}
fn main() {
- foo(|&: x: &int| println!("{}", *x));
+ foo(|x: &int| println!("{}", *x));
}
} else if let Foo::Two(_x) = foo {
panic!("bad pattern match");
} else if let Foo::Three(s, _) = foo {
- assert_eq!(s.as_slice(), "three");
+ assert_eq!(s, "three");
} else {
panic!("bad else");
}
}
macro_rules! t {
- ($a:expr, $b:expr) => { assert_eq!($a.as_slice(), $b) }
+ ($a:expr, $b:expr) => { assert_eq!($a, $b) }
}
pub fn main() {
}
fn good(a: &str, b: &str) {
- foo(&[a.as_slice(), b.as_slice()]);
+ foo(&[a, b]);
}
fn main() {}
pub fn main () {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "child" {
+ let args = args;
+ if args.len() > 1 && args[1] == "child" {
for _ in 0..1000 {
println!("hello?");
}
return;
}
- let mut p = process::Command::new(args[0].as_slice());
+ let mut p = process::Command::new(&args[0]);
p.arg("child").stdout(process::Ignored).stderr(process::Ignored);
println!("{:?}", p.spawn().unwrap().wait());
}
static NAME: &'static str = "hello world";
fn main() {
- match NAME.to_ascii_lowercase().as_slice() {
+ match &*NAME.to_ascii_lowercase() {
"foo" => {}
_ => {}
}
}
pub fn main() {
- let p = |:| ();
+ let p = || ();
f(p);
}
}
fn borrow<'a>(binding: &'a A) -> &'a str {
- match binding.a.as_slice() {
+ match &*binding.a {
"in" => "in_",
"ref" => "ref_",
ident => ident
// This test basically mimics how trace_macros! macro is implemented,
// which is a rare combination of vector patterns, multiple wild-card
// patterns and guard functions.
- let r = match [Foo::Bar(0, false)].as_slice() {
+ let r = match [Foo::Bar(0, false)] {
[Foo::Bar(_, pred)] if pred => 1,
[Foo::Bar(_, pred)] if !pred => 2,
_ => 0,
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "child" {
+ let args = args;
+ if args.len() > 1 && args[1] == "child" {
child();
} else {
parent();
fn parent() {
let args = os::args();
- let args = args.as_slice();
- let mut p = old_io::process::Command::new(args[0].as_slice())
+ let args = args;
+ let mut p = old_io::process::Command::new(&args[0])
.arg("child").spawn().unwrap();
p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap();
let out = p.wait_with_output().unwrap();
assert!(out.status.success());
- let s = str::from_utf8(out.output.as_slice()).unwrap();
+ let s = str::from_utf8(&out.output).unwrap();
assert_eq!(s, "test1\n\ntest2\n\ntest3\n");
}
}
fn get_s<'a>(&'a self) -> &'a str {
- self.s.as_slice()
+ &self.s
}
}
}
pub fn main() {
- assert_eq!("MyStruct".to_string(), do_stuff(|: s: MyStruct| format!("{:?}", s)));
+ assert_eq!("MyStruct".to_string(), do_stuff(|s: MyStruct| format!("{:?}", s)));
}
let obj = UnitLikeStruct;
let json_str: String = json::encode(&obj).unwrap();
- let json_object = json::from_str(json_str.as_slice());
+ let json_object = json::from_str(&json_str);
let mut decoder = json::Decoder::new(json_object.unwrap());
let mut decoded_obj: UnitLikeStruct = Decodable::decode(&mut decoder).unwrap();
fn main() {
let args = os::args();
- if args.len() > 1 && args[1].as_slice() == "child" {
+ if args.len() > 1 && args[1] == "child" {
return child()
}
fn test() {
let args = os::args();
- let mut p = Command::new(args[0].as_slice()).arg("child")
+ let mut p = Command::new(&args[0]).arg("child")
.stdin(process::Ignored)
.stdout(process::Ignored)
.stderr(process::Ignored)
pub fn main() {
- {|&: i| if 1 == i { }};
+ {|i| if 1 == i { }};
}
fn main() {
let s = "abcbdef";
- match_indices(s, |&mut: c: char| c == 'b')
+ match_indices(s, |c: char| c == 'b')
.collect::<Vec<(uint, uint)>>();
}
}
assert_eq!((x,y), (1,1));
let b: &[_] = &["out", "in"];
- assert_eq!(history.as_slice(), b);
+ assert_eq!(history, b);
}
}
}
let mut out = stdio::stdout();
out.write(&['a' as u8; 128 * 1024]).unwrap();
} else {
- let out = Command::new(args[0].as_slice()).arg("child").output();
+ let out = Command::new(&args[0]).arg("child").output();
let out = out.unwrap();
assert!(out.status.success());
}
fn main() {
// If we're the child, make sure we were invoked correctly
let args = os::args();
- if args.len() > 1 && args[1].as_slice() == "child" {
+ if args.len() > 1 && args[1] == "child" {
// FIXME: This should check the whole `args[0]` instead of just
// checking that it ends_with the executable name. This
// is needed because of Windows, which has a different behavior.
// Append the new directory to our own PATH.
let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new()));
path.push(child_dir.clone());
- let path = os::join_paths(path.as_slice()).unwrap();
+ let path = os::join_paths(&path).unwrap();
- let child_output = Command::new("mytest").env("PATH", path.as_slice())
+ let child_output = Command::new("mytest").env("PATH", path)
.arg("child")
.output().unwrap();
fn match_on_upvar() {
let mut foo = Some(box 8i32);
- let f = move|:| {
+ let f = move|| {
match foo {
None => {},
Some(x) => {
fn main() {
let mut buf = Vec::new();
- |&mut: c: u8| buf.push(c);
+ |c: u8| buf.push(c);
}
fn main() {
let y = 0u8;
- let closure = move |&: x| y + x;
+ let closure = move |x| y + x;
// Check that both closures are capturing by value
assert_eq!(1, mem::size_of_val(&closure));
impl<'a, I: 'a, O: 'a> Parser<'a, I, O> {
fn compose<K: 'a>(mut self, mut rhs: Parser<'a, O, K>) -> Parser<'a, I, K> {
Parser {
- parse: box move |&mut: x: I| {
+ parse: box move |x: I| {
match (self.parse)(x) {
Ok(r) => (rhs.parse)(r),
Err(e) => Err(e)
{
let mut test = X(box 5);
{
- let mut change = |&mut:| { *test = 10 };
+ let mut change = || { *test = 10 };
change();
}
assert_eq!(*test, 10);
pub fn main() {
let x = [1, 2, 3];
- let y = x.as_slice();
+ let y = x;
}
// There is currently no safe way to construct a `Box<str>`, so improvise
let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8];
let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) };
- assert_eq!(box_str.as_slice(), "hello");
+ assert_eq!(&*box_str, "hello");
f(box_str);
}
fn main() {
struct Symbol<'a, F: Fn(Vec<&'a str>) -> &'a str> { function: F }
- let f = |&: x: Vec<&str>| -> &str "foobar";
+ let f = |x: Vec<&str>| -> &str "foobar";
let sym = Symbol { function: f };
(sym.function)(vec![]);
}
}
pub fn main() {
- println!("num: {}", action(Thunk::with_arg(move |:u| u)));
+ println!("num: {}", action(Thunk::with_arg(move |u| u)));
}
E: Promisable + Clone,
F: FnOnce(&T) -> Result<T, E> + Send,
G: FnOnce(Result<T, E>) -> Result<T, E> {
- Thunk::with_arg(move |: result: Result<T, E>| {
+ Thunk::with_arg(move |result: Result<T, E>| {
match result {
Ok(ref t) => action(t),
Err(ref e) => Err(e.clone()),
const X: &'static str = "12345";
fn test(s: String) -> bool {
- match s.as_slice() {
+ match &*s {
X => true,
_ => false
}
fn main() {
let x = 2u8;
let y = 3u8;
- assert_eq!((move |:| x + y)(), 5);
+ assert_eq!((move || x + y)(), 5);
}
// Use different number of type parameters and closure type to trigger
// an obvious ICE when param environments are mixed up
pub fn outside<A,B>() {
- inside(|&:| {});
+ inside(|| {});
}
fn main() {
fn foo(&self);
fn bar(&self) {
- (|:| { self.foo() })()
+ (|| { self.foo() })()
}
}
extern crate "issue-18711" as issue;
fn main() {
- (|:| issue::inner(()))();
+ (|| issue::inner(()))();
}
struct LifetimeStruct<'a>;
fn main() {
- takes_hrtb_closure(|&mut: lts| println!("{:?}", lts));
+ takes_hrtb_closure(|lts| println!("{:?}", lts));
}
fn takes_hrtb_closure<F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) {
#![allow(non_camel_case_types)]
pub fn main() {
- let one = |&:| {
+ let one = || {
enum r { a };
r::a as uint
};
- let two = |&:| {
+ let two = || {
enum r { a };
r::a as uint
};
fn main() {
let x = 5us;
- let command = Arc::new(Box::new(|&:| { x*2 }));
+ let command = Arc::new(Box::new(|| { x*2 }));
assert_eq!(command(), 10);
}
--- /dev/null
+// Copyright 2015 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.
+
+static foo: [uint; 3] = [1, 2, 3];
+
+static slice_1: &'static [uint] = &foo;
+static slice_2: &'static [uint] = &foo;
+
+fn main() {}
type Connection = Box<FnMut(Vec<u8>) + 'static>;
fn f() -> Option<Connection> {
- let mock_connection: Connection = box |&mut: _| {};
+ let mock_connection: Connection = box |_| {};
Some(mock_connection)
}
pub fn main() {
let x = 1u;
- let y = |&:| x;
+ let y = || x;
let _z = y();
}
let mut table = HashMap::new();
table.insert("one".to_string(), 1);
table.insert("two".to_string(), 2);
- assert!(check_strs(format!("{:?}", table).as_slice(), "HashMap {\"one\": 1, \"two\": 2}") ||
- check_strs(format!("{:?}", table).as_slice(), "HashMap {\"two\": 2, \"one\": 1}"));
+ assert!(check_strs(&format!("{:?}", table), "HashMap {\"one\": 1, \"two\": 2}") ||
+ check_strs(&format!("{:?}", table), "HashMap {\"two\": 2, \"one\": 1}"));
}
fn test_ascii_art_ctor() {
let art = AsciiArt(3, 3, '*');
- assert!(check_strs(art.to_string().as_slice(), "...\n...\n..."));
+ assert!(check_strs(&art.to_string(), "...\n...\n..."));
}
art.add_pt(0, 0);
art.add_pt(0, -10);
art.add_pt(1, 2);
- assert!(check_strs(art.to_string().as_slice(), "*..\n...\n.*."));
+ assert!(check_strs(&art.to_string(), "*..\n...\n.*."));
}
let mut art = AsciiArt(4, 4, '*');
art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}});
art.add_point(Point {x: 2, y: 2});
- assert!(check_strs(art.to_string().as_slice(), "****\n*..*\n*.**\n****"));
+ assert!(check_strs(&art.to_string(), "****\n*..*\n*.**\n****"));
}
pub fn main() {
fn parse_args() -> String {
let args = ::std::os::args();
- let args = args.as_slice();
+ let args = args;
let mut n = 0;
while n < args.len() {
- match args[n].as_slice() {
+ match &*args[n] {
"-v" => (),
s => {
return s.to_string();
// Regression test for issue #5239
pub fn main() {
- let _f = |&: ref x: int| { *x };
+ let _f = |ref x: int| { *x };
let foo = 10;
assert!(_f(foo) == 10);
}
pub fn main() {
let s: String = "foobar".to_string();
- let mut t: &str = s.as_slice();
+ let mut t: &str = &s;
t = &t[0..3]; // for master: str::view(t, 0, 3) maybe
}
fn muli(x:int, y:int) -> int { x * y }
pub fn main() {
- let mut f = |&mut: x, y| muli(x, y);
+ let mut f = |x, y| muli(x, y);
{
let g = &mut f;
let h = g as &mut OpInt;
let _: () = f(| | { });
// empty block with no type info should compile too
let _ = f(||{});
- let _ = (|&:|{});
+ let _ = (||{});
}
let x = [(), ()];
let slice = &x[..1];
- 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(&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(&x[..], "[(), ()]".to_string());
}
pub fn light_fuse(fld: Box<bomb>) {
int3!();
- let f = |&:| {
+ let f = || {
int3!();
fld.boom(Ident_new()); // *** 1
};
a: &["test".to_string()],
b: Some(b),
};
- assert_eq!(a.b.as_ref().unwrap()[0].as_slice(), "foo");
+ assert_eq!(a.b.as_ref().unwrap()[0], "foo");
}
bar: box 32,
};
Thing1 {
- baz: Vec::new().as_slice(),
+ baz: &Vec::new(),
bar: box 32,
};
let _t2_fixed = Thing2 {
bar: 32,
};
Thing2 {
- baz: Vec::new().as_slice(),
+ baz: &Vec::new(),
bar: 32,
};
}
fn test_append() {
let mut s = String::new();
s.push_str("a");
- assert_eq!(s.as_slice(), "a");
+ assert_eq!(s, "a");
let mut s = String::from_str("a");
s.push_str("b");
println!("{}", s.clone());
- assert_eq!(s.as_slice(), "ab");
+ assert_eq!(s, "ab");
let mut s = String::from_str("c");
s.push_str("offee");
- assert!(s.as_slice() == "coffee");
+ assert!(s == "coffee");
s.push_str("&tea");
- assert!(s.as_slice() == "coffee&tea");
+ assert!(s == "coffee&tea");
}
pub fn main() {
pub fn main() {
let mut e = Refs{refs: vec!(), n: 0};
- let _f = |&:| println!("{}", e.n);
- let x: &[int] = e.refs.as_slice();
+ let _f = || println!("{}", e.n);
+ let x: &[int] = &e.refs;
assert_eq!(x.len(), 0);
}
fn foo() -> Box<FnMut() -> isize + 'static> {
let k = box 22;
let _u = A {a: k.clone()};
- let result = |&mut:| 22;
+ // FIXME(#16640) suffix in `22i` suffix shouldn't be necessary
+ let result = || 22i;
box result
}
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "child" {
+ let args = args;
+ if args.len() > 1 && args[1] == "child" {
debug!("foo");
debug!("bar");
return
}
- let p = Command::new(args[0].as_slice())
+ let p = Command::new(&args[0])
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
- let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
+ let mut lines = str::from_utf8(&p.error).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
}
match t::tag1("test".to_string()) {
t::tag2 => panic!(),
- t::tag1(ref s) if "test" != s.as_slice() => panic!(),
- t::tag1(ref s) if "test" == s.as_slice() => (),
+ t::tag1(ref s) if "test" != &**s => panic!(),
+ t::tag1(ref s) if "test" == &**s => (),
_ => panic!()
}
let mut buf = [0_u8; 6];
{
- let mut writer = buf.as_mut_slice();
+ let mut writer: &mut [_] = &mut buf;
writer.my_write(&[0, 1, 2]).unwrap();
writer.my_write(&[3, 4, 5]).unwrap();
}
sb.append("Hello, ");
sb.append("World!");
let str = to_string(sb);
- assert_eq!(str.as_slice(), "Hello, World!");
+ assert_eq!(str, "Hello, World!");
}
}
fn g() {
- let frob = |&: mut q: Box<int>| { *q = 2; assert!(*q == 2); };
+ let frob = |mut q: Box<int>| { *q = 2; assert!(*q == 2); };
let w = box 37;
frob(w);
x = 30;
assert_eq!(x, 30);
- (|&: A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
+ (|A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
}
let s = "\\{20}";
let mut correct_s = String::from_str("\\");
correct_s.push_str("{20}");
- assert_eq!(s, correct_s.as_slice());
+ assert_eq!(s, correct_s);
}
}
unsafe {
let expected: &[_] = &[1, 2, 3];
- assert_eq!(expected, ORDER.as_slice());
+ assert_eq!(expected, ORDER);
}
}
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "recurse" {
+ let args = args;
+ if args.len() > 1 && args[1] == "recurse" {
let _t = Thread::scoped(recurse);
} else {
- let recurse = Command::new(args[0].as_slice()).arg("recurse").output().unwrap();
+ let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
- let error = String::from_utf8_lossy(recurse.error.as_slice());
+ let error = String::from_utf8_lossy(&recurse.error);
println!("wut");
println!("`{}`", error);
assert!(error.contains("has overflowed its stack"));
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "recurse" {
+ if args.len() > 1 && args[1] == "recurse" {
recurse();
} else {
- let recurse = Command::new(args[0].as_slice()).arg("recurse").output().unwrap();
+ let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
- let error = String::from_utf8_lossy(recurse.error.as_slice());
+ let error = String::from_utf8_lossy(&recurse.error);
assert!(error.contains("has overflowed its stack"));
}
}
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "silent" {
+ let args = args;
+ if args.len() > 1 && args[1] == "silent" {
silent_recurse();
- } else if args.len() > 1 && args[1].as_slice() == "loud" {
+ } else if args.len() > 1 && args[1] == "loud" {
loud_recurse();
} else {
- let silent = Command::new(args[0].as_slice()).arg("silent").output().unwrap();
+ let silent = Command::new(&args[0]).arg("silent").output().unwrap();
assert!(!silent.status.success());
- let error = String::from_utf8_lossy(silent.error.as_slice());
+ let error = String::from_utf8_lossy(&silent.error);
assert!(error.contains("has overflowed its stack"));
- let loud = Command::new(args[0].as_slice()).arg("loud").output().unwrap();
+ let loud = Command::new(&args[0]).arg("loud").output().unwrap();
assert!(!loud.status.success());
- let error = String::from_utf8_lossy(silent.error.as_slice());
+ let error = String::from_utf8_lossy(&silent.error);
assert!(error.contains("has overflowed its stack"));
}
}
assert_eq!((i_value, *i.borrow()), (2, 5));
let s = Rc::new("foo".to_string());
- assert_eq!(s.as_slice(), "foo");
+ assert_eq!(&**s, "foo");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
mut_s.borrow_mut().push_str("bar");
// HACK assert_eq! would panic here because it stores the LHS and RHS in two locals.
- assert!(mut_s.borrow().as_slice() == "foobar");
- assert!(mut_s.borrow_mut().as_slice() == "foobar");
+ assert!(&**mut_s.borrow() == "foobar");
+ assert!(&**mut_s.borrow_mut() == "foobar");
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
p.borrow_mut().x = 3;
// Check the final states.
assert_eq!(*n, 2);
let expected: &[_] = &[1, 2];
- assert_eq!((*v).as_slice(), expected);
+ assert_eq!((*v), expected);
}
let s = Rc::new("foo".to_string());
assert_eq!(*s, "foo".to_string());
- assert_eq!((*s).as_slice(), "foo");
+ assert_eq!((*s), "foo");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
(*(*mut_s).borrow_mut()).push_str("bar");
// assert_eq! would panic here because it stores the LHS and RHS in two locals.
- assert!((*(*mut_s).borrow()).as_slice() == "foobar");
- assert!((*(*mut_s).borrow_mut()).as_slice() == "foobar");
+ assert!((*(*mut_s).borrow()) == "foobar");
+ assert!((*(*mut_s).borrow_mut()) == "foobar");
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
(*(*p).borrow_mut()).x = 3;
}
pub fn main() {
- let f = |&: (x, _): (int, int)| println!("{}", x + 1);
- let g = |&: Foo { x: x, y: _y }: Foo| println!("{}", x + 1);
+ let f = |(x, _): (int, int)| println!("{}", x + 1);
+ let g = |Foo { x: x, y: _y }: Foo| println!("{}", x + 1);
f((2, 3));
g(Foo { x: 1, y: 2 });
}
// restore original environment
match old_env {
None => os::unsetenv("RUN_TEST_NEW_ENV"),
- Some(val) => os::setenv("RUN_TEST_NEW_ENV", val.as_slice())
+ Some(val) => os::setenv("RUN_TEST_NEW_ENV", val)
}
let prog = cmd.spawn().unwrap();
let result = prog.wait_with_output().unwrap();
- let output = String::from_utf8_lossy(result.output.as_slice());
+ let output = String::from_utf8_lossy(&result.output);
assert!(!output.contains("RUN_TEST_NEW_ENV"),
"found RUN_TEST_NEW_ENV inside of:\n\n{}", output);
let p = Command::new(&child_path)
.arg(arg)
.cwd(&cwd)
- .env_set_all(my_env.as_slice())
+ .env_set_all(&my_env)
.spawn().unwrap().wait_with_output().unwrap();
// display the output
- assert!(old_io::stdout().write(p.output.as_slice()).is_ok());
- assert!(old_io::stderr().write(p.error.as_slice()).is_ok());
+ assert!(old_io::stdout().write(&p.output).is_ok());
+ assert!(old_io::stderr().write(&p.error).is_ok());
// make sure the child succeeded
assert!(p.status.success());
assert!(my_cwd.ends_with_path(&Path::new(child_dir)));
// check arguments
- assert_eq!(my_args[1].as_slice(), arg);
+ assert_eq!(&*my_args[1], arg);
// check environment variable
assert!(my_env.contains(&env));
// Test that range syntax works in return statements
fn return_range_to() -> ::std::ops::RangeTo<i32> { return ..1; }
+fn return_full_range() -> ::std::ops::RangeFull { return ..; }
pub fn main() {
let mut count = 0;
let x = [1]..[2];
assert!(x == (([1])..([2])));
+
+ let y = ..;
+ assert!(y == (..));
}
pub fn main() {
let x = vec!(1, 2, 3);
- let y = call_sum(x.as_slice());
+ let y = call_sum(&x);
println!("y=={}", y);
assert_eq!(y, 6);
unsafe fn test_triangle() -> bool {
static COUNT : uint = 16;
let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>();
- let ascend = ascend.as_mut_slice();
+ let ascend = &mut *ascend;
static ALIGN : uint = 1;
// Checks that `ascend` forms triangle of ascending size formed
}
}
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
test_1(ascend); // triangle -> square
test_2(ascend); // square -> triangle
test_3(ascend); // triangle -> square
assert!(old_size < new_size);
ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
}
}
assert!(new_size < old_size);
ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
}
}
assert!(old_size < new_size);
ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
}
}
assert!(new_size < old_size);
ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
- sanity_check(ascend.as_slice());
+ sanity_check(&*ascend);
}
}
}
pub fn main() {
let p = vec!(1,2,3,4,5);
- let r = foo(p.as_slice());
+ let r = foo(&p);
assert_eq!(r, 1);
let p = vec!(5,4,3,2,1);
- let r = foo(p.as_slice());
+ let r = foo(&p);
assert_eq!(r, 5);
}
let mut i = 3i32;
assert_eq!(i, 3);
{
- let cl = |&mut:| i += 1;
+ let cl = || i += 1;
let mut cl_box = box_it(box cl);
cl_box.cl.call_mut(());
}
pub fn main() {
let v = vec!(1,2,3);
- both(v.as_slice());
+ both(&v);
}
pub fn main() {
let v = vec!(1, 2, 3);
- let x = view(v.as_slice());
- let y = view(x.as_slice());
+ let x = view(&v);
+ let y = view(x);
assert!((v[0] == x[0]) && (v[0] == y[0]));
}
pub fn main() {
fn explicit() {
fn test<F>(_x: Option<Box<F>>) where F: FnMut(Box<for<'a> FnMut(&'a int)>) {}
- test(Some(box |&mut: _f: Box<for<'a> FnMut(&'a int)>| {}));
+ test(Some(box |_f: Box<for<'a> FnMut(&'a int)>| {}));
}
// The code below is shorthand for the code above (and more likely
// to represent what one encounters in practice).
fn implicit() {
fn test<F>(_x: Option<Box<F>>) where F: FnMut(Box< FnMut(& int)>) {}
- test(Some(box |&mut: _f: Box< FnMut(& int)>| {}));
+ test(Some(box |_f: Box< FnMut(& int)>| {}));
}
explicit();
use TypeStructure::{TypeInt, TypeFunction};
use AstKind::{ExprInt, ExprVar, ExprLambda};
-use arena::Arena;
+use arena::TypedArena;
use std::collections::HashMap;
use std::mem;
impl<'tcx> Eq for TypeStructure<'tcx> {}
+type TyArena<'tcx> = TypedArena<TypeStructure<'tcx>>;
+type AstArena<'ast> = TypedArena<AstStructure<'ast>>;
+
struct TypeContext<'tcx, 'ast> {
- ty_arena: &'tcx Arena,
+ ty_arena: &'tcx TyArena<'tcx>,
types: Vec<Type<'tcx>> ,
type_table: HashMap<NodeId, Type<'tcx>>,
- ast_arena: &'ast Arena,
+ ast_arena: &'ast AstArena<'ast>,
ast_counter: uint,
}
impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
- fn new(ty_arena: &'tcx Arena, ast_arena: &'ast Arena)
+ fn new(ty_arena: &'tcx TyArena<'tcx>, ast_arena: &'ast AstArena<'ast>)
-> TypeContext<'tcx, 'ast> {
TypeContext { ty_arena: ty_arena,
types: Vec::new(),
}
}
- let ty = self.ty_arena.alloc(|| s);
+ let ty = self.ty_arena.alloc(s);
self.types.push(ty);
ty
}
fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
let id = self.ast_counter;
self.ast_counter += 1;
- self.ast_arena.alloc(|| AstStructure { id: NodeId {id:id}, kind: a })
+ self.ast_arena.alloc(AstStructure { id: NodeId {id:id}, kind: a })
}
}
}
pub fn main() {
- let ty_arena = arena::Arena::new();
- let ast_arena = arena::Arena::new();
+ let ty_arena = TypedArena::new();
+ let ast_arena = TypedArena::new();
let mut tcx = TypeContext::new(&ty_arena, &ast_arena);
let ast = tcx.ast(ExprInt);
let ty = compute_types(&mut tcx, ast);
}
pub fn main() {
- let cl_box = box_it(box |&mut:| println!("Hello, world!"));
+ let cl_box = box_it(box || println!("Hello, world!"));
call_static_closure(cl_box);
}
let y = [ 0; 1 ];
print!("[");
- for xi in &x[] {
- print!("{:?}, ", &xi[]);
+ for xi in &x[..] {
+ print!("{:?}, ", &xi[..]);
}
println!("]");
- println!("{:?}", &y[]);
+ println!("{:?}", &y[..]);
}
static mut calls: uint = 0;
fn surrounding() {
- let return_works = |&: n: int| {
+ let return_works = |n: int| {
unsafe { calls += 1 }
if n >= 0 { return; }
return_works(10);
return_works(20);
- let return_works_proc = |: n: int| {
+ let return_works_proc = |n: int| {
unsafe { calls += 1 }
if n >= 0 { return; }
ffi::c_str_to_bytes(&ptr).to_vec()
}).collect::<Vec<_>>()
};
- let me = args[0].as_slice();
+ let me = &*args[0];
let x: &[u8] = &[1u8];
pass(Command::new(me).arg(x).output().unwrap());
fn pass(output: ProcessOutput) {
if !output.status.success() {
- println!("{:?}", str::from_utf8(output.output.as_slice()));
- println!("{:?}", str::from_utf8(output.error.as_slice()));
+ println!("{:?}", str::from_utf8(&output.output));
+ println!("{:?}", str::from_utf8(&output.error));
}
}
info!("bar foo");
});
- assert_eq!(rx.recv().unwrap().as_slice(), "foo");
- assert_eq!(rx.recv().unwrap().as_slice(), "foo bar");
- assert_eq!(rx.recv().unwrap().as_slice(), "bar foo");
+ assert_eq!(rx.recv().unwrap(), "foo");
+ assert_eq!(rx.recv().unwrap(), "foo bar");
+ assert_eq!(rx.recv().unwrap(), "bar foo");
assert!(rx.recv().is_err());
}
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "segfault" {
+ if args.len() > 1 && args[1] == "segfault" {
unsafe { *(0 as *mut int) = 1 }; // trigger a segfault
} else {
- let segfault = Command::new(args[0].as_slice()).arg("segfault").output().unwrap();
+ let segfault = Command::new(&args[0]).arg("segfault").output().unwrap();
assert!(!segfault.status.success());
- let error = String::from_utf8_lossy(segfault.error.as_slice());
+ let error = String::from_utf8_lossy(&segfault.error);
assert!(!error.contains("has overflowed its stack"));
}
}
fn test05() {
let three = box 3;
- let fn_to_send = move|: n:int| {
+ let fn_to_send = move|n:int| {
println!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
pub fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() >= 2 && args[1].as_slice() == "signal" {
+ let args = args;
+ if args.len() >= 2 && args[1] == "signal" {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
- let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap();
+ let status = Command::new(&args[0]).arg("signal").status().unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
fn main() {
let args = os::args();
- let args = args.as_slice();
- if args.len() > 1 && args[1].as_slice() == "test" {
+ let args = args;
+ if args.len() > 1 && args[1] == "test" {
return test();
}
- let mut p = Command::new(args[0].as_slice())
+ let mut p = Command::new(&args[0])
.arg("test").spawn().unwrap();
assert!(p.wait().unwrap().success());
}
fn main() {
let x: &[int] = &[1, 2, 3, 4, 5];
let cmp: &[int] = &[1, 2, 3, 4, 5];
- assert!(&x[] == cmp);
+ assert!(&x[..] == cmp);
let cmp: &[int] = &[3, 4, 5];
assert!(&x[2..] == cmp);
let cmp: &[int] = &[1, 2, 3];
let x: Vec<int> = vec![1, 2, 3, 4, 5];
let cmp: &[int] = &[1, 2, 3, 4, 5];
- assert!(&x[] == cmp);
+ assert!(&x[..] == cmp);
let cmp: &[int] = &[3, 4, 5];
assert!(&x[2..] == cmp);
let cmp: &[int] = &[1, 2, 3];
let x: &mut [int] = &mut [1, 2, 3, 4, 5];
{
let cmp: &mut [int] = &mut [1, 2, 3, 4, 5];
- assert!(&mut x[] == cmp);
+ assert!(&mut x[..] == cmp);
}
{
let cmp: &mut [int] = &mut [3, 4, 5];
let mut x: Vec<int> = vec![1, 2, 3, 4, 5];
{
let cmp: &mut [int] = &mut [1, 2, 3, 4, 5];
- assert!(&mut x[] == cmp);
+ assert!(&mut x[..] == cmp);
}
{
let cmp: &mut [int] = &mut [3, 4, 5];
fn main() {
let mut x = Foo;
- &x[];
+ &x[..];
&x[Foo..];
&x[..Foo];
&x[Foo..Foo];
- &mut x[];
+ &mut x[..];
&mut x[Foo..];
&mut x[..Foo];
&mut x[Foo..Foo];
static S: $t = $e;
let v: $t = $e;
assert_eq!(S, v);
- assert_eq!(format!("{:?}", v).as_slice(), $s);
- assert_eq!(format!("{:?}", S).as_slice(), $s);
+ assert_eq!(format!("{:?}", v), $s);
+ assert_eq!(format!("{:?}", S), $s);
});*
}}
}
pub fn main() {
let mut a: Vec<int> = vec!(0, 1, 2, 3, 4, 5, 6);
- a.as_mut_slice().swap(2, 4);
+ a.swap(2, 4);
assert_eq!(a[2], 4);
assert_eq!(a[4], 2);
let mut n = 42;
fn test_rm_tempdir() {
let (tx, rx) = channel();
- let f = move|:| -> () {
+ let f = move|| -> () {
let tmp = TempDir::new("test_rm_tempdir").unwrap();
tx.send(tmp.path().clone()).unwrap();
panic!("panic to unwind past `tmp`");
let tmp = TempDir::new("test_rm_tempdir").unwrap();
let path = tmp.path().clone();
- let f = move|:| -> () {
+ let f = move|| -> () {
let _tmp = tmp;
panic!("panic to unwind past `tmp`");
};
let path;
{
- let f = move|:| {
+ let f = move || {
TempDir::new("test_rm_tempdir").unwrap()
};
- let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
+ // FIXME(#16640) `: TempDir` annotation shouldn't be necessary
+ let tmp: TempDir = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
}
fn test_rm_tempdir_close() {
let (tx, rx) = channel();
- let f = move|:| -> () {
+ let f = move|| -> () {
let tmp = TempDir::new("test_rm_tempdir").unwrap();
tx.send(tmp.path().clone()).unwrap();
tmp.close();
let tmp = TempDir::new("test_rm_tempdir").unwrap();
let path = tmp.path().clone();
- let f = move|:| -> () {
+ let f = move|| -> () {
let tmp = tmp;
tmp.close();
panic!("panic when unwinding past `tmp`");
let path;
{
- let f = move|:| {
+ let f = move || {
TempDir::new("test_rm_tempdir").unwrap()
};
- let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
+ // FIXME(#16640) `: TempDir` annotation shouldn't be necessary
+ let tmp: TempDir = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
tmp.close();
}
impl Pet for Catte {
- fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+ fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
- fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+ fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
- fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+ fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
// Note that every unboxed closure has its own anonymous type,
// so no two IDs should equal each other, even when compatible
{
- let a = id(|&: _: &int, _: &int| {});
- let b = id(|&: _: &int, _: &int| {});
+ let a = id(|_: &int, _: &int| {});
+ let b = id(|_: &int, _: &int| {});
assert!(a != b);
}
pub fn main() {
let x: Vec<_> = (0u..5).collect();
let expected: &[uint] = &[0,1,2,3,4];
- assert_eq!(x.as_slice(), expected);
+ assert_eq!(x, expected);
let x = (0u..5).collect::<Vec<_>>();
- assert_eq!(x.as_slice(), expected);
+ assert_eq!(x, expected);
let y: _ = "hello";
assert_eq!(y.len(), 5);
fn main() {
let z: int = 7;
- assert_eq!(a(move |&: x: int, y| x + y + z), 10);
- assert_eq!(b(move |&mut: x: int, y| x + y + z), 14);
- assert_eq!(c(move |: x: int, y| x + y + z), 18);
+ assert_eq!(a(move |x: int, y| x + y + z), 10);
+ assert_eq!(b(move |x: int, y| x + y + z), 14);
+ assert_eq!(c(move |x: int, y| x + y + z), 18);
}
use std::ops::FnMut;
fn make_adder(x: i32) -> Box<FnMut(i32)->i32+'static> {
- (box move |&mut: y: i32| -> i32 { x + y }) as
+ (box move |y: i32| -> i32 { x + y }) as
Box<FnMut(i32)->i32+'static>
}
let mut x = 0u;
let y = 2u;
- call_fn(|&:| assert_eq!(x, 0));
- call_fn_mut(|&mut:| x += y);
- call_fn_once(|:| x += y);
+ call_fn(|| assert_eq!(x, 0));
+ call_fn_mut(|| x += y);
+ call_fn_once(|| x += y);
assert_eq!(x, y * 2);
}
#![feature(unboxed_closures)]
fn main() {
- let mut unboxed = |&mut:| {};
+ let mut unboxed = || {};
unboxed();
}
fn test_fn() {
{
- a(move |&: a: int, b| { a + b });
+ a(move |a: int, b| { a + b });
}
assert_eq!(drop_count(), 0);
{
let z = &Droppable::new();
- a(move |&: a: int, b| { z; a + b });
+ a(move |a: int, b| { z; a + b });
assert_eq!(drop_count(), 0);
}
assert_eq!(drop_count(), 1);
{
let z = &Droppable::new();
let zz = &Droppable::new();
- a(move |&: a: int, b| { z; zz; a + b });
+ a(move |a: int, b| { z; zz; a + b });
assert_eq!(drop_count(), 1);
}
assert_eq!(drop_count(), 3);
fn test_fn_mut() {
{
- b(move |&mut: a: int, b| { a + b });
+ b(move |a: int, b| { a + b });
}
assert_eq!(drop_count(), 3);
{
let z = &Droppable::new();
- b(move |&mut: a: int, b| { z; a + b });
+ b(move |a: int, b| { z; a + b });
assert_eq!(drop_count(), 3);
}
assert_eq!(drop_count(), 4);
{
let z = &Droppable::new();
let zz = &Droppable::new();
- b(move |&mut: a: int, b| { z; zz; a + b });
+ b(move |a: int, b| { z; zz; a + b });
assert_eq!(drop_count(), 4);
}
assert_eq!(drop_count(), 6);
fn test_fn_once() {
{
- c(move |: a: int, b| { a + b });
+ c(move |a: int, b| { a + b });
}
assert_eq!(drop_count(), 6);
{
let z = Droppable::new();
- c(move |: a: int, b| { z; a + b });
+ c(move |a: int, b| { z; a + b });
assert_eq!(drop_count(), 7);
}
assert_eq!(drop_count(), 7);
{
let z = Droppable::new();
let zz = Droppable::new();
- c(move |: a: int, b| { z; zz; a + b });
+ c(move |a: int, b| { z; zz; a + b });
assert_eq!(drop_count(), 9);
}
assert_eq!(drop_count(), 9);
}
pub fn main() {
- let f = |&mut: x: i32, y: i32| -> i32 { x + y };
+ let f = |x: i32, y: i32| -> i32 { x + y };
let z = call_it(3, f);
println!("{}", z);
assert_eq!(z, 5);
}
pub fn main() {
- doit(0, &|&: x /*: int*/ | { x.to_int(); });
+ doit(0, &|x /*: int*/ | { x.to_int(); });
}
fn doit<T>(val: T, f: &Fn(T)) { f.call((val,)) }
pub fn main() {
- doit(0, &|&: x /*: int*/ | { x.to_int(); });
+ doit(0, &|x /*: int*/ | { x.to_int(); });
}
}
pub fn main() {
- doit(0, &|&: x /*: int*/ | { x.to_int(); });
+ doit(0, &|x /*: int*/ | { x.to_int(); });
}
fn main(){
fn bar<'a, T:Clone+'a> (t: T) -> Box<FnMut()->T + 'a> {
- box move |&mut:| t.clone()
+ box move || t.clone()
}
let mut f = bar(42_u32);
fn main() {
{
let mut x = 0u;
- move |&mut:| x += 1;
+ move || x += 1;
}
{
let mut x = 0u;
- move |:| x += 1;
+ move || x += 1;
}
{
let mut x = 0u;
- move |&mut:| set(&mut x);
+ move || set(&mut x);
}
{
let mut x = 0u;
- move |:| set(&mut x);
+ move || set(&mut x);
}
}
#![feature(unboxed_closures)]
fn main() {
- let task: Box<Fn(int) -> int> = box |&: x| x;
+ let task: Box<Fn(int) -> int> = box |x| x;
task.call((0, ));
- let mut task: Box<FnMut(int) -> int> = box |&mut: x| x;
+ let mut task: Box<FnMut(int) -> int> = box |x| x;
task(0);
- call(|:x| x, 22);
+ call(|x| x, 22);
}
fn call<F:FnOnce(int) -> int>(f: F, x: int) -> int {
use std::ops::FnMut;
pub fn main() {
- let mut f = |&mut: x: int, y: int| -> int { x + y };
+ let mut f = |x: int, y: int| -> int { x + y };
let z = f(1, 2);
assert_eq!(z, 3);
}
fn main() {
let z = 10;
- assert_eq!(a(move |&: x: int, y| x + y + z), 13);
- assert_eq!(b(move |&mut: x: int, y| x + y + z), 17);
- assert_eq!(c(move |: x: int, y| x + y + z), 21);
+ assert_eq!(a(move |x: int, y| x + y + z), 13);
+ assert_eq!(b(move |x: int, y| x + y + z), 17);
+ assert_eq!(c(move |x: int, y| x + y + z), 21);
}
#![feature(unboxed_closures)]
fn main() {
- let onetime = |: x| x;
+ let onetime = |x| x;
onetime(0);
}
pub fn main() {
let mut a = 7u;
let b = &mut a;
- replace_map(b, |: x: uint| x * 2);
+ replace_map(b, |x: uint| x * 2);
assert_eq!(*b, 14u);
}
}).join();
let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap();
- assert_eq!(s.as_slice(), "This panic should happen.");
+ assert_eq!(&**s, "This panic should happen.");
}
pub fn main() {
let _x = box 1;
- let lam_move = |&:| {};
+ let lam_move = || {};
lam_move();
}
let a: Vec<int> = vec!(1, 2, 3, 4, 5);
let b: Vec<int> = vec!(6, 7, 8, 9, 0);
let mut v: Vec<int> = a;
- v.push_all(b.as_slice());
+ v.push_all(&b);
println!("{}", v[9]);
assert_eq!(v[0], 1);
assert_eq!(v[7], 8);
// work out the total number of comparisons required to sort
// this array...
let mut count = 0us;
- main.clone().as_mut_slice().sort_by(|a, b| { count += 1; a.cmp(b) });
+ main.clone().sort_by(|a, b| { count += 1; a.cmp(b) });
// ... and then panic on each and every single one.
for panic_countdown in 0..count {
let _ = Thread::scoped(move|| {
let mut v = v;
let mut panic_countdown = panic_countdown;
- v.as_mut_slice().sort_by(|a, b| {
+ v.sort_by(|a, b| {
if panic_countdown == 0 {
panic!()
}
// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
let ps_cmd_output = Command::new("ps").args(&["-A", "-o", "pid,ppid,args"]).output().unwrap();
- let ps_output = String::from_utf8_lossy(ps_cmd_output.output.as_slice());
+ let ps_output = String::from_utf8_lossy(&ps_cmd_output.output);
for (line_no, line) in ps_output.split('\n').enumerate() {
if 0 < line_no && 0 < line.len() &&
let too_long = format!("/NoSuchCommand{:0300}", 0u8);
let _failures = (0..100).map(|_| {
- let cmd = Command::new(too_long.as_slice());
+ let cmd = Command::new(&too_long);
let failed = cmd.spawn();
assert!(failed.is_err(), "Make sure the command fails to spawn(): {:?}", cmd);
failed
return while !x.get() { x.set(true); };
}
let i = &Cell::new(false);
- let dont = {|&:|the(i)};
+ let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn main() {
// ICE trigger
- warm_up(|&: b: &mut Bencher| () );
+ warm_up(|b: &mut Bencher| () );
// OK
- warm_up(|&: b| () );
+ warm_up(|b| () );
}