]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #14514 : Randati/rust/patch-1, r=huonw
authorbors <bors@rust-lang.org>
Fri, 30 May 2014 07:31:44 +0000 (00:31 -0700)
committerbors <bors@rust-lang.org>
Fri, 30 May 2014 07:31:44 +0000 (00:31 -0700)
178 files changed:
.gitignore
mk/crates.mk
src/compiletest/compiletest.rs
src/compiletest/header.rs
src/compiletest/runtest.rs
src/compiletest/util.rs
src/doc/complement-cheatsheet.md
src/doc/guide-tasks.md
src/doc/rust.md
src/liballoc/arc.rs
src/libcollections/bitv.rs
src/libcollections/deque.rs
src/libcollections/dlist.rs
src/libcollections/hashmap.rs
src/libcollections/lib.rs
src/libcollections/treemap.rs
src/libcollections/trie.rs
src/libcore/any.rs
src/libcore/char.rs
src/libcore/cmp.rs
src/libcore/fmt/mod.rs
src/libcore/fmt/num.rs
src/libcore/lib.rs
src/libcore/result.rs
src/libcore/tuple.rs
src/libflate/lib.rs
src/libgetopts/lib.rs
src/libgreen/lib.rs
src/libgreen/sched.rs
src/libnative/io/file_win32.rs
src/libnum/bigint.rs
src/libnum/complex.rs
src/libnum/rational.rs
src/librand/distributions/exponential.rs
src/librand/distributions/gamma.rs
src/librand/distributions/mod.rs
src/librand/distributions/normal.rs
src/librand/distributions/range.rs
src/librand/isaac.rs
src/librand/lib.rs
src/librand/os.rs [deleted file]
src/librand/rand_impls.rs
src/librand/reader.rs [deleted file]
src/librand/reseeding.rs
src/libregex/re.rs
src/libregex/test/bench.rs
src/librustc/back/archive.rs
src/librustc/back/link.rs
src/librustc/back/lto.rs
src/librustc/driver/driver.rs
src/librustc/lib/llvm.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/loader.rs
src/librustc/metadata/tyencode.rs
src/librustc/middle/borrowck/mod.rs
src/librustc/middle/cfg/construct.rs
src/librustc/middle/check_match.rs
src/librustc/middle/check_static.rs
src/librustc/middle/dataflow.rs
src/librustc/middle/dead.rs
src/librustc/middle/lang_items.rs
src/librustc/middle/liveness.rs
src/librustc/middle/mem_categorization.rs
src/librustc/middle/privacy.rs
src/librustc/middle/region.rs
src/librustc/middle/trans/_match.rs
src/librustc/middle/trans/asm.rs
src/librustc/middle/trans/base.rs
src/librustc/middle/trans/cleanup.rs
src/librustc/middle/trans/closure.rs
src/librustc/middle/trans/common.rs
src/librustc/middle/trans/datum.rs
src/librustc/middle/trans/debuginfo.rs
src/librustc/middle/trans/expr.rs
src/librustc/middle/trans/glue.rs
src/librustc/middle/trans/llrepr.rs
src/librustc/middle/trans/monomorphize.rs
src/librustc/middle/trans/tvec.rs
src/librustc/middle/trans/type_of.rs
src/librustc/middle/ty.rs
src/librustc/middle/typeck/check/_match.rs
src/librustc/middle/typeck/check/method.rs
src/librustc/middle/typeck/check/mod.rs
src/librustc/middle/typeck/infer/error_reporting.rs
src/librustc/middle/typeck/infer/mod.rs
src/librustc/middle/typeck/infer/region_inference/mod.rs
src/librustc/middle/typeck/infer/to_str.rs
src/librustc/middle/typeck/mod.rs
src/librustc/util/ppaux.rs
src/librustdoc/clean/mod.rs
src/librustdoc/html/format.rs
src/librustdoc/html/markdown.rs
src/librustdoc/html/render.rs
src/librustdoc/html/toc.rs
src/librustdoc/lib.rs
src/librustdoc/test.rs
src/librustuv/file.rs
src/libsemver/lib.rs
src/libserialize/base64.rs
src/libserialize/ebml.rs
src/libserialize/hex.rs
src/libserialize/json.rs
src/libstd/ascii.rs
src/libstd/fmt.rs
src/libstd/io/fs.rs
src/libstd/io/tempfile.rs
src/libstd/io/test.rs
src/libstd/lib.rs
src/libstd/macros.rs
src/libstd/num/int_macros.rs
src/libstd/num/strconv.rs
src/libstd/num/uint_macros.rs
src/libstd/os.rs
src/libstd/path/windows.rs
src/libstd/rand/mod.rs [new file with mode: 0644]
src/libstd/rand/os.rs [new file with mode: 0644]
src/libstd/rand/reader.rs [new file with mode: 0644]
src/libstd/rt/unwind.rs
src/libstd/slice.rs
src/libstd/str.rs
src/libstd/string.rs
src/libstd/to_str.rs
src/libsyntax/ast.rs
src/libsyntax/ast_util.rs
src/libsyntax/ext/deriving/cmp/eq.rs
src/libsyntax/ext/deriving/cmp/ord.rs
src/libsyntax/ext/deriving/mod.rs
src/libsyntax/ext/deriving/rand.rs
src/libsyntax/ext/format.rs
src/libsyntax/fold.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pprust.rs
src/libsyntax/visit.rs
src/libterm/terminfo/parm.rs
src/libterm/terminfo/parser/compiled.rs
src/libterm/terminfo/searcher.rs
src/libtest/lib.rs
src/libtime/lib.rs
src/libuuid/lib.rs
src/test/bench/core-std.rs
src/test/bench/noise.rs
src/test/bench/shootout-binarytrees.rs
src/test/bench/shootout-chameneos-redux.rs
src/test/bench/shootout-k-nucleotide-pipes.rs
src/test/compile-fail/issue-13428.rs
src/test/compile-fail/task-rng-isnt-sendable.rs
src/test/debuginfo/borrowed-enum.rs
src/test/debuginfo/generic-struct-style-enum.rs
src/test/debuginfo/generic-tuple-style-enum.rs
src/test/debuginfo/managed-enum.rs
src/test/debuginfo/option-like-enum.rs
src/test/debuginfo/recursive-struct.rs
src/test/debuginfo/struct-in-enum.rs
src/test/debuginfo/struct-style-enum.rs
src/test/debuginfo/tuple-style-enum.rs
src/test/debuginfo/unique-enum.rs
src/test/run-fail/explicit-fail-msg.rs
src/test/run-fail/unwind-lambda.rs
src/test/run-make/unicode-input/multiple_files.rs
src/test/run-make/unicode-input/span_length.rs
src/test/run-pass/autoref-intermediate-types-issue-3585.rs
src/test/run-pass/bug-7183-generics.rs
src/test/run-pass/closure-reform.rs
src/test/run-pass/deriving-rand.rs
src/test/run-pass/issue-2804.rs
src/test/run-pass/issue-8898.rs
src/test/run-pass/log-knows-the-names-of-variants-in-std.rs
src/test/run-pass/log-knows-the-names-of-variants.rs
src/test/run-pass/match-borrowed_str.rs
src/test/run-pass/monad.rs
src/test/run-pass/process-spawn-with-unicode-params.rs
src/test/run-pass/send_str_treemap.rs
src/test/run-pass/str-concat.rs
src/test/run-pass/string-self-append.rs
src/test/run-pass/trait-cast.rs
src/test/run-pass/trait-to-str.rs
src/test/run-pass/traits-default-method-macro.rs
src/test/run-pass/vector-sort-failure-safe.rs

index 9ed279d9d74a28d66302a61bbf3a71ad60233f4d..29ba4cab3be457189c71e2696b51ea99e994a902 100644 (file)
@@ -60,7 +60,6 @@ config.mk
 /rt/
 /rustllvm/
 /test/
-/build
 /inst/
 /mingw-build/
 src/.DS_Store
index a4dc0c0465e77cdf7f4385773709583b317a7c43..a683528c847aa6757fc309972a021c2653d679f7 100644 (file)
@@ -60,9 +60,9 @@ DEPS_core :=
 DEPS_rlibc :=
 DEPS_alloc := core libc native:jemalloc
 DEPS_debug := std
-DEPS_std := core libc alloc native:rustrt native:backtrace
+DEPS_std := core rand libc alloc native:rustrt native:backtrace
 DEPS_graphviz := std
-DEPS_green := std rand native:context_switch
+DEPS_green := std native:context_switch
 DEPS_rustuv := std native:uv native:uv_support
 DEPS_native := std
 DEPS_syntax := std term serialize collections log fmt_macros debug
@@ -77,16 +77,16 @@ DEPS_glob := std
 DEPS_serialize := std collections log
 DEPS_term := std collections log
 DEPS_semver := std
-DEPS_uuid := std serialize rand
+DEPS_uuid := std serialize
 DEPS_sync := std alloc
 DEPS_getopts := std
-DEPS_collections := std rand debug
+DEPS_collections := std debug
 DEPS_fourcc := syntax std
 DEPS_hexfloat := syntax std
-DEPS_num := std rand
+DEPS_num := std
 DEPS_test := std collections getopts serialize term time regex
 DEPS_time := std serialize sync
-DEPS_rand := std
+DEPS_rand := core
 DEPS_url := std collections
 DEPS_workcache := std serialize collections log
 DEPS_log := std sync
@@ -104,6 +104,7 @@ TOOL_SOURCE_rustc := $(S)src/driver/driver.rs
 ONLY_RLIB_core := 1
 ONLY_RLIB_rlibc := 1
 ONLY_RLIB_alloc := 1
+ONLY_RLIB_rand := 1
 
 ################################################################################
 # You should not need to edit below this line
index 701f8899fa4ef8da792eefaa6f6dc4cd763c946a..8fcad94ee1cfc7cff997f61b143426c9c50b7105 100644 (file)
@@ -188,41 +188,41 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
 
 pub fn log_config(config: &Config) {
     let c = config;
-    logv(c, format_strbuf!("configuration:"));
-    logv(c, format_strbuf!("compile_lib_path: {}", config.compile_lib_path));
-    logv(c, format_strbuf!("run_lib_path: {}", config.run_lib_path));
-    logv(c, format_strbuf!("rustc_path: {}", config.rustc_path.display()));
-    logv(c, format_strbuf!("src_base: {}", config.src_base.display()));
-    logv(c, format_strbuf!("build_base: {}", config.build_base.display()));
-    logv(c, format_strbuf!("stage_id: {}", config.stage_id));
-    logv(c, format_strbuf!("mode: {}", config.mode));
-    logv(c, format_strbuf!("run_ignored: {}", config.run_ignored));
-    logv(c, format_strbuf!("filter: {}",
-                           opt_str(&config.filter
-                                          .as_ref()
-                                          .map(|re| {
-                                              re.to_str().into_string()
-                                          }))));
-    logv(c, format_strbuf!("runtool: {}", opt_str(&config.runtool)));
-    logv(c, format_strbuf!("host-rustcflags: {}",
-                           opt_str(&config.host_rustcflags)));
-    logv(c, format_strbuf!("target-rustcflags: {}",
-                           opt_str(&config.target_rustcflags)));
-    logv(c, format_strbuf!("jit: {}", config.jit));
-    logv(c, format_strbuf!("target: {}", config.target));
-    logv(c, format_strbuf!("host: {}", config.host));
-    logv(c, format_strbuf!("android-cross-path: {}",
-                           config.android_cross_path.display()));
-    logv(c, format_strbuf!("adb_path: {}", config.adb_path));
-    logv(c, format_strbuf!("adb_test_dir: {}", config.adb_test_dir));
-    logv(c, format_strbuf!("adb_device_status: {}",
-                           config.adb_device_status));
+    logv(c, format!("configuration:"));
+    logv(c, format!("compile_lib_path: {}", config.compile_lib_path));
+    logv(c, format!("run_lib_path: {}", config.run_lib_path));
+    logv(c, format!("rustc_path: {}", config.rustc_path.display()));
+    logv(c, format!("src_base: {}", config.src_base.display()));
+    logv(c, format!("build_base: {}", config.build_base.display()));
+    logv(c, format!("stage_id: {}", config.stage_id));
+    logv(c, format!("mode: {}", config.mode));
+    logv(c, format!("run_ignored: {}", config.run_ignored));
+    logv(c, format!("filter: {}",
+                    opt_str(&config.filter
+                                   .as_ref()
+                                   .map(|re| {
+                                       re.to_str().into_string()
+                                   }))));
+    logv(c, format!("runtool: {}", opt_str(&config.runtool)));
+    logv(c, format!("host-rustcflags: {}",
+                    opt_str(&config.host_rustcflags)));
+    logv(c, format!("target-rustcflags: {}",
+                    opt_str(&config.target_rustcflags)));
+    logv(c, format!("jit: {}", config.jit));
+    logv(c, format!("target: {}", config.target));
+    logv(c, format!("host: {}", config.host));
+    logv(c, format!("android-cross-path: {}",
+                    config.android_cross_path.display()));
+    logv(c, format!("adb_path: {}", config.adb_path));
+    logv(c, format!("adb_test_dir: {}", config.adb_test_dir));
+    logv(c, format!("adb_device_status: {}",
+                    config.adb_device_status));
     match config.test_shard {
         None => logv(c, "test_shard: (all)".to_string()),
-        Some((a,b)) => logv(c, format_strbuf!("test_shard: {}.{}", a, b))
+        Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b))
     }
-    logv(c, format_strbuf!("verbose: {}", config.verbose));
-    logv(c, format_strbuf!("\n"));
+    logv(c, format!("verbose: {}", config.verbose));
+    logv(c, format!("\n"));
 }
 
 pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
@@ -356,12 +356,10 @@ fn shorten(path: &Path) -> String {
         let filename = path.filename_str();
         let p = path.dir_path();
         let dir = p.filename_str();
-        format_strbuf!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
+        format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
     }
 
-    test::DynTestName(format_strbuf!("[{}] {}",
-                                     config.mode,
-                                     shorten(testfile)))
+    test::DynTestName(format!("[{}] {}", config.mode, shorten(testfile)))
 }
 
 pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
index 531f51f982f6bdfeb45d53c5f4af51447d4b1b19..4b0b68bca997ccd6a9da9bc04036816b91ac1674 100644 (file)
@@ -120,11 +120,11 @@ pub fn load_props(testfile: &Path) -> TestProps {
 
 pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
     fn ignore_target(config: &Config) -> String {
-        format_strbuf!("ignore-{}", util::get_os(config.target.as_slice()))
+        format!("ignore-{}", util::get_os(config.target.as_slice()))
     }
     fn ignore_stage(config: &Config) -> String {
-        format_strbuf!("ignore-{}",
-                       config.stage_id.as_slice().split('-').next().unwrap())
+        format!("ignore-{}",
+                config.stage_id.as_slice().split('-').next().unwrap())
     }
 
     let val = iter_header(testfile, |ln| {
@@ -243,7 +243,7 @@ fn parse_name_directive(line: &str, directive: &str) -> bool {
 
 pub fn parse_name_value_directive(line: &str, directive: String)
                                   -> Option<String> {
-    let keycolon = format_strbuf!("{}:", directive);
+    let keycolon = format!("{}:", directive);
     match line.find_str(keycolon.as_slice()) {
         Some(colon) => {
             let value = line.slice(colon + keycolon.len(),
index 7ad302646b36cee5b633964b69d1ce857f72f9f6..8429e83a7aa4390cb6a0fd2b745a72efbd8af94c 100644 (file)
@@ -121,8 +121,7 @@ fn check_correct_failure_status(proc_res: &ProcRes) {
     static RUST_ERR: int = 101;
     if !proc_res.status.matches_exit_status(RUST_ERR) {
         fatal_ProcRes(
-            format_strbuf!("failure produced the wrong error: {}",
-                           proc_res.status),
+            format!("failure produced the wrong error: {}", proc_res.status),
             proc_res);
     }
 }
@@ -165,7 +164,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
 
     let mut round = 0;
     while round < rounds {
-        logv(config, format_strbuf!("pretty-printing round {}", round));
+        logv(config, format!("pretty-printing round {}", round));
         let proc_res = print_source(config,
                                     props,
                                     testfile,
@@ -173,8 +172,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
                                     "normal");
 
         if !proc_res.status.success() {
-            fatal_ProcRes(format_strbuf!("pretty-printing failed in round {}",
-                                         round),
+            fatal_ProcRes(format!("pretty-printing failed in round {}", round),
                           &proc_res);
         }
 
@@ -214,15 +212,14 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
     // additionally, run `--pretty expanded` and try to build it.
     let proc_res = print_source(config, props, testfile, (*srcs.get(round)).clone(), "expanded");
     if !proc_res.status.success() {
-        fatal_ProcRes(format_strbuf!("pretty-printing (expanded) failed"),
-                                     &proc_res);
+        fatal_ProcRes(format!("pretty-printing (expanded) failed"), &proc_res);
     }
 
     let ProcRes{ stdout: expanded_src, .. } = proc_res;
     let proc_res = typecheck_source(config, props, testfile, expanded_src);
     if !proc_res.status.success() {
-        fatal_ProcRes(format_strbuf!("pretty-printed source (expanded) does \
-                                      not typecheck"),
+        fatal_ProcRes(format!("pretty-printed source (expanded) does \
+                               not typecheck"),
                       &proc_res);
     }
 
@@ -253,7 +250,7 @@ fn make_pp_args(config: &Config,
         let mut args = vec!("-".to_string(),
                             "--pretty".to_string(),
                             pretty_type,
-                            format_strbuf!("--target={}", config.target),
+                            format!("--target={}", config.target),
                             "-L".to_string(),
                             aux_dir.as_str().unwrap().to_string());
         args.push_all_move(split_maybe_args(&config.target_rustcflags));
@@ -300,7 +297,7 @@ fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> P
         let mut args = vec!("-".to_string(),
                             "--no-trans".to_string(),
                             "--crate-type=lib".to_string(),
-                            format_strbuf!("--target={}", target),
+                            format!("--target={}", target),
                             "-L".to_string(),
                             config.build_base.as_str().unwrap().to_string(),
                             "-L".to_string(),
@@ -343,10 +340,8 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
 
             // write debugger script
             let script_str = ["set charset UTF-8".to_string(),
-                              format_strbuf!("file {}",
-                                             exe_file.as_str()
-                                                     .unwrap()
-                                                     .to_string()),
+                              format!("file {}", exe_file.as_str().unwrap()
+                                                         .to_string()),
                               "target remote :5039".to_string(),
                               cmds,
                               "quit".to_string()].connect("\n");
@@ -366,8 +361,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                          ],
                          vec!(("".to_string(), "".to_string())),
                          Some("".to_string()))
-                .expect(format_strbuf!("failed to exec `{}`",
-                                       config.adb_path));
+                .expect(format!("failed to exec `{}`", config.adb_path));
 
             procsrv::run("",
                          config.adb_path.as_slice(),
@@ -378,15 +372,15 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                          ],
                          vec!(("".to_string(), "".to_string())),
                          Some("".to_string()))
-                .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+                .expect(format!("failed to exec `{}`", config.adb_path));
 
-            let adb_arg = format_strbuf!("export LD_LIBRARY_PATH={}; \
-                                          gdbserver :5039 {}/{}",
-                                         config.adb_test_dir.clone(),
-                                         config.adb_test_dir.clone(),
-                                         str::from_utf8(
-                                             exe_file.filename()
-                                             .unwrap()).unwrap());
+            let adb_arg = format!("export LD_LIBRARY_PATH={}; \
+                                   gdbserver :5039 {}/{}",
+                                  config.adb_test_dir.clone(),
+                                  config.adb_test_dir.clone(),
+                                  str::from_utf8(
+                                      exe_file.filename()
+                                      .unwrap()).unwrap());
 
             let mut process = procsrv::run_background("",
                                                       config.adb_path
@@ -398,8 +392,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                                                       vec!(("".to_string(),
                                                             "".to_string())),
                                                       Some("".to_string()))
-                .expect(format_strbuf!("failed to exec `{}`",
-                                       config.adb_path));
+                .expect(format!("failed to exec `{}`", config.adb_path));
             loop {
                 //waiting 1 second for gdbserver start
                 timer::sleep(1000);
@@ -423,8 +416,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                 vec!("-quiet".to_string(),
                      "-batch".to_string(),
                      "-nx".to_string(),
-                     format_strbuf!("-command={}",
-                                    debugger_script.as_str().unwrap()));
+                     format!("-command={}", debugger_script.as_str().unwrap()));
 
             let gdb_path = tool_path.append("/bin/arm-linux-androideabi-gdb");
             let procsrv::Result {
@@ -436,12 +428,12 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                              debugger_opts.as_slice(),
                              vec!(("".to_string(), "".to_string())),
                              None)
-                .expect(format_strbuf!("failed to exec `{}`", gdb_path));
+                .expect(format!("failed to exec `{}`", gdb_path));
             let cmdline = {
                 let cmdline = make_cmdline("",
                                            "arm-linux-androideabi-gdb",
                                            debugger_opts.as_slice());
-                logv(config, format_strbuf!("executing {}", cmdline));
+                logv(config, format!("executing {}", cmdline));
                 cmdline
             };
 
@@ -484,8 +476,7 @@ fn debugger() -> String {
                 vec!("-quiet".to_string(),
                      "-batch".to_string(),
                      "-nx".to_string(),
-                     format_strbuf!("-command={}",
-                                    debugger_script.as_str().unwrap()),
+                     format!("-command={}", debugger_script.as_str().unwrap()),
                      exe_file.as_str().unwrap().to_string());
             proc_args = ProcArgs {
                 prog: debugger(),
@@ -593,9 +584,8 @@ fn run_lldb(config: &Config, test_executable: &Path, debugger_script: &Path) ->
                  str::from_utf8(error.as_slice()).unwrap().to_string())
             },
             Err(e) => {
-                fatal(format_strbuf!("Failed to setup Python process for \
-                                      LLDB script: {}",
-                                     e))
+                fatal(format!("Failed to setup Python process for \
+                               LLDB script: {}", e))
             }
         };
 
@@ -604,7 +594,7 @@ fn run_lldb(config: &Config, test_executable: &Path, debugger_script: &Path) ->
             status: status,
             stdout: out,
             stderr: err,
-            cmdline: format_strbuf!("{}", cmd)
+            cmdline: format!("{}", cmd)
         };
     }
 }
@@ -647,9 +637,7 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
                 });
             }
             Err(e) => {
-                fatal(format_strbuf!("Error while parsing debugger commands: \
-                                      {}",
-                                     e))
+                fatal(format!("Error while parsing debugger commands: {}", e))
             }
         }
         counter += 1;
@@ -732,9 +720,8 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
             }
         }
         if i != num_check_lines {
-            fatal_ProcRes(format_strbuf!("line not found in debugger output: \
-                                          {}",
-                                         check_lines.get(i).unwrap()),
+            fatal_ProcRes(format!("line not found in debugger output: {}",
+                                  check_lines.get(i).unwrap()),
                           debugger_run_result);
         }
     }
@@ -744,8 +731,8 @@ fn check_error_patterns(props: &TestProps,
                         testfile: &Path,
                         proc_res: &ProcRes) {
     if props.error_patterns.is_empty() {
-        fatal(format_strbuf!("no error pattern specified in {}",
-                             testfile.display().as_maybe_owned().as_slice()));
+        fatal(format!("no error pattern specified in {}",
+                      testfile.display().as_maybe_owned().as_slice()));
     }
 
     if proc_res.status.success() {
@@ -756,7 +743,7 @@ fn check_error_patterns(props: &TestProps,
     let mut next_err_pat = props.error_patterns.get(next_err_idx);
     let mut done = false;
     let output_to_check = if props.check_stdout {
-        format_strbuf!("{}{}", proc_res.stdout, proc_res.stderr)
+        format!("{}{}", proc_res.stdout, proc_res.stderr)
     } else {
         proc_res.stderr.clone()
     };
@@ -777,12 +764,12 @@ fn check_error_patterns(props: &TestProps,
     let missing_patterns =
         props.error_patterns.slice(next_err_idx, props.error_patterns.len());
     if missing_patterns.len() == 1u {
-        fatal_ProcRes(format_strbuf!("error pattern '{}' not found!",
-                                     missing_patterns[0]),
+        fatal_ProcRes(format!("error pattern '{}' not found!",
+                              missing_patterns[0]),
                       proc_res);
     } else {
         for pattern in missing_patterns.iter() {
-            error(format_strbuf!("error pattern '{}' not found!", *pattern));
+            error(format!("error pattern '{}' not found!", *pattern));
         }
         fatal_ProcRes("multiple error patterns not found".to_string(),
                       proc_res);
@@ -811,7 +798,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
     }
 
     let prefixes = expected_errors.iter().map(|ee| {
-        format_strbuf!("{}:{}:", testfile.display(), ee.line)
+        format!("{}:{}:", testfile.display(), ee.line)
     }).collect::<Vec<String> >();
 
     #[cfg(target_os = "win32")]
@@ -870,9 +857,8 @@ fn prefix_matches( line : &str, prefix : &str ) -> bool {
         }
 
         if !was_expected && is_compiler_error_or_warning(line) {
-            fatal_ProcRes(format_strbuf!("unexpected compiler error or \
-                                          warning: '{}'",
-                                         line),
+            fatal_ProcRes(format!("unexpected compiler error or warning: '{}'",
+                                  line),
                           proc_res);
         }
     }
@@ -880,11 +866,8 @@ fn prefix_matches( line : &str, prefix : &str ) -> bool {
     for (i, &flag) in found_flags.iter().enumerate() {
         if !flag {
             let ee = expected_errors.get(i);
-            fatal_ProcRes(format_strbuf!("expected {} on line {} not found: \
-                                          {}",
-                                         ee.kind,
-                                         ee.line,
-                                         ee.msg),
+            fatal_ProcRes(format!("expected {} on line {} not found: {}",
+                                  ee.kind, ee.line, ee.msg),
                           proc_res);
         }
     }
@@ -1065,8 +1048,8 @@ fn compose_and_run_compiler(
                                      None);
         if !auxres.status.success() {
             fatal_ProcRes(
-                format_strbuf!("auxiliary build of {} failed to compile: ",
-                               abs_ab.display()),
+                format!("auxiliary build of {} failed to compile: ",
+                        abs_ab.display()),
                 &auxres);
         }
 
@@ -1121,7 +1104,7 @@ fn make_compile_args(config: &Config,
     let mut args = vec!(testfile.as_str().unwrap().to_string(),
                         "-L".to_string(),
                         config.build_base.as_str().unwrap().to_string(),
-                        format_strbuf!("--target={}", target));
+                        format!("--target={}", target));
     args.push_all(extras.as_slice());
     if !props.no_prefer_dynamic {
         args.push("-C".to_string());
@@ -1213,7 +1196,7 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
             let cmdline = make_cmdline(lib_path,
                                        prog.as_slice(),
                                        args.as_slice());
-            logv(config, format_strbuf!("executing {}", cmdline));
+            logv(config, format!("executing {}", cmdline));
             cmdline
         };
     let procsrv::Result {
@@ -1224,8 +1207,7 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
                      prog.as_slice(),
                      args.as_slice(),
                      env,
-                     input).expect(format_strbuf!("failed to exec `{}`",
-                                                  prog));
+                     input).expect(format!("failed to exec `{}`", prog));
     dump_output(config, testfile, out.as_slice(), err.as_slice());
     return ProcRes {
         status: status,
@@ -1240,24 +1222,19 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
 #[cfg(target_os = "macos")]
 #[cfg(target_os = "freebsd")]
 fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
-    format_strbuf!("{} {}", prog, args.connect(" "))
+    format!("{} {}", prog, args.connect(" "))
 }
 
 #[cfg(target_os = "win32")]
 fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
-    format_strbuf!("{} {} {}",
-                   lib_path_cmd_prefix(libpath),
-                   prog,
-                   args.connect(" "))
+    format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
 }
 
 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
 // for diagnostic purposes
 #[cfg(target_os = "win32")]
 fn lib_path_cmd_prefix(path: &str) -> String {
-    format_strbuf!("{}=\"{}\"",
-                   util::lib_path_env_var(),
-                   util::make_new_path(path))
+    format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
 }
 
 fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
@@ -1356,7 +1333,7 @@ fn _arm_exec_compiled_test(config: &Config,
                                    ],
                                    vec!(("".to_string(), "".to_string())),
                                    Some("".to_string()))
-        .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+        .expect(format!("failed to exec `{}`", config.adb_path));
 
     if config.verbose {
         println!("push ({}) {} {} {}",
@@ -1366,19 +1343,18 @@ fn _arm_exec_compiled_test(config: &Config,
                  copy_result.err);
     }
 
-    logv(config, format_strbuf!("executing ({}) {}", config.target, cmdline));
+    logv(config, format!("executing ({}) {}", config.target, cmdline));
 
     let mut runargs = Vec::new();
 
     // run test via adb_run_wrapper
     runargs.push("shell".to_string());
     for (key, val) in env.move_iter() {
-        runargs.push(format_strbuf!("{}={}", key, val));
+        runargs.push(format!("{}={}", key, val));
     }
-    runargs.push(format_strbuf!("{}/adb_run_wrapper.sh",
-                                config.adb_test_dir));
-    runargs.push(format_strbuf!("{}", config.adb_test_dir));
-    runargs.push(format_strbuf!("{}", prog_short));
+    runargs.push(format!("{}/adb_run_wrapper.sh", config.adb_test_dir));
+    runargs.push(format!("{}", config.adb_test_dir));
+    runargs.push(format!("{}", prog_short));
 
     for tv in args.args.iter() {
         runargs.push(tv.to_string());
@@ -1387,15 +1363,13 @@ fn _arm_exec_compiled_test(config: &Config,
                  config.adb_path.as_slice(),
                  runargs.as_slice(),
                  vec!(("".to_string(), "".to_string())), Some("".to_string()))
-        .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+        .expect(format!("failed to exec `{}`", config.adb_path));
 
     // get exitcode of result
     runargs = Vec::new();
     runargs.push("shell".to_string());
     runargs.push("cat".to_string());
-    runargs.push(format_strbuf!("{}/{}.exitcode",
-                                config.adb_test_dir,
-                                prog_short));
+    runargs.push(format!("{}/{}.exitcode", config.adb_test_dir, prog_short));
 
     let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
         procsrv::run("",
@@ -1403,7 +1377,7 @@ fn _arm_exec_compiled_test(config: &Config,
                      runargs.as_slice(),
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+        .expect(format!("failed to exec `{}`", config.adb_path));
 
     let mut exitcode: int = 0;
     for c in exitcode_out.as_slice().chars() {
@@ -1418,9 +1392,7 @@ fn _arm_exec_compiled_test(config: &Config,
     runargs = Vec::new();
     runargs.push("shell".to_string());
     runargs.push("cat".to_string());
-    runargs.push(format_strbuf!("{}/{}.stdout",
-                                config.adb_test_dir,
-                                prog_short));
+    runargs.push(format!("{}/{}.stdout", config.adb_test_dir, prog_short));
 
     let procsrv::Result{ out: stdout_out, err: _, status: _ } =
         procsrv::run("",
@@ -1428,15 +1400,13 @@ fn _arm_exec_compiled_test(config: &Config,
                      runargs.as_slice(),
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+        .expect(format!("failed to exec `{}`", config.adb_path));
 
     // get stderr of result
     runargs = Vec::new();
     runargs.push("shell".to_string());
     runargs.push("cat".to_string());
-    runargs.push(format_strbuf!("{}/{}.stderr",
-                                config.adb_test_dir,
-                                prog_short));
+    runargs.push(format!("{}/{}.stderr", config.adb_test_dir, prog_short));
 
     let procsrv::Result{ out: stderr_out, err: _, status: _ } =
         procsrv::run("",
@@ -1444,7 +1414,7 @@ fn _arm_exec_compiled_test(config: &Config,
                      runargs.as_slice(),
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format_strbuf!("failed to exec `{}`", config.adb_path));
+        .expect(format!("failed to exec `{}`", config.adb_path));
 
     dump_output(config,
                 testfile,
@@ -1478,8 +1448,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
                                            vec!(("".to_string(),
                                                  "".to_string())),
                                            Some("".to_string()))
-                .expect(format_strbuf!("failed to exec `{}`",
-                                       config.adb_path));
+                .expect(format!("failed to exec `{}`", config.adb_path));
 
             if config.verbose {
                 println!("push ({}) {} {} {}",
@@ -1549,8 +1518,8 @@ fn extract_function_from_bitcode(config: &Config, _props: &TestProps,
     let proc_args = ProcArgs {
         // FIXME (#9639): This needs to handle non-utf8 paths
         prog: prog.as_str().unwrap().to_string(),
-        args: vec!(format_strbuf!("-func={}", fname),
-                   format_strbuf!("-o={}", extracted_bc.as_str().unwrap()),
+        args: vec!(format!("-func={}", fname),
+                   format!("-o={}", extracted_bc.as_str().unwrap()),
                    bitcodefile.as_str().unwrap().to_string())
     };
     compose_and_run(config, testfile, proc_args, Vec::new(), "", None)
@@ -1566,7 +1535,7 @@ fn disassemble_extract(config: &Config, _props: &TestProps,
     let proc_args = ProcArgs {
         // FIXME (#9639): This needs to handle non-utf8 paths
         prog: prog.as_str().unwrap().to_string(),
-        args: vec!(format_strbuf!("-o={}", extracted_ll.as_str().unwrap()),
+        args: vec!(format!("-o={}", extracted_ll.as_str().unwrap()),
                    extracted_bc.as_str().unwrap().to_string())
     };
     compose_and_run(config, testfile, proc_args, Vec::new(), "", None)
index 8f1d5cceb2b995ea0ee3432b3dfc9a2738bde8bd..00f0689b96b660b01295edafec35d65af743d929 100644 (file)
@@ -39,7 +39,7 @@ pub fn make_new_path(path: &str) -> String {
     // maintain the current value while adding our own
     match getenv(lib_path_env_var().as_slice()) {
       Some(curr) => {
-        format_strbuf!("{}{}{}", path, path_div(), curr)
+        format!("{}{}{}", path, path_div(), curr)
       }
       None => path.to_str().to_string()
     }
index 759518b6769174a22670aff1e7e08d09af214e96..f14b70afc7a174d60d8c4a0ffddbd75bc0f1a4c6 100644 (file)
@@ -23,14 +23,14 @@ let y: int = x.unwrap();
 
 **Int to string, in non-base-10**
 
-Use the `format_strbuf!` syntax extension.
+Use the `format!` syntax extension.
 
 ~~~
 let x: int = 42;
-let y: String = format_strbuf!("{:t}", x);   // binary
-let y: String = format_strbuf!("{:o}", x);   // octal
-let y: String = format_strbuf!("{:x}", x);   // lowercase hexadecimal
-let y: String = format_strbuf!("{:X}", x);   // uppercase hexadecimal
+let y: String = format!("{:t}", x);   // binary
+let y: String = format!("{:o}", x);   // octal
+let y: String = format!("{:x}", x);   // lowercase hexadecimal
+let y: String = format!("{:X}", x);   // uppercase hexadecimal
 ~~~
 
 **String to int, in non-base-10**
index ad6ec65ef44baae93570575db8fe0e50aad1e311..6b45174591462776f7cf027c5376316fb8eab2f8 100644 (file)
@@ -329,10 +329,10 @@ Here is a small example showing how to use Arcs. We wish to run concurrently sev
 a single large vector of floats. Each task needs the full vector to perform its duty.
 
 ~~~
-extern crate rand;
 extern crate sync;
 
 use sync::Arc;
+use std::rand;
 
 fn pnorm(nums: &[f64], p: uint) -> f64 {
     nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
@@ -358,7 +358,7 @@ created by the line
 
 ~~~
 # extern crate sync;
-# extern crate rand;
+# use std::rand;
 # use sync::Arc;
 # fn main() {
 # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
@@ -372,7 +372,7 @@ reference to the underlying vector as if it were local.
 
 ~~~
 # extern crate sync;
-# extern crate rand;
+# use std::rand;
 # use sync::Arc;
 # fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
 # fn main() {
index d62d03518125e7de3365c3871e533a661da88d69..bf4fd3dcc9377a568a0c96ac33e970e534126ba9 100644 (file)
@@ -1036,6 +1036,7 @@ Unsafe operations are those that potentially violate the memory-safety guarantee
 The following language level features cannot be used in the safe subset of Rust:
 
   - Dereferencing a [raw pointer](#pointer-types).
+  - Reading or writing a [mutable static variable](#mutable-statics).
   - Calling an unsafe function (including an intrinsic or foreign function).
 
 ##### Unsafe functions
index a408bf8e284e70c2b985130db840023a8c1154e1..546e4e5269979c27e773823d76beb39fd064a0ff 100644 (file)
@@ -160,7 +160,8 @@ pub fn make_unique<'a>(&'a mut self) -> &'a mut T {
         // reference count is guaranteed to be 1 at this point, and we required
         // the Arc itself to be `mut`, so we're returning the only possible
         // reference to the inner data.
-        unsafe { mem::transmute::<&_, &mut _>(self.deref()) }
+        let inner = unsafe { &mut *self._ptr };
+        &mut inner.data
     }
 }
 
index 0b5d499c533bc37d7bac5da57568bde590690000..48491222be47ea3c6a4aa0973f4df6b5e370cf7e 100644 (file)
@@ -980,8 +980,8 @@ mod tests {
     use bitv;
 
     use std::uint;
-    use rand;
-    use rand::Rng;
+    use std::rand;
+    use std::rand::Rng;
 
     static BENCH_BITS : uint = 1 << 14;
 
index e031b07f87296829973100303c09d68bc9d036b0..fa2cb233873d969e6dd426f241850251399d9f13 100644 (file)
@@ -44,8 +44,8 @@ pub mod bench {
     extern crate test;
     use self::test::Bencher;
     use std::container::MutableMap;
-    use rand;
-    use rand::Rng;
+    use std::rand;
+    use std::rand::Rng;
 
     pub fn insert_rand_n<M:MutableMap<uint,uint>>(n: uint,
                                                   map: &mut M,
index 8072ee02bc0121ffd49d95131f94d580cd267fcc..957299197386f3e61b34a51b449bd5e551fd4fab 100644 (file)
@@ -610,7 +610,7 @@ mod tests {
     extern crate test;
     use self::test::Bencher;
     use deque::Deque;
-    use rand;
+    use std::rand;
     use super::{DList, Node, ListInsertion};
 
     pub fn check_links<T>(list: &DList<T>) {
index 42b57a1ea40632844dac9c1fbea763bb3de72e1a..6f5c0a8c2402e2d643c6df200077d6d2aff71b81 100644 (file)
@@ -24,8 +24,8 @@
 use std::mem::replace;
 use std::num;
 use std::option::{Option, Some, None};
-use rand;
-use rand::Rng;
+use std::rand;
+use std::rand::Rng;
 use std::result::{Ok, Err};
 use std::slice::ImmutableVector;
 
index cbf4ae03a767086dbd2f9088df62df240bbde4c8..d1c75b895798ab33c95db763a7664382977cabbc 100644 (file)
@@ -24,7 +24,6 @@
 
 #![deny(deprecated_owned_vector)]
 
-extern crate rand;
 extern crate debug;
 
 #[cfg(test)] extern crate test;
index fb663d91131af970c3204f824299c3e3713e7f48..3e862f280606cac480d7034cb4af72e6054b3ca2 100644 (file)
@@ -1000,8 +1000,8 @@ fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
 mod test_treemap {
     use super::{TreeMap, TreeNode};
 
-    use rand::Rng;
-    use rand;
+    use std::rand::Rng;
+    use std::rand;
 
     #[test]
     fn find_empty() {
index 9d64b3c2394b02d7cf47c93deeb47cdfff52809f..e6df4fd87e12e976b9054823b8c09389ce3e975d 100644 (file)
@@ -915,7 +915,7 @@ fn test_mut_bound() {
 mod bench_map {
     extern crate test;
     use super::TrieMap;
-    use rand::{weak_rng, Rng};
+    use std::rand::{weak_rng, Rng};
     use self::test::Bencher;
 
     #[bench]
index 94ac344db3485e64993b489de63e25fcfdb97e62..f463c194424da14250241b022764a6529dbbb7e1 100644 (file)
@@ -119,7 +119,7 @@ mod tests {
     use prelude::*;
     use super::*;
     use realstd::owned::{Box, AnyOwnExt};
-    use realstd::str::{Str, StrAllocating};
+    use realstd::str::Str;
 
     #[deriving(Eq, Show)]
     struct Test;
index 0c5d3151af0f5b8418a7be97c6707d37b8b05131..2d1cab5d841561b7e62f6c631c5a89d12560a9ad 100644 (file)
@@ -607,7 +607,7 @@ mod test {
     use slice::ImmutableVector;
     use option::{Some, None};
     use realstd::string::String;
-    use realstd::str::{Str, StrAllocating};
+    use realstd::str::Str;
 
     #[test]
     fn test_is_lowercase() {
index 1c621f7f4ce154992c27e345711d4bffa7dc8464..32fc3331fa2f771c6329091710adce9d096c328e 100644 (file)
@@ -37,6 +37,9 @@
 //! assert!(SketchyNum {num: 25} != SketchyNum {num: 57});
 //! ```
 
+pub use PartialEq = cmp::Eq;
+pub use PartialOrd = cmp::Ord;
+
 /// Trait for values that can be compared for equality and inequality.
 ///
 /// This trait allows partial equality, where types can be unordered instead of
index 13236a1f654d0333eedce9337567c4f07428d7f0..f41efdbc1db6f131390a5dd296170d74b19bcbc2 100644 (file)
@@ -596,7 +596,6 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
 #[cfg(test)]
 pub fn format(args: &Arguments) -> ::realstd::string::String {
     use str;
-    use realstd::str::StrAllocating;
     use realstd::io::MemWriter;
 
     fn mywrite<T: ::realstd::io::Writer>(t: &mut T, b: &[u8]) {
index 731911185ff7e4e0b382cb2c5e0772977507e99f..7ad78df2fe8cecf0b945f700dec9840affa72166 100644 (file)
@@ -194,7 +194,7 @@ mod tests {
     use fmt::radix;
     use super::{Binary, Octal, Decimal, LowerHex, UpperHex};
     use super::{GenericRadix, Radix};
-    use realstd::str::{Str, StrAllocating};
+    use realstd::str::Str;
 
     #[test]
     fn test_radix_base() {
@@ -399,35 +399,35 @@ mod bench {
     mod uint {
         use super::test::Bencher;
         use fmt::radix;
-        use rand::{XorShiftRng, Rng};
+        use realstd::rand::{weak_rng, Rng};
 
         #[bench]
         fn format_bin(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:t}", rng.gen::<uint>()); })
         }
 
         #[bench]
         fn format_oct(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:o}", rng.gen::<uint>()); })
         }
 
         #[bench]
         fn format_dec(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:u}", rng.gen::<uint>()); })
         }
 
         #[bench]
         fn format_hex(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:x}", rng.gen::<uint>()); })
         }
 
         #[bench]
         fn format_base_36(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{}", radix(rng.gen::<uint>(), 36)); })
         }
     }
@@ -435,35 +435,35 @@ fn format_base_36(b: &mut Bencher) {
     mod int {
         use super::test::Bencher;
         use fmt::radix;
-        use rand::{XorShiftRng, Rng};
+        use realstd::rand::{weak_rng, Rng};
 
         #[bench]
         fn format_bin(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:t}", rng.gen::<int>()); })
         }
 
         #[bench]
         fn format_oct(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:o}", rng.gen::<int>()); })
         }
 
         #[bench]
         fn format_dec(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:d}", rng.gen::<int>()); })
         }
 
         #[bench]
         fn format_hex(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{:x}", rng.gen::<int>()); })
         }
 
         #[bench]
         fn format_base_36(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { format!("{}", radix(rng.gen::<int>(), 36)); })
         }
     }
index 56cbe2e2a30d187ec32bea4f82fc34ed6f1febe0..2ff2dca0c867300fa1f0182b642495167fd005f2 100644 (file)
@@ -59,7 +59,6 @@
 #[cfg(test)] extern crate realcore = "core";
 #[cfg(test)] extern crate libc;
 #[cfg(test)] extern crate native;
-#[cfg(test)] extern crate rand;
 #[cfg(test)] extern crate realstd = "std";
 
 #[cfg(test)] pub use cmp = realcore::cmp;
index 926605dddb3e6713606f4f7b8c717cdde4adccd4..fd51ede204ff1f4f344696843bc4f0e3116fd453 100644 (file)
@@ -637,11 +637,10 @@ pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
 #[cfg(test)]
 mod tests {
     use realstd::vec::Vec;
-    use realstd::string::String;
 
     use result::{collect, fold, fold_};
     use prelude::*;
-    use realstd::str::{Str, StrAllocating};
+    use realstd::str::Str;
     use iter::range;
 
     pub fn op1() -> Result<int, &'static str> { Ok(666) }
index 059b96ffac713fcbc6a3598d0f5c553cc23fc949..edcb37dbb64c2342c3ed8d11aa4ae567555b507a 100644 (file)
@@ -294,7 +294,7 @@ mod tests {
     use super::*;
     use clone::Clone;
     use cmp::*;
-    use realstd::str::{Str, StrAllocating};
+    use realstd::str::Str;
 
     #[test]
     fn test_clone() {
index 54f147dead8b68f02807ebaeb2c987e7b22b0acc..8bfd2d867c130ad749497202ef0d56b40b62d1c4 100644 (file)
@@ -108,10 +108,9 @@ pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
 
 #[cfg(test)]
 mod tests {
-    extern crate rand;
-
     use super::{inflate_bytes, deflate_bytes};
-    use self::rand::Rng;
+    use std::rand;
+    use std::rand::Rng;
 
     #[test]
     #[allow(deprecated_owned_vector)]
@@ -120,7 +119,8 @@ fn test_flate_round_trip() {
         let mut words = vec!();
         for _ in range(0, 20) {
             let range = r.gen_range(1u, 10);
-            words.push(r.gen_vec::<u8>(range));
+            let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
+            words.push(v);
         }
         for _ in range(0, 20) {
             let mut input = vec![];
index c88b825811f51b112f448e00fd11d86f8bedd0b2..37c3fe0d2ef8e63eaf1721f141b19f8a28b9d8d2 100644 (file)
@@ -500,19 +500,19 @@ impl Fail_ {
     pub fn to_err_msg(self) -> String {
         match self {
             ArgumentMissing(ref nm) => {
-                format_strbuf!("Argument to option '{}' missing.", *nm)
+                format!("Argument to option '{}' missing.", *nm)
             }
             UnrecognizedOption(ref nm) => {
-                format_strbuf!("Unrecognized option: '{}'.", *nm)
+                format!("Unrecognized option: '{}'.", *nm)
             }
             OptionMissing(ref nm) => {
-                format_strbuf!("Required option '{}' missing.", *nm)
+                format!("Required option '{}' missing.", *nm)
             }
             OptionDuplicated(ref nm) => {
-                format_strbuf!("Option '{}' given more than once.", *nm)
+                format!("Option '{}' given more than once.", *nm)
             }
             UnexpectedArgument(ref nm) => {
-                format_strbuf!("Option '{}' does not take an argument.", *nm)
+                format!("Option '{}' does not take an argument.", *nm)
             }
         }
     }
@@ -740,9 +740,8 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String {
         row
     });
 
-    format_strbuf!("{}\n\nOptions:\n{}\n",
-                   brief,
-                   rows.collect::<Vec<String>>().connect("\n"))
+    format!("{}\n\nOptions:\n{}\n", brief,
+            rows.collect::<Vec<String>>().connect("\n"))
 }
 
 fn format_option(opt: &OptGroup) -> String {
@@ -784,7 +783,7 @@ fn format_option(opt: &OptGroup) -> String {
 
 /// Derive a short one-line usage summary from a set of long options.
 pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String {
-    let mut line = format_strbuf!("Usage: {} ", program_name);
+    let mut line = format!("Usage: {} ", program_name);
     line.push_str(opts.iter()
                       .map(format_option)
                       .collect::<Vec<String>>()
index 4584c08cbd8984f093ff58639a72c0467f0e0be9..31fd8950c804c2d48fa5d1ece63ff3b3903bdb9a 100644 (file)
 
 #[cfg(test)] #[phase(syntax, link)] extern crate log;
 #[cfg(test)] extern crate rustuv;
-extern crate rand;
 extern crate libc;
 extern crate alloc;
 
index d28e74a2b80b7c14d823c5a4175b822c43f5a76d..6dc6ccb79018061f1e1e394ef3323b844cfb6855 100644 (file)
@@ -17,7 +17,7 @@
 use std::unstable::mutex::NativeMutex;
 use std::raw;
 
-use rand::{XorShiftRng, Rng, Rand};
+use std::rand::{XorShiftRng, Rng, Rand};
 
 use TaskState;
 use context::Context;
@@ -977,8 +977,9 @@ fn to_fn(self) -> |&mut Scheduler, Box<GreenTask>| {
 // worry there.
 #[cfg(windows)]
 fn new_sched_rng() -> XorShiftRng {
-    match XorShiftRng::new() {
-        Ok(r) => r,
+    use std::rand::OsRng;
+    match OsRng::new() {
+        Ok(mut r) => r.gen(),
         Err(e) => {
             rtabort!("sched: failed to create seeded RNG: {}", e)
         }
@@ -988,7 +989,7 @@ fn new_sched_rng() -> XorShiftRng {
 fn new_sched_rng() -> XorShiftRng {
     use libc;
     use std::mem;
-    use rand::SeedableRng;
+    use std::rand::SeedableRng;
 
     let fd = "/dev/urandom".with_c_str(|name| {
         unsafe { libc::open(name, libc::O_RDONLY, 0) }
index c9a48db69207a23d01585850d9c7784eff4a6cd1..4f1f3b3ca26f726374cbc7e3fcaaf57085da0389 100644 (file)
@@ -90,6 +90,25 @@ pub fn fd(&self) -> fd_t { self.inner.fd }
     pub fn handle(&self) -> libc::HANDLE {
         unsafe { libc::get_osfhandle(self.fd()) as libc::HANDLE }
     }
+
+    // A version of seek that takes &self so that tell can call it
+    //   - the private seek should of course take &mut self.
+    fn seek_common(&self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
+        let whence = match style {
+            io::SeekSet => libc::FILE_BEGIN,
+            io::SeekEnd => libc::FILE_END,
+            io::SeekCur => libc::FILE_CURRENT,
+        };
+        unsafe {
+            let mut newpos = 0;
+            match libc::SetFilePointerEx(self.handle(), pos, &mut newpos,
+                                         whence) {
+                0 => Err(super::last_error()),
+                _ => Ok(newpos as u64),
+            }
+        }
+    }
+
 }
 
 impl io::Reader for FileDesc {
@@ -151,26 +170,13 @@ fn pwrite(&mut self, buf: &[u8], mut offset: u64) -> Result<(), IoError> {
         }
         Ok(())
     }
+
     fn seek(&mut self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
-        let whence = match style {
-            io::SeekSet => libc::FILE_BEGIN,
-            io::SeekEnd => libc::FILE_END,
-            io::SeekCur => libc::FILE_CURRENT,
-        };
-        unsafe {
-            let mut newpos = 0;
-            match libc::SetFilePointerEx(self.handle(), pos, &mut newpos,
-                                         whence) {
-                0 => Err(super::last_error()),
-                _ => Ok(newpos as u64),
-            }
-        }
+        self.seek_common(pos, style)
     }
+
     fn tell(&self) -> Result<u64, IoError> {
-        // This transmute is fine because our seek implementation doesn't
-        // actually use the mutable self at all.
-        // FIXME #13933: Remove/justify all `&T` to `&mut T` transmutes
-        unsafe { mem::transmute::<&_, &mut FileDesc>(self).seek(0, io::SeekCur) }
+        self.seek_common(0, io::SeekCur)
     }
 
     fn fsync(&mut self) -> Result<(), IoError> {
index e8d0434c392856c4eb83b385c5667a4d7f2f26d6..c6af8ac9b4b89075b6ac17ced547382089f523a0 100644 (file)
@@ -1215,7 +1215,7 @@ fn to_str_radix(&self, radix: uint) -> String {
         match self.sign {
             Plus  => self.data.to_str_radix(radix),
             Zero  => "0".to_string(),
-            Minus => format_strbuf!("-{}", self.data.to_str_radix(radix)),
+            Minus => format!("-{}", self.data.to_str_radix(radix)),
         }
     }
 }
@@ -1372,7 +1372,7 @@ mod biguint_tests {
     use std::num::{Zero, One, FromStrRadix, ToStrRadix};
     use std::num::{ToPrimitive, FromPrimitive};
     use std::num::CheckedDiv;
-    use rand::{task_rng};
+    use std::rand::task_rng;
     use std::u64;
 
     #[test]
@@ -2055,34 +2055,34 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
             (16, "fff".to_string())
         )), ( BigUint::from_slice([ 1, 2 ]), vec!(
             (2,
-             format_strbuf!("10{}1", "0".repeat(bits - 1))),
+             format!("10{}1", "0".repeat(bits - 1))),
             (4,
-             format_strbuf!("2{}1", "0".repeat(bits / 2 - 1))),
+             format!("2{}1", "0".repeat(bits / 2 - 1))),
             (10, match bits {
                 32 => "8589934593".to_string(),
                 16 => "131073".to_string(),
                 _ => fail!()
             }),
             (16,
-             format_strbuf!("2{}1", "0".repeat(bits / 4 - 1)))
+             format!("2{}1", "0".repeat(bits / 4 - 1)))
         )), ( BigUint::from_slice([ 1, 2, 3 ]), vec!(
             (2,
-             format_strbuf!("11{}10{}1",
-                            "0".repeat(bits - 2),
-                            "0".repeat(bits - 1))),
+             format!("11{}10{}1",
+                     "0".repeat(bits - 2),
+                     "0".repeat(bits - 1))),
             (4,
-             format_strbuf!("3{}2{}1",
-                            "0".repeat(bits / 2 - 1),
-                            "0".repeat(bits / 2 - 1))),
+             format!("3{}2{}1",
+                     "0".repeat(bits / 2 - 1),
+                     "0".repeat(bits / 2 - 1))),
             (10, match bits {
                 32 => "55340232229718589441".to_string(),
                 16 => "12885032961".to_string(),
                 _ => fail!()
             }),
             (16,
-             format_strbuf!("3{}2{}1",
-                            "0".repeat(bits / 4 - 1),
-                            "0".repeat(bits / 4 - 1)))
+             format!("3{}2{}1",
+                     "0".repeat(bits / 4 - 1),
+                     "0".repeat(bits / 4 - 1)))
         )) )
     }
 
@@ -2220,7 +2220,7 @@ mod bigint_tests {
     use std::num::CheckedDiv;
     use std::num::{Zero, One, FromStrRadix, ToStrRadix};
     use std::num::{ToPrimitive, FromPrimitive};
-    use rand::{task_rng};
+    use std::rand::task_rng;
     use std::u64;
 
     #[test]
index a4c2183921433af9fa6ccfb65ceb6b61455497bf..6c5547b28e8cf6aedfa2be3927228afda451dfc1 100644 (file)
@@ -177,13 +177,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 impl<T: ToStrRadix + Num + Ord> ToStrRadix for Complex<T> {
     fn to_str_radix(&self, radix: uint) -> String {
         if self.im < Zero::zero() {
-            format_strbuf!("{}-{}i",
-                           self.re.to_str_radix(radix),
-                           (-self.im).to_str_radix(radix))
+            format!("{}-{}i",
+                    self.re.to_str_radix(radix),
+                    (-self.im).to_str_radix(radix))
         } else {
-            format_strbuf!("{}+{}i",
-                           self.re.to_str_radix(radix),
-                           self.im.to_str_radix(radix))
+            format!("{}+{}i",
+                    self.re.to_str_radix(radix),
+                    self.im.to_str_radix(radix))
         }
     }
 }
index e916265396e265204a3844d22b92a2bb7fd501ce..ba0a571268f44e64e56fb834b3286654d77def10 100644 (file)
@@ -282,9 +282,9 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
     /// Renders as `numer/denom` where the numbers are in base `radix`.
     fn to_str_radix(&self, radix: uint) -> String {
-        format_strbuf!("{}/{}",
-                       self.numer.to_str_radix(radix),
-                       self.denom.to_str_radix(radix))
+        format!("{}/{}",
+                self.numer.to_str_radix(radix),
+                self.denom.to_str_radix(radix))
     }
 }
 
index 03c87eb931d604428fead709072ffa1ba6d572b9..d4e689ccb5c5998a3fb685dadc264a554c94b47f 100644 (file)
@@ -10,7 +10,8 @@
 
 //! The exponential distribution.
 
-use std::num::Float;
+use core::num::Float;
+
 use {Rng, Rand};
 use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
 
@@ -58,7 +59,8 @@ fn zero_case<R:Rng>(rng: &mut R, _u: f64) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{Exp, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{Exp, IndependentSample};
 ///
 /// let exp = Exp::new(2.0);
 /// let v = exp.ind_sample(&mut rand::task_rng());
@@ -90,14 +92,15 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 
 #[cfg(test)]
 mod test {
+    use std::prelude::*;
+
     use distributions::{Sample, IndependentSample};
-    use {Rng, task_rng};
     use super::Exp;
 
     #[test]
     fn test_exp() {
         let mut exp = Exp::new(10.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             assert!(exp.sample(&mut rng) >= 0.0);
             assert!(exp.ind_sample(&mut rng) >= 0.0);
@@ -118,22 +121,24 @@ fn test_exp_invalid_lambda_neg() {
 #[cfg(test)]
 mod bench {
     extern crate test;
+
+    use std::prelude::*;
+
     use self::test::Bencher;
     use std::mem::size_of;
-    use {XorShiftRng, RAND_BENCH_N};
     use super::Exp;
     use distributions::Sample;
 
     #[bench]
     fn rand_exp(b: &mut Bencher) {
-        let mut rng = XorShiftRng::new().unwrap();
+        let mut rng = ::test::weak_rng();
         let mut exp = Exp::new(2.71828 * 3.14159);
 
         b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
+            for _ in range(0, ::RAND_BENCH_N) {
                 exp.sample(&mut rng);
             }
         });
-        b.bytes = size_of::<f64>() as u64 * RAND_BENCH_N;
+        b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
     }
 }
index 1bb2c35bce206bd05ba6be5913f540fca6e4c188..445fe9acbeca0f6ff0fb09349c7a3abe308f6e6d 100644 (file)
@@ -10,7 +10,8 @@
 
 //! The Gamma and derived distributions.
 
-use std::num::Float;
+use core::num::Float;
+
 use {Rng, Open01};
 use super::normal::StandardNormal;
 use super::{IndependentSample, Sample, Exp};
@@ -34,7 +35,8 @@
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{IndependentSample, Gamma};
+/// use std::rand;
+/// use std::rand::distributions::{IndependentSample, Gamma};
 ///
 /// let gamma = Gamma::new(2.0, 5.0);
 /// let v = gamma.ind_sample(&mut rand::task_rng());
@@ -182,7 +184,8 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{ChiSquared, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{ChiSquared, IndependentSample};
 ///
 /// let chi = ChiSquared::new(11.0);
 /// let v = chi.ind_sample(&mut rand::task_rng());
@@ -238,7 +241,8 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{FisherF, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{FisherF, IndependentSample};
 ///
 /// let f = FisherF::new(2.0, 32.0);
 /// let v = f.ind_sample(&mut rand::task_rng());
@@ -281,7 +285,8 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{StudentT, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{StudentT, IndependentSample};
 ///
 /// let t = StudentT::new(11.0);
 /// let v = t.ind_sample(&mut rand::task_rng());
@@ -315,14 +320,15 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 
 #[cfg(test)]
 mod test {
+    use std::prelude::*;
+
     use distributions::{Sample, IndependentSample};
-    use {Rng, task_rng};
     use super::{ChiSquared, StudentT, FisherF};
 
     #[test]
     fn test_chi_squared_one() {
         let mut chi = ChiSquared::new(1.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             chi.sample(&mut rng);
             chi.ind_sample(&mut rng);
@@ -331,7 +337,7 @@ fn test_chi_squared_one() {
     #[test]
     fn test_chi_squared_small() {
         let mut chi = ChiSquared::new(0.5);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             chi.sample(&mut rng);
             chi.ind_sample(&mut rng);
@@ -340,7 +346,7 @@ fn test_chi_squared_small() {
     #[test]
     fn test_chi_squared_large() {
         let mut chi = ChiSquared::new(30.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             chi.sample(&mut rng);
             chi.ind_sample(&mut rng);
@@ -355,7 +361,7 @@ fn test_chi_squared_invalid_dof() {
     #[test]
     fn test_f() {
         let mut f = FisherF::new(2.0, 32.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             f.sample(&mut rng);
             f.ind_sample(&mut rng);
@@ -365,7 +371,7 @@ fn test_f() {
     #[test]
     fn test_t() {
         let mut t = StudentT::new(11.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             t.sample(&mut rng);
             t.ind_sample(&mut rng);
@@ -376,36 +382,36 @@ fn test_t() {
 #[cfg(test)]
 mod bench {
     extern crate test;
+    use std::prelude::*;
     use self::test::Bencher;
     use std::mem::size_of;
     use distributions::IndependentSample;
-    use {XorShiftRng, RAND_BENCH_N};
     use super::Gamma;
 
 
     #[bench]
     fn bench_gamma_large_shape(b: &mut Bencher) {
         let gamma = Gamma::new(10., 1.0);
-        let mut rng = XorShiftRng::new().unwrap();
+        let mut rng = ::test::weak_rng();
 
         b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
+            for _ in range(0, ::RAND_BENCH_N) {
                 gamma.ind_sample(&mut rng);
             }
         });
-        b.bytes = size_of::<f64>() as u64 * RAND_BENCH_N;
+        b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
     }
 
     #[bench]
     fn bench_gamma_small_shape(b: &mut Bencher) {
         let gamma = Gamma::new(0.1, 1.0);
-        let mut rng = XorShiftRng::new().unwrap();
+        let mut rng = ::test::weak_rng();
 
         b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
+            for _ in range(0, ::RAND_BENCH_N) {
                 gamma.ind_sample(&mut rng);
             }
         });
-        b.bytes = size_of::<f64>() as u64 * RAND_BENCH_N;
+        b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
     }
 }
index b3535a695eaf310e331350dd44c38a2a3e711dce..bb09db48802690f53774f2ab9a1d6aa67b17c319 100644 (file)
 
 */
 
-use std::num;
-use std::num::CheckedAdd;
+#![experimental]
+
+use core::prelude::*;
+use core::num;
+use core::num::CheckedAdd;
+
 use {Rng, Rand};
 
 pub use self::range::Range;
@@ -89,30 +93,32 @@ pub struct Weighted<T> {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{Weighted, WeightedChoice, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{Weighted, WeightedChoice, IndependentSample};
 ///
-/// let wc = WeightedChoice::new(vec!(Weighted { weight: 2, item: 'a' },
-///                                   Weighted { weight: 4, item: 'b' },
-///                                   Weighted { weight: 1, item: 'c' }));
+/// let mut items = vec!(Weighted { weight: 2, item: 'a' },
+///                      Weighted { weight: 4, item: 'b' },
+///                      Weighted { weight: 1, item: 'c' });
+/// let wc = WeightedChoice::new(items.as_mut_slice());
 /// let mut rng = rand::task_rng();
 /// for _ in range(0, 16) {
 ///      // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
 ///      println!("{}", wc.ind_sample(&mut rng));
 /// }
 /// ```
-pub struct WeightedChoice<T> {
-    items: Vec<Weighted<T>>,
+pub struct WeightedChoice<'a, T> {
+    items: &'a mut [Weighted<T>],
     weight_range: Range<uint>
 }
 
-impl<T: Clone> WeightedChoice<T> {
+impl<'a, T: Clone> WeightedChoice<'a, T> {
     /// Create a new `WeightedChoice`.
     ///
     /// Fails if:
     /// - `v` is empty
     /// - the total weight is 0
     /// - the total weight is larger than a `uint` can contain.
-    pub fn new(mut items: Vec<Weighted<T>>) -> WeightedChoice<T> {
+    pub fn new<'a>(items: &'a mut [Weighted<T>]) -> WeightedChoice<'a, T> {
         // strictly speaking, this is subsumed by the total weight == 0 case
         assert!(!items.is_empty(), "WeightedChoice::new called with no items");
 
@@ -122,9 +128,11 @@ pub fn new(mut items: Vec<Weighted<T>>) -> WeightedChoice<T> {
         // weights so we can binary search. This *could* drop elements
         // with weight == 0 as an optimisation.
         for item in items.mut_iter() {
-            running_total = running_total.checked_add(&item.weight)
-                .expect("WeightedChoice::new called with a total weight larger \
-                        than a uint can contain");
+            running_total = match running_total.checked_add(&item.weight) {
+                Some(n) => n,
+                None => fail!("WeightedChoice::new called with a total weight \
+                               larger than a uint can contain")
+            };
 
             item.weight = running_total;
         }
@@ -139,11 +147,11 @@ pub fn new(mut items: Vec<Weighted<T>>) -> WeightedChoice<T> {
     }
 }
 
-impl<T: Clone> Sample<T> for WeightedChoice<T> {
+impl<'a, T: Clone> Sample<T> for WeightedChoice<'a, T> {
     fn sample<R: Rng>(&mut self, rng: &mut R) -> T { self.ind_sample(rng) }
 }
 
-impl<T: Clone> IndependentSample<T> for WeightedChoice<T> {
+impl<'a, T: Clone> IndependentSample<T> for WeightedChoice<'a, T> {
     fn ind_sample<R: Rng>(&self, rng: &mut R) -> T {
         // we want to find the first element that has cumulative
         // weight > sample_weight, which we do by binary since the
@@ -153,8 +161,8 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> T {
         let sample_weight = self.weight_range.ind_sample(rng);
 
         // short circuit when it's the first item
-        if sample_weight < self.items.get(0).weight {
-            return self.items.get(0).item.clone();
+        if sample_weight < self.items[0].weight {
+            return self.items[0].item.clone();
         }
 
         let mut idx = 0;
@@ -169,7 +177,7 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> T {
         // one is exactly the total weight.)
         while modifier > 1 {
             let i = idx + modifier / 2;
-            if self.items.get(i).weight <= sample_weight {
+            if self.items[i].weight <= sample_weight {
                 // we're small, so look to the right, but allow this
                 // exact element still.
                 idx = i;
@@ -182,7 +190,7 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> T {
             }
             modifier /= 2;
         }
-        return self.items.get(idx + 1).item.clone();
+        return self.items[idx + 1].item.clone();
     }
 }
 
@@ -247,7 +255,9 @@ fn ziggurat<R:Rng>(
 
 #[cfg(test)]
 mod tests {
-    use {task_rng, Rng, Rand};
+    use std::prelude::*;
+
+    use {Rng, Rand};
     use super::{RandSample, WeightedChoice, Weighted, Sample, IndependentSample};
 
     #[deriving(Eq, Show)]
@@ -274,8 +284,8 @@ fn next_u64(&mut self) -> u64 {
     fn test_rand_sample() {
         let mut rand_sample = RandSample::<ConstRand>;
 
-        assert_eq!(rand_sample.sample(&mut task_rng()), ConstRand(0));
-        assert_eq!(rand_sample.ind_sample(&mut task_rng()), ConstRand(0));
+        assert_eq!(rand_sample.sample(&mut ::test::rng()), ConstRand(0));
+        assert_eq!(rand_sample.ind_sample(&mut ::test::rng()), ConstRand(0));
     }
     #[test]
     fn test_weighted_choice() {
@@ -286,7 +296,8 @@ fn test_weighted_choice() {
 
         macro_rules! t (
             ($items:expr, $expected:expr) => {{
-                let wc = WeightedChoice::new($items);
+                let mut items = $items;
+                let wc = WeightedChoice::new(items.as_mut_slice());
                 let expected = $expected;
 
                 let mut rng = CountingRng { i: 0 };
@@ -332,19 +343,19 @@ macro_rules! t (
 
     #[test] #[should_fail]
     fn test_weighted_choice_no_items() {
-        WeightedChoice::<int>::new(vec!());
+        WeightedChoice::<int>::new([]);
     }
     #[test] #[should_fail]
     fn test_weighted_choice_zero_weight() {
-        WeightedChoice::new(vec!(Weighted { weight: 0, item: 0},
-                                 Weighted { weight: 0, item: 1}));
+        WeightedChoice::new(&mut [Weighted { weight: 0, item: 0},
+                                  Weighted { weight: 0, item: 1}]);
     }
     #[test] #[should_fail]
     fn test_weighted_choice_weight_overflows() {
         let x = (-1) as uint / 2; // x + x + 2 is the overflow
-        WeightedChoice::new(vec!(Weighted { weight: x, item: 0 },
-                                 Weighted { weight: 1, item: 1 },
-                                 Weighted { weight: x, item: 2 },
-                                 Weighted { weight: 1, item: 3 }));
+        WeightedChoice::new(&mut [Weighted { weight: x, item: 0 },
+                                  Weighted { weight: 1, item: 1 },
+                                  Weighted { weight: x, item: 2 },
+                                  Weighted { weight: 1, item: 3 }]);
     }
 }
index dea73945b4384058a5e23c4a0bdb91f147942dda..47ab7d32e05751c080679c4a807d85fdb69e24dd 100644 (file)
@@ -10,7 +10,8 @@
 
 //! The normal and derived distributions.
 
-use std::num::Float;
+use core::num::Float;
+
 use {Rng, Rand, Open01};
 use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
 
@@ -74,7 +75,8 @@ fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{Normal, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{Normal, IndependentSample};
 ///
 /// // mean 2, standard deviation 3
 /// let normal = Normal::new(2.0, 3.0);
@@ -116,7 +118,8 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{LogNormal, IndependentSample};
+/// use std::rand;
+/// use std::rand::distributions::{LogNormal, IndependentSample};
 ///
 /// // mean 2, standard deviation 3
 /// let log_normal = LogNormal::new(2.0, 3.0);
@@ -146,14 +149,15 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 
 #[cfg(test)]
 mod tests {
+    use std::prelude::*;
+
     use distributions::{Sample, IndependentSample};
-    use {Rng, task_rng};
     use super::{Normal, LogNormal};
 
     #[test]
     fn test_normal() {
         let mut norm = Normal::new(10.0, 10.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             norm.sample(&mut rng);
             norm.ind_sample(&mut rng);
@@ -169,7 +173,7 @@ fn test_normal_invalid_sd() {
     #[test]
     fn test_log_normal() {
         let mut lnorm = LogNormal::new(10.0, 10.0);
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         for _ in range(0, 1000) {
             lnorm.sample(&mut rng);
             lnorm.ind_sample(&mut rng);
@@ -185,22 +189,22 @@ fn test_log_normal_invalid_sd() {
 #[cfg(test)]
 mod bench {
     extern crate test;
+    use std::prelude::*;
     use self::test::Bencher;
     use std::mem::size_of;
-    use {XorShiftRng, RAND_BENCH_N};
     use distributions::{Sample};
     use super::Normal;
 
     #[bench]
     fn rand_normal(b: &mut Bencher) {
-        let mut rng = XorShiftRng::new().unwrap();
+        let mut rng = ::test::weak_rng();
         let mut normal = Normal::new(-2.71828, 3.14159);
 
         b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
+            for _ in range(0, ::RAND_BENCH_N) {
                 normal.sample(&mut rng);
             }
         });
-        b.bytes = size_of::<f64>() as u64 * RAND_BENCH_N;
+        b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
     }
 }
index cee80b62e3dec45b5358c158e8a82e1e11c4f035..f0e1d1715a2baeab3fc0bd915029b6dc7466a487 100644 (file)
@@ -12,7 +12,9 @@
 
 // this is surprisingly complicated to be both generic & correct
 
-use std::num::Bounded;
+use core::prelude::*;
+use core::num::Bounded;
+
 use Rng;
 use distributions::{Sample, IndependentSample};
 
@@ -33,7 +35,8 @@
 /// # Example
 ///
 /// ```rust
-/// use rand::distributions::{IndependentSample, Range};
+/// use std::rand;
+/// use std::rand::distributions::{IndependentSample, Range};
 ///
 /// fn main() {
 ///     let between = Range::new(10u, 10000u);
@@ -161,8 +164,8 @@ fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty {
 
 #[cfg(test)]
 mod tests {
+    use std::prelude::*;
     use distributions::{Sample, IndependentSample};
-    use {Rng, task_rng};
     use super::Range;
     use std::num::Bounded;
 
@@ -179,7 +182,7 @@ fn test_range_bad_limits_flipped() {
 
     #[test]
     fn test_integers() {
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         macro_rules! t (
             ($($ty:ty),*) => {{
                 $(
@@ -204,7 +207,7 @@ macro_rules! t (
 
     #[test]
     fn test_floats() {
-        let mut rng = task_rng();
+        let mut rng = ::test::rng();
         macro_rules! t (
             ($($ty:ty),*) => {{
                 $(
index 1d9da40f18b6efc6418a2453e0b581cb9e663f69..83b86e1e15804674854b1b0268291cb9e6ef74da 100644 (file)
 
 //! The ISAAC random number generator.
 
-use {Rng, SeedableRng, OSRng};
-use std::io::IoResult;
-use std::iter::{range_step, Repeat};
-use std::slice::raw;
-use std::mem;
+use core::prelude::*;
+use core::iter::{range_step, Repeat};
+use core::slice::raw;
+use core::mem;
+
+use {Rng, SeedableRng, Rand};
 
 static RAND_SIZE_LEN: u32 = 8;
 static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
@@ -23,7 +24,7 @@
 ///
 /// The ISAAC algorithm is generally accepted as suitable for
 /// cryptographic purposes, but this implementation has not be
-/// verified as such. Prefer a generator like `OSRng` that defers to
+/// verified as such. Prefer a generator like `OsRng` that defers to
 /// the operating system for cases that need high security.
 ///
 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
@@ -44,26 +45,6 @@ pub struct IsaacRng {
 };
 
 impl IsaacRng {
-    /// Create an ISAAC random number generator with a random seed.
-    ///
-    /// This reads randomness from the operating system (via `OSRng`)
-    /// which may fail, any error is propagated via the `IoResult`
-    /// return value.
-    pub fn new() -> IoResult<IsaacRng> {
-        let mut rng = EMPTY;
-        let mut os_rng = try!(OSRng::new());
-        unsafe {
-            let ptr = rng.rsl.as_mut_ptr();
-
-            raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
-                os_rng.fill_bytes(slice);
-            })
-        }
-
-        rng.init(true);
-        Ok(rng)
-    }
-
     /// Create an ISAAC random number generator using the default
     /// fixed seed.
     pub fn new_unseeded() -> IsaacRng {
@@ -221,6 +202,26 @@ fn from_seed(seed: &'a [u32]) -> IsaacRng {
     }
 }
 
+impl Rand for IsaacRng {
+    fn rand<R: Rng>(other: &mut R) -> IsaacRng {
+        let mut ret = EMPTY;
+        unsafe {
+            let ptr = ret.rsl.as_mut_ptr();
+
+            raw::mut_buf_as_slice(ptr as *mut u8,
+                                  mem::size_of_val(&ret.rsl), |slice| {
+                other.fill_bytes(slice);
+            })
+        }
+        ret.cnt = 0;
+        ret.a = 0;
+        ret.b = 0;
+        ret.c = 0;
+
+        ret.init(true);
+        return ret;
+    }
+}
 
 static RAND_SIZE_64_LEN: uint = 8;
 static RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN;
@@ -230,7 +231,7 @@ fn from_seed(seed: &'a [u32]) -> IsaacRng {
 ///
 /// The ISAAC algorithm is generally accepted as suitable for
 /// cryptographic purposes, but this implementation has not be
-/// verified as such. Prefer a generator like `OSRng` that defers to
+/// verified as such. Prefer a generator like `OsRng` that defers to
 /// the operating system for cases that need high security.
 ///
 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
@@ -252,28 +253,6 @@ pub struct Isaac64Rng {
 };
 
 impl Isaac64Rng {
-    /// Create a 64-bit ISAAC random number generator with a random
-    /// seed.
-    ///
-    /// This reads randomness from the operating system (via `OSRng`)
-    /// which may fail, any error is propagated via the `IoResult`
-    /// return value.
-    pub fn new() -> IoResult<Isaac64Rng> {
-        let mut rng = EMPTY_64;
-        let mut os_rng = try!(OSRng::new());
-
-        unsafe {
-            let ptr = rng.rsl.as_mut_ptr();
-
-            raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
-                os_rng.fill_bytes(slice);
-            })
-        }
-
-        rng.init(true);
-        Ok(rng)
-    }
-
     /// Create a 64-bit ISAAC random number generator using the
     /// default fixed seed.
     pub fn new_unseeded() -> Isaac64Rng {
@@ -437,24 +416,50 @@ fn from_seed(seed: &'a [u64]) -> Isaac64Rng {
     }
 }
 
+impl Rand for Isaac64Rng {
+    fn rand<R: Rng>(other: &mut R) -> Isaac64Rng {
+        let mut ret = EMPTY_64;
+        unsafe {
+            let ptr = ret.rsl.as_mut_ptr();
+
+            raw::mut_buf_as_slice(ptr as *mut u8,
+                                  mem::size_of_val(&ret.rsl), |slice| {
+                other.fill_bytes(slice);
+            })
+        }
+        ret.cnt = 0;
+        ret.a = 0;
+        ret.b = 0;
+        ret.c = 0;
+
+        ret.init(true);
+        return ret;
+    }
+}
+
 #[cfg(test)]
 mod test {
+    use std::prelude::*;
+
+    use core::iter::order;
+    use {Rng, SeedableRng};
     use super::{IsaacRng, Isaac64Rng};
-    use {Rng, SeedableRng, task_rng};
 
     #[test]
     fn test_rng_32_rand_seeded() {
-        let s = task_rng().gen_vec::<u32>(256);
+        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());
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
     }
     #[test]
     fn test_rng_64_rand_seeded() {
-        let s = task_rng().gen_vec::<u64>(256);
+        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());
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
     }
 
     #[test]
@@ -462,36 +467,38 @@ fn test_rng_32_seeded() {
         let seed = &[1, 23, 456, 7890, 12345];
         let mut ra: IsaacRng = SeedableRng::from_seed(seed);
         let mut rb: IsaacRng = SeedableRng::from_seed(seed);
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
     }
     #[test]
     fn test_rng_64_seeded() {
         let seed = &[1, 23, 456, 7890, 12345];
         let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
         let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
     }
 
     #[test]
     fn test_rng_32_reseed() {
-        let s = task_rng().gen_vec::<u32>(256);
+        let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
         let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
-        let string1 = r.gen_ascii_str(100);
+        let string1: String = r.gen_ascii_chars().take(100).collect();
 
         r.reseed(s.as_slice());
 
-        let string2 = r.gen_ascii_str(100);
+        let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
     }
     #[test]
     fn test_rng_64_reseed() {
-        let s = task_rng().gen_vec::<u64>(256);
+        let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
         let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
-        let string1 = r.gen_ascii_str(100);
+        let string1: String = r.gen_ascii_chars().take(100).collect();
 
         r.reseed(s.as_slice());
 
-        let string2 = r.gen_ascii_str(100);
+        let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
     }
 
index 4a11b692076008c70c2e204fad02ba9cb1b270da..353ac4cfed1af357c4a03cf1753369400c6dc91a 100644 (file)
@@ -8,96 +8,45 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-/*!
-Utilities for random number generation
-
-The key functions are `random()` and `Rng::gen()`. These are polymorphic
-and so can be used to generate any type that implements `Rand`. Type inference
-means that often a simple call to `rand::random()` or `rng.gen()` will
-suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
-
-See the `distributions` submodule for sampling random numbers from
-distributions like normal and exponential.
-
-# Task-local RNG
-
-There is built-in support for a RNG associated with each task stored
-in task-local storage. This RNG can be accessed via `task_rng`, or
-used implicitly via `random`. This RNG is normally randomly seeded
-from an operating-system source of randomness, e.g. `/dev/urandom` on
-Unix systems, and will automatically reseed itself from this source
-after generating 32 KiB of random data.
-
-# Cryptographic security
-
-An application that requires an entropy source for cryptographic purposes
-must use `OSRng`, which reads randomness from the source that the operating
-system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
-The other random number generators provided by this module are not suitable
-for such purposes.
-
-*Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
-This module uses `/dev/urandom` for the following reasons:
-
--   On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
-    This does not mean that `/dev/random` provides better output than
-    `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
-    number generator (CSPRNG) based on entropy pool for random number generation,
-    so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
-    However, this means that `/dev/urandom` can yield somewhat predictable randomness
-    if the entropy pool is very small, such as immediately after first booting.
-    If an application likely to be run soon after first booting, or on a system with very
-    few entropy sources, one should consider using `/dev/random` via `ReaderRng`.
--   On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
-    between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
-    and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
-
-# Examples
-
-```rust
-use rand::Rng;
-
-let mut rng = rand::task_rng();
-if rng.gen() { // bool
-    println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
-}
-```
-
-```rust
-let tuple_ptr = rand::random::<Box<(f64, char)>>();
-println!("{}", tuple_ptr)
-```
-*/
+//! Interface to random number generators in Rust.
+//!
+//! This is an experimental library which lives underneath the standard library
+//! in its dependency chain. This library is intended to define the interface
+//! for random number generation and also provide utilities around doing so. It
+//! is not recommended to use this library directly, but rather the official
+//! interface through `std::rand`.
 
 #![crate_id = "rand#0.11.0-pre"]
 #![license = "MIT/ASL2"]
-#![crate_type = "dylib"]
 #![crate_type = "rlib"]
 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
        html_root_url = "http://doc.rust-lang.org/")]
 
-#![feature(macro_rules, managed_boxes, phase)]
-#![deny(deprecated_owned_vector)]
+#![feature(macro_rules, phase, globs)]
+#![no_std]
+#![experimental]
+
+#[phase(syntax, link)]
+extern crate core;
 
+#[cfg(test)] extern crate native;
 #[cfg(test)] extern crate debug;
+#[cfg(test)] #[phase(syntax, link)] extern crate std;
 #[cfg(test)] #[phase(syntax, link)] extern crate log;
 
-use std::io::IoResult;
-use std::kinds::marker;
-use std::mem;
-use std::string::String;
+use core::prelude::*;
 
 pub use isaac::{IsaacRng, Isaac64Rng};
-pub use os::OSRng;
 
 use distributions::{Range, IndependentSample};
 use distributions::range::SampleRange;
 
+#[cfg(test)]
+static RAND_BENCH_N: u64 = 100;
+
 pub mod distributions;
 pub mod isaac;
-pub mod os;
-pub mod reader;
 pub mod reseeding;
 mod rand_impls;
 
@@ -148,7 +97,7 @@ fn next_u64(&mut self) -> u64 {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut v = [0u8, .. 13579];
     /// task_rng().fill_bytes(v);
@@ -183,7 +132,7 @@ fn fill_bytes(&mut self, dest: &mut [u8]) {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut rng = task_rng();
     /// let x: uint = rng.gen();
@@ -195,20 +144,22 @@ fn gen<T: Rand>(&mut self) -> T {
         Rand::rand(self)
     }
 
-    /// Return a random vector of the specified length.
+    /// Return an iterator which will yield an infinite number of randomly
+    /// generated items.
     ///
     /// # Example
     ///
-    /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// ```
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut rng = task_rng();
-    /// let x: Vec<uint> = rng.gen_vec(10);
+    /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
     /// println!("{}", x);
-    /// println!("{}", rng.gen_vec::<(f64, bool)>(5));
+    /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
+    ///                   .collect::<Vec<(f64, bool)>>());
     /// ```
-    fn gen_vec<T: Rand>(&mut self, len: uint) -> Vec<T> {
-        Vec::from_fn(len, |_| self.gen())
+    fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
+        Generator { rng: self }
     }
 
     /// Generate a random value in the range [`low`, `high`). Fails if
@@ -223,7 +174,7 @@ fn gen_vec<T: Rand>(&mut self, len: uint) -> Vec<T> {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut rng = task_rng();
     /// let n: uint = rng.gen_range(0u, 10);
@@ -241,7 +192,7 @@ fn gen_range<T: Ord + SampleRange>(&mut self, low: T, high: T) -> T {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut rng = task_rng();
     /// println!("{:b}", rng.gen_weighted_bool(3));
@@ -250,25 +201,18 @@ fn gen_weighted_bool(&mut self, n: uint) -> bool {
         n == 0 || self.gen_range(0, n) == 0
     }
 
-    /// Return a random string of the specified length composed of
-    /// A-Z,a-z,0-9.
+    /// Return an iterator of random characters from the set A-Z,a-z,0-9.
     ///
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
-    /// println!("{}", task_rng().gen_ascii_str(10));
+    /// let s: String = task_rng().gen_ascii_chars().take(10).collect();
+    /// println!("{}", s);
     /// ```
-    fn gen_ascii_str(&mut self, len: uint) -> String {
-        static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
-                                                             abcdefghijklmnopqrstuvwxyz\
-                                                             0123456789");
-        let mut s = String::with_capacity(len);
-        for _ in range(0, len) {
-            s.push_char(*self.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
-        }
-        s
+    fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
+        AsciiGenerator { rng: self }
     }
 
     /// Return a random element from `values`.
@@ -278,7 +222,7 @@ fn gen_ascii_str(&mut self, len: uint) -> String {
     /// # Example
     ///
     /// ```
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let choices = [1, 2, 4, 8, 16, 32];
     /// let mut rng = task_rng();
@@ -304,7 +248,7 @@ fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{task_rng, Rng};
+    /// use std::rand::{task_rng, Rng};
     ///
     /// let mut rng = task_rng();
     /// let mut y = [1,2,3];
@@ -322,32 +266,35 @@ fn shuffle<T>(&mut self, values: &mut [T]) {
             values.swap(i, self.gen_range(0u, i + 1u));
         }
     }
+}
 
-    /// Randomly sample up to `n` elements from an iterator.
-    ///
-    /// # Example
-    ///
-    /// ```rust
-    /// use rand::{task_rng, Rng};
-    ///
-    /// let mut rng = task_rng();
-    /// let sample = rng.sample(range(1, 100), 5);
-    /// println!("{}", sample);
-    /// ```
-    fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> Vec<A> {
-        let mut reservoir = Vec::with_capacity(n);
-        for (i, elem) in iter.enumerate() {
-            if i < n {
-                reservoir.push(elem);
-                continue
-            }
+/// Iterator which will generate a stream of random items.
+///
+/// This iterator is created via the `gen_iter` method on `Rng`.
+pub struct Generator<'a, T, R> {
+    rng: &'a mut R,
+}
 
-            let k = self.gen_range(0, i + 1);
-            if k < reservoir.len() {
-                *reservoir.get_mut(k) = elem
-            }
-        }
-        reservoir
+impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
+    fn next(&mut self) -> Option<T> {
+        Some(self.rng.gen())
+    }
+}
+
+/// Iterator which will continuously generate random ascii characters.
+///
+/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
+pub struct AsciiGenerator<'a, R> {
+    rng: &'a mut R,
+}
+
+impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
+    fn next(&mut self) -> Option<char> {
+        static GEN_ASCII_STR_CHARSET: &'static [u8] =
+            bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
+                    abcdefghijklmnopqrstuvwxyz\
+                    0123456789");
+        Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
     }
 }
 
@@ -359,7 +306,7 @@ pub trait SeedableRng<Seed>: Rng {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{Rng, SeedableRng, StdRng};
+    /// use std::rand::{Rng, SeedableRng, StdRng};
     ///
     /// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
     /// println!("{}", rng.gen::<f64>());
@@ -373,7 +320,7 @@ pub trait SeedableRng<Seed>: Rng {
     /// # Example
     ///
     /// ```rust
-    /// use rand::{Rng, SeedableRng, StdRng};
+    /// use std::rand::{Rng, SeedableRng, StdRng};
     ///
     /// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
     /// println!("{}", rng.gen::<f64>());
@@ -381,95 +328,12 @@ pub trait SeedableRng<Seed>: Rng {
     fn from_seed(seed: Seed) -> Self;
 }
 
-/// The standard RNG. This is designed to be efficient on the current
-/// platform.
-#[cfg(not(target_word_size="64"))]
-pub struct StdRng { rng: IsaacRng }
-
-/// The standard RNG. This is designed to be efficient on the current
-/// platform.
-#[cfg(target_word_size="64")]
-pub struct StdRng { rng: Isaac64Rng }
-
-impl StdRng {
-    /// Create a randomly seeded instance of `StdRng`.
-    ///
-    /// This is a very expensive operation as it has to read
-    /// randomness from the operating system and use this in an
-    /// expensive seeding operation. If one is only generating a small
-    /// number of random numbers, or doesn't need the utmost speed for
-    /// generating each number, `task_rng` and/or `random` may be more
-    /// appropriate.
-    ///
-    /// Reading the randomness from the OS may fail, and any error is
-    /// propagated via the `IoResult` return value.
-    #[cfg(not(target_word_size="64"))]
-    pub fn new() -> IoResult<StdRng> {
-        IsaacRng::new().map(|r| StdRng { rng: r })
-    }
-    /// Create a randomly seeded instance of `StdRng`.
-    ///
-    /// This is a very expensive operation as it has to read
-    /// randomness from the operating system and use this in an
-    /// expensive seeding operation. If one is only generating a small
-    /// number of random numbers, or doesn't need the utmost speed for
-    /// generating each number, `task_rng` and/or `random` may be more
-    /// appropriate.
-    ///
-    /// Reading the randomness from the OS may fail, and any error is
-    /// propagated via the `IoResult` return value.
-    #[cfg(target_word_size="64")]
-    pub fn new() -> IoResult<StdRng> {
-        Isaac64Rng::new().map(|r| StdRng { rng: r })
-    }
-}
-
-impl Rng for StdRng {
-    #[inline]
-    fn next_u32(&mut self) -> u32 {
-        self.rng.next_u32()
-    }
-
-    #[inline]
-    fn next_u64(&mut self) -> u64 {
-        self.rng.next_u64()
-    }
-}
-
-impl<'a> SeedableRng<&'a [uint]> for StdRng {
-    fn reseed(&mut self, seed: &'a [uint]) {
-        // the internal RNG can just be seeded from the above
-        // randomness.
-        self.rng.reseed(unsafe {mem::transmute(seed)})
-    }
-
-    fn from_seed(seed: &'a [uint]) -> StdRng {
-        StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
-    }
-}
-
-/// Create a weak random number generator with a default algorithm and seed.
-///
-/// It returns the fastest `Rng` algorithm currently available in Rust without
-/// consideration for cryptography or security. If you require a specifically
-/// seeded `Rng` for consistency over time you should pick one algorithm and
-/// create the `Rng` yourself.
-///
-/// This will read randomness from the operating system to seed the
-/// generator.
-pub fn weak_rng() -> XorShiftRng {
-    match XorShiftRng::new() {
-        Ok(r) => r,
-        Err(e) => fail!("weak_rng: failed to create seeded RNG: {}", e)
-    }
-}
-
 /// An Xorshift[1] random number
 /// generator.
 ///
 /// The Xorshift algorithm is not suitable for cryptographic purposes
 /// but is very fast. If you do not know for sure that it fits your
-/// requirements, use a more secure one such as `IsaacRng` or `OSRng`.
+/// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
 ///
 /// [1]: Marsaglia, George (July 2003). ["Xorshift
 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
@@ -481,6 +345,23 @@ pub struct XorShiftRng {
     w: u32,
 }
 
+impl XorShiftRng {
+    /// Creates a new XorShiftRng instance which is not seeded.
+    ///
+    /// The initial values of this RNG are constants, so all generators created
+    /// by this function will yield the same stream of random numbers. It is
+    /// highly recommended that this is created through `SeedableRng` instead of
+    /// this function
+    pub fn new_unseeded() -> XorShiftRng {
+        XorShiftRng {
+            x: 0x193a6754,
+            y: 0xa8a7d469,
+            z: 0x97830e05,
+            w: 0x113ba7bb,
+        }
+    }
+}
+
 impl Rng for XorShiftRng {
     #[inline]
     fn next_u32(&mut self) -> u32 {
@@ -521,122 +402,16 @@ fn from_seed(seed: [u32, .. 4]) -> XorShiftRng {
     }
 }
 
-impl XorShiftRng {
-    /// Create an xor shift random number generator with a random seed.
-    pub fn new() -> IoResult<XorShiftRng> {
-        let mut s = [0u8, ..16];
-        let mut r = try!(OSRng::new());
-        loop {
-            r.fill_bytes(s);
-
-            if !s.iter().all(|x| *x == 0) {
-                break;
-            }
-        }
-        let s: [u32, ..4] = unsafe { mem::transmute(s) };
-        Ok(SeedableRng::from_seed(s))
-    }
-}
-
-/// Controls how the task-local RNG is reseeded.
-struct TaskRngReseeder;
-
-impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
-    fn reseed(&mut self, rng: &mut StdRng) {
-        *rng = match StdRng::new() {
-            Ok(r) => r,
-            Err(e) => fail!("could not reseed task_rng: {}", e)
+impl Rand for XorShiftRng {
+    fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
+        let mut tuple: (u32, u32, u32, u32) = rng.gen();
+        while tuple == (0, 0, 0, 0) {
+            tuple = rng.gen();
         }
+        let (x, y, z, w) = tuple;
+        XorShiftRng { x: x, y: y, z: z, w: w }
     }
 }
-static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
-type TaskRngInner = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
-/// The task-local RNG.
-pub struct TaskRng {
-    // This points into TLS (specifically, it points to the endpoint
-    // of a Box stored in TLS, to make it robust against TLS moving
-    // things internally) and so this struct cannot be legally
-    // transferred between tasks *and* it's unsafe to deallocate the
-    // RNG other than when a task is finished.
-    //
-    // The use of unsafe code here is OK if the invariants above are
-    // satisfied; and it allows us to avoid (unnecessarily) using a
-    // GC'd or RC'd pointer.
-    rng: *mut TaskRngInner,
-    marker: marker::NoSend,
-}
-
-/// Retrieve the lazily-initialized task-local random number
-/// generator, seeded by the system. Intended to be used in method
-/// chaining style, e.g. `task_rng().gen::<int>()`.
-///
-/// The RNG provided will reseed itself from the operating system
-/// after generating a certain amount of randomness.
-///
-/// The internal RNG used is platform and architecture dependent, even
-/// if the operating system random number generator is rigged to give
-/// the same sequence always. If absolute consistency is required,
-/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
-pub fn task_rng() -> TaskRng {
-    // used to make space in TLS for a random number generator
-    local_data_key!(TASK_RNG_KEY: Box<TaskRngInner>)
-
-    match TASK_RNG_KEY.get() {
-        None => {
-            let r = match StdRng::new() {
-                Ok(r) => r,
-                Err(e) => fail!("could not initialize task_rng: {}", e)
-            };
-            let mut rng = box reseeding::ReseedingRng::new(r,
-                                                        TASK_RNG_RESEED_THRESHOLD,
-                                                        TaskRngReseeder);
-            let ptr = &mut *rng as *mut TaskRngInner;
-
-            TASK_RNG_KEY.replace(Some(rng));
-
-            TaskRng { rng: ptr, marker: marker::NoSend }
-        }
-        Some(rng) => TaskRng {
-            rng: &**rng as *_ as *mut TaskRngInner,
-            marker: marker::NoSend
-        }
-    }
-}
-
-impl Rng for TaskRng {
-    fn next_u32(&mut self) -> u32 {
-        unsafe { (*self.rng).next_u32() }
-    }
-
-    fn next_u64(&mut self) -> u64 {
-        unsafe { (*self.rng).next_u64() }
-    }
-
-    #[inline]
-    fn fill_bytes(&mut self, bytes: &mut [u8]) {
-        unsafe { (*self.rng).fill_bytes(bytes) }
-    }
-}
-
-/// Generate a random value using the task-local random number
-/// generator.
-///
-/// # Example
-///
-/// ```rust
-/// use rand::random;
-///
-/// if random() {
-///     let x = random();
-///     println!("{}", 2u * x);
-/// } else {
-///     println!("{}", random::<f64>());
-/// }
-/// ```
-#[inline]
-pub fn random<T: Rand>() -> T {
-    task_rng().gen()
-}
 
 /// A wrapper for generating floating point numbers uniformly in the
 /// open interval `(0,1)` (not including either endpoint).
@@ -647,7 +422,7 @@ pub fn random<T: Rand>() -> T {
 ///
 /// # Example
 /// ```rust
-/// use rand::{random, Open01};
+/// use std::rand::{random, Open01};
 ///
 /// let Open01(val) = random::<Open01<f32>>();
 /// println!("f32 from (0,1): {}", val);
@@ -662,263 +437,41 @@ pub fn random<T: Rand>() -> T {
 /// `[0,1)`.
 ///
 /// # Example
+///
 /// ```rust
-/// use rand::{random, Closed01};
+/// use std::rand::{random, Closed01};
 ///
 /// let Closed01(val) = random::<Closed01<f32>>();
 /// println!("f32 from [0,1]: {}", val);
 /// ```
 pub struct Closed01<F>(pub F);
 
-#[cfg(test)]
-mod test {
-    use super::{Rng, task_rng, random, SeedableRng, StdRng};
-
-    struct ConstRng { i: u64 }
-    impl Rng for ConstRng {
-        fn next_u32(&mut self) -> u32 { self.i as u32 }
-        fn next_u64(&mut self) -> u64 { self.i }
-
-        // no fill_bytes on purpose
-    }
-
-    #[test]
-    fn test_fill_bytes_default() {
-        let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 };
-
-        // check every remainder mod 8, both in small and big vectors.
-        let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
-                       80, 81, 82, 83, 84, 85, 86, 87];
-        for &n in lengths.iter() {
-            let mut v = Vec::from_elem(n, 0u8);
-            r.fill_bytes(v.as_mut_slice());
-
-            // use this to get nicer error messages.
-            for (i, &byte) in v.iter().enumerate() {
-                if byte == 0 {
-                    fail!("byte {} of {} is zero", i, n)
-                }
-            }
-        }
-    }
-
-    #[test]
-    fn test_gen_range() {
-        let mut r = task_rng();
-        for _ in range(0, 1000) {
-            let a = r.gen_range(-3i, 42);
-            assert!(a >= -3 && a < 42);
-            assert_eq!(r.gen_range(0, 1), 0);
-            assert_eq!(r.gen_range(-12, -11), -12);
-        }
-
-        for _ in range(0, 1000) {
-            let a = r.gen_range(10, 42);
-            assert!(a >= 10 && a < 42);
-            assert_eq!(r.gen_range(0, 1), 0);
-            assert_eq!(r.gen_range(3_000_000u, 3_000_001), 3_000_000);
-        }
-
-    }
-
-    #[test]
-    #[should_fail]
-    fn test_gen_range_fail_int() {
-        let mut r = task_rng();
-        r.gen_range(5i, -2);
-    }
-
-    #[test]
-    #[should_fail]
-    fn test_gen_range_fail_uint() {
-        let mut r = task_rng();
-        r.gen_range(5u, 2u);
-    }
-
-    #[test]
-    fn test_gen_f64() {
-        let mut r = task_rng();
-        let a = r.gen::<f64>();
-        let b = r.gen::<f64>();
-        debug!("{:?}", (a, b));
-    }
-
-    #[test]
-    fn test_gen_weighted_bool() {
-        let mut r = task_rng();
-        assert_eq!(r.gen_weighted_bool(0u), true);
-        assert_eq!(r.gen_weighted_bool(1u), true);
-    }
-
-    #[test]
-    fn test_gen_ascii_str() {
-        let mut r = task_rng();
-        debug!("{}", r.gen_ascii_str(10u));
-        debug!("{}", r.gen_ascii_str(10u));
-        debug!("{}", r.gen_ascii_str(10u));
-        assert_eq!(r.gen_ascii_str(0u).len(), 0u);
-        assert_eq!(r.gen_ascii_str(10u).len(), 10u);
-        assert_eq!(r.gen_ascii_str(16u).len(), 16u);
-    }
-
-    #[test]
-    fn test_gen_vec() {
-        let mut r = task_rng();
-        assert_eq!(r.gen_vec::<u8>(0u).len(), 0u);
-        assert_eq!(r.gen_vec::<u8>(10u).len(), 10u);
-        assert_eq!(r.gen_vec::<f64>(16u).len(), 16u);
-    }
-
-    #[test]
-    fn test_choose() {
-        let mut r = task_rng();
-        assert_eq!(r.choose([1, 1, 1]).map(|&x|x), Some(1));
-
-        let v: &[int] = &[];
-        assert_eq!(r.choose(v), None);
-    }
-
-    #[test]
-    fn test_shuffle() {
-        let mut r = task_rng();
-        let empty: &mut [int] = &mut [];
-        r.shuffle(empty);
-        let mut one = [1];
-        r.shuffle(one);
-        assert_eq!(one.as_slice(), &[1]);
-
-        let mut two = [1, 2];
-        r.shuffle(two);
-        assert!(two == [1, 2] || two == [2, 1]);
-
-        let mut x = [1, 1, 1];
-        r.shuffle(x);
-        assert_eq!(x.as_slice(), &[1, 1, 1]);
-    }
-
-    #[test]
-    fn test_task_rng() {
-        let mut r = task_rng();
-        r.gen::<int>();
-        let mut v = [1, 1, 1];
-        r.shuffle(v);
-        assert_eq!(v.as_slice(), &[1, 1, 1]);
-        assert_eq!(r.gen_range(0u, 1u), 0u);
-    }
-
-    #[test]
-    fn test_random() {
-        // not sure how to test this aside from just getting some values
-        let _n : uint = random();
-        let _f : f32 = random();
-        let _o : Option<Option<i8>> = random();
-        let _many : ((),
-                     (Box<uint>,
-                      @int,
-                      Box<Option<Box<(@u32, Box<(@bool,)>)>>>),
-                     (u8, i8, u16, i16, u32, i32, u64, i64),
-                     (f32, (f64, (f64,)))) = random();
-    }
-
-    #[test]
-    fn test_sample() {
-        let min_val = 1;
-        let max_val = 100;
-
-        let mut r = task_rng();
-        let vals = range(min_val, max_val).collect::<Vec<int>>();
-        let small_sample = r.sample(vals.iter(), 5);
-        let large_sample = r.sample(vals.iter(), vals.len() + 5);
-
-        assert_eq!(small_sample.len(), 5);
-        assert_eq!(large_sample.len(), vals.len());
-
-        assert!(small_sample.iter().all(|e| {
-            **e >= min_val && **e <= max_val
-        }));
-    }
-
-    #[test]
-    fn test_std_rng_seeded() {
-        let s = task_rng().gen_vec::<uint>(256);
-        let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
-        let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
-    }
-
-    #[test]
-    fn test_std_rng_reseed() {
-        let s = task_rng().gen_vec::<uint>(256);
-        let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
-        let string1 = r.gen_ascii_str(100);
-
-        r.reseed(s.as_slice());
-
-        let string2 = r.gen_ascii_str(100);
-        assert_eq!(string1, string2);
-    }
+#[cfg(not(test))]
+mod std {
+    pub use core::{option, fmt}; // fail!()
 }
 
 #[cfg(test)]
-static RAND_BENCH_N: u64 = 100;
-
-#[cfg(test)]
-mod bench {
-    extern crate test;
-    use self::test::Bencher;
-    use {XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N};
-    use std::mem::size_of;
-
-    #[bench]
-    fn rand_xorshift(b: &mut Bencher) {
-        let mut rng = XorShiftRng::new().unwrap();
-        b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
-                rng.gen::<uint>();
-            }
-        });
-        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
-    }
+mod test {
+    use std::rand;
 
-    #[bench]
-    fn rand_isaac(b: &mut Bencher) {
-        let mut rng = IsaacRng::new().unwrap();
-        b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
-                rng.gen::<uint>();
-            }
-        });
-        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
-    }
+    pub struct MyRng<R> { inner: R }
 
-    #[bench]
-    fn rand_isaac64(b: &mut Bencher) {
-        let mut rng = Isaac64Rng::new().unwrap();
-        b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
-                rng.gen::<uint>();
+    impl<R: rand::Rng> ::Rng for MyRng<R> {
+        fn next_u32(&mut self) -> u32 {
+            fn next<T: rand::Rng>(t: &mut T) -> u32 {
+                use std::rand::Rng;
+                t.next_u32()
             }
-        });
-        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+            next(&mut self.inner)
+        }
     }
 
-    #[bench]
-    fn rand_std(b: &mut Bencher) {
-        let mut rng = StdRng::new().unwrap();
-        b.iter(|| {
-            for _ in range(0, RAND_BENCH_N) {
-                rng.gen::<uint>();
-            }
-        });
-        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+    pub fn rng() -> MyRng<rand::TaskRng> {
+        MyRng { inner: rand::task_rng() }
     }
 
-    #[bench]
-    fn rand_shuffle_100(b: &mut Bencher) {
-        let mut rng = XorShiftRng::new().unwrap();
-        let x : &mut[uint] = [1,..100];
-        b.iter(|| {
-            rng.shuffle(x);
-        })
+    pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
+        MyRng { inner: rand::weak_rng() }
     }
 }
diff --git a/src/librand/os.rs b/src/librand/os.rs
deleted file mode 100644 (file)
index 0e1d01a..0000000
+++ /dev/null
@@ -1,240 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <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.
-
-//! Interfaces to the operating system provided random number
-//! generators.
-
-pub use self::imp::OSRng;
-
-#[cfg(unix)]
-mod imp {
-    use Rng;
-    use reader::ReaderRng;
-    use std::io::{IoResult, File};
-
-    /// A random number generator that retrieves randomness straight from
-    /// the operating system. Platform sources:
-    ///
-    /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
-    ///   `/dev/urandom`.
-    /// - Windows: calls `CryptGenRandom`, using the default cryptographic
-    ///   service provider with the `PROV_RSA_FULL` type.
-    ///
-    /// This does not block.
-    #[cfg(unix)]
-    pub struct OSRng {
-        inner: ReaderRng<File>
-    }
-
-    impl OSRng {
-        /// Create a new `OSRng`.
-        pub fn new() -> IoResult<OSRng> {
-            let reader = try!(File::open(&Path::new("/dev/urandom")));
-            let reader_rng = ReaderRng::new(reader);
-
-            Ok(OSRng { inner: reader_rng })
-        }
-    }
-
-    impl Rng for OSRng {
-        fn next_u32(&mut self) -> u32 {
-            self.inner.next_u32()
-        }
-        fn next_u64(&mut self) -> u64 {
-            self.inner.next_u64()
-        }
-        fn fill_bytes(&mut self, v: &mut [u8]) {
-            self.inner.fill_bytes(v)
-        }
-    }
-}
-
-#[cfg(windows)]
-mod imp {
-    extern crate libc;
-
-    use Rng;
-    use std::io::{IoResult, IoError};
-    use std::mem;
-    use std::os;
-    use std::rt::stack;
-    use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
-
-    type HCRYPTPROV = c_ulong;
-
-    /// A random number generator that retrieves randomness straight from
-    /// the operating system. Platform sources:
-    ///
-    /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
-    ///   `/dev/urandom`.
-    /// - Windows: calls `CryptGenRandom`, using the default cryptographic
-    ///   service provider with the `PROV_RSA_FULL` type.
-    ///
-    /// This does not block.
-    pub struct OSRng {
-        hcryptprov: HCRYPTPROV
-    }
-
-    static PROV_RSA_FULL: DWORD = 1;
-    static CRYPT_SILENT: DWORD = 64;
-    static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
-    static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
-
-    extern "system" {
-        fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
-                                pszContainer: LPCSTR,
-                                pszProvider: LPCSTR,
-                                dwProvType: DWORD,
-                                dwFlags: DWORD) -> BOOL;
-        fn CryptGenRandom(hProv: HCRYPTPROV,
-                          dwLen: DWORD,
-                          pbBuffer: *mut BYTE) -> BOOL;
-        fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
-    }
-
-    impl OSRng {
-        /// Create a new `OSRng`.
-        pub fn new() -> IoResult<OSRng> {
-            let mut hcp = 0;
-            let mut ret = unsafe {
-                CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
-                                     PROV_RSA_FULL,
-                                     CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
-            };
-
-            // FIXME #13259:
-            // It turns out that if we can't acquire a context with the
-            // NTE_BAD_SIGNATURE error code, the documentation states:
-            //
-            //     The provider DLL signature could not be verified. Either the
-            //     DLL or the digital signature has been tampered with.
-            //
-            // Sounds fishy, no? As it turns out, our signature can be bad
-            // because our Thread Information Block (TIB) isn't exactly what it
-            // expects. As to why, I have no idea. The only data we store in the
-            // TIB is the stack limit for each thread, but apparently that's
-            // enough to make the signature valid.
-            //
-            // Furthermore, this error only happens the *first* time we call
-            // CryptAcquireContext, so we don't have to worry about future
-            // calls.
-            //
-            // Anyway, the fix employed here is that if we see this error, we
-            // pray that we're not close to the end of the stack, temporarily
-            // set the stack limit to 0 (what the TIB originally was), acquire a
-            // context, and then reset the stack limit.
-            //
-            // Again, I'm not sure why this is the fix, nor why we're getting
-            // this error. All I can say is that this seems to allow libnative
-            // to progress where it otherwise would be hindered. Who knew?
-            if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
-                unsafe {
-                    let limit = stack::get_sp_limit();
-                    stack::record_sp_limit(0);
-                    ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
-                                               PROV_RSA_FULL,
-                                               CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
-                    stack::record_sp_limit(limit);
-                }
-            }
-
-            if ret == 0 {
-                Err(IoError::last_error())
-            } else {
-                Ok(OSRng { hcryptprov: hcp })
-            }
-        }
-    }
-
-    impl Rng for OSRng {
-        fn next_u32(&mut self) -> u32 {
-            let mut v = [0u8, .. 4];
-            self.fill_bytes(v);
-            unsafe { mem::transmute(v) }
-        }
-        fn next_u64(&mut self) -> u64 {
-            let mut v = [0u8, .. 8];
-            self.fill_bytes(v);
-            unsafe { mem::transmute(v) }
-        }
-        fn fill_bytes(&mut self, v: &mut [u8]) {
-            let ret = unsafe {
-                CryptGenRandom(self.hcryptprov, v.len() as DWORD,
-                               v.as_mut_ptr())
-            };
-            if ret == 0 {
-                fail!("couldn't generate random bytes: {}", os::last_os_error());
-            }
-        }
-    }
-
-    impl Drop for OSRng {
-        fn drop(&mut self) {
-            let ret = unsafe {
-                CryptReleaseContext(self.hcryptprov, 0)
-            };
-            if ret == 0 {
-                fail!("couldn't release context: {}", os::last_os_error());
-            }
-        }
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use super::OSRng;
-    use Rng;
-    use std::task;
-
-    #[test]
-    fn test_os_rng() {
-        let mut r = OSRng::new().unwrap();
-
-        r.next_u32();
-        r.next_u64();
-
-        let mut v = [0u8, .. 1000];
-        r.fill_bytes(v);
-    }
-
-    #[test]
-    fn test_os_rng_tasks() {
-
-        let mut txs = vec!();
-        for _ in range(0, 20) {
-            let (tx, rx) = channel();
-            txs.push(tx);
-            task::spawn(proc() {
-                // wait until all the tasks are ready to go.
-                rx.recv();
-
-                // deschedule to attempt to interleave things as much
-                // as possible (XXX: is this a good test?)
-                let mut r = OSRng::new().unwrap();
-                task::deschedule();
-                let mut v = [0u8, .. 1000];
-
-                for _ in range(0, 100) {
-                    r.next_u32();
-                    task::deschedule();
-                    r.next_u64();
-                    task::deschedule();
-                    r.fill_bytes(v);
-                    task::deschedule();
-                }
-            })
-        }
-
-        // start all the tasks
-        for tx in txs.iter() {
-            tx.send(())
-        }
-    }
-}
index 5846cb5f312cad42c0ebc0c1ea0148d6e47209b5..458a9ba378d98d31a1c805de64c2849c1c0b1c17 100644 (file)
 
 //! The implementations of `Rand` for the built-in types.
 
-use std::char;
-use std::int;
-use std::uint;
+use core::prelude::*;
+use core::char;
+use core::int;
+use core::uint;
 
 use {Rand,Rng};
 
@@ -214,19 +215,10 @@ fn rand<R: Rng>(rng: &mut R) -> Option<T> {
     }
 }
 
-impl<T: Rand> Rand for Box<T> {
-    #[inline]
-    fn rand<R: Rng>(rng: &mut R) -> Box<T> { box rng.gen() }
-}
-
-impl<T: Rand + 'static> Rand for @T {
-    #[inline]
-    fn rand<R: Rng>(rng: &mut R) -> @T { @rng.gen() }
-}
-
 #[cfg(test)]
 mod tests {
-    use {Rng, task_rng, Open01, Closed01};
+    use std::prelude::*;
+    use std::rand::{Rng, task_rng, Open01, Closed01};
 
     struct ConstantRng(u64);
     impl Rng for ConstantRng {
diff --git a/src/librand/reader.rs b/src/librand/reader.rs
deleted file mode 100644 (file)
index e800f64..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <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.
-
-//! A wrapper around any Reader to treat it as an RNG.
-
-use Rng;
-
-/// An RNG that reads random bytes straight from a `Reader`. This will
-/// work best with an infinite reader, but this is not required.
-///
-/// It will fail if it there is insufficient data to fulfill a request.
-///
-/// # Example
-///
-/// ```rust
-/// use rand::{reader, Rng};
-/// use std::io::MemReader;
-///
-/// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8)));
-/// println!("{:x}", rng.gen::<uint>());
-/// ```
-pub struct ReaderRng<R> {
-    reader: R
-}
-
-impl<R: Reader> ReaderRng<R> {
-    /// Create a new `ReaderRng` from a `Reader`.
-    pub fn new(r: R) -> ReaderRng<R> {
-        ReaderRng {
-            reader: r
-        }
-    }
-}
-
-impl<R: Reader> Rng for ReaderRng<R> {
-    fn next_u32(&mut self) -> u32 {
-        // This is designed for speed: reading a LE integer on a LE
-        // platform just involves blitting the bytes into the memory
-        // of the u32, similarly for BE on BE; avoiding byteswapping.
-        if cfg!(target_endian="little") {
-            self.reader.read_le_u32().unwrap()
-        } else {
-            self.reader.read_be_u32().unwrap()
-        }
-    }
-    fn next_u64(&mut self) -> u64 {
-        // see above for explanation.
-        if cfg!(target_endian="little") {
-            self.reader.read_le_u64().unwrap()
-        } else {
-            self.reader.read_be_u64().unwrap()
-        }
-    }
-    fn fill_bytes(&mut self, v: &mut [u8]) {
-        if v.len() == 0 { return }
-        match self.reader.read_at_least(v.len(), v) {
-            Ok(_) => {}
-            Err(e) => fail!("ReaderRng.fill_bytes error: {}", e)
-        }
-    }
-}
-
-#[cfg(test)]
-#[allow(deprecated_owned_vector)]
-mod test {
-    use super::ReaderRng;
-    use std::io::MemReader;
-    use std::mem;
-    use Rng;
-
-    #[test]
-    fn test_reader_rng_u64() {
-        // transmute from the target to avoid endianness concerns.
-        let v = box [1u64, 2u64, 3u64];
-        let bytes: ~[u8] = unsafe {mem::transmute(v)};
-        let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
-
-        assert_eq!(rng.next_u64(), 1);
-        assert_eq!(rng.next_u64(), 2);
-        assert_eq!(rng.next_u64(), 3);
-    }
-    #[test]
-    fn test_reader_rng_u32() {
-        // transmute from the target to avoid endianness concerns.
-        let v = box [1u32, 2u32, 3u32];
-        let bytes: ~[u8] = unsafe {mem::transmute(v)};
-        let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
-
-        assert_eq!(rng.next_u32(), 1);
-        assert_eq!(rng.next_u32(), 2);
-        assert_eq!(rng.next_u32(), 3);
-    }
-    #[test]
-    fn test_reader_rng_fill_bytes() {
-        let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
-        let mut w = [0u8, .. 8];
-
-        let mut rng = ReaderRng::new(MemReader::new(Vec::from_slice(v)));
-        rng.fill_bytes(w);
-
-        assert!(v == w);
-    }
-
-    #[test]
-    #[should_fail]
-    fn test_reader_rng_insufficient_bytes() {
-        let mut rng = ReaderRng::new(MemReader::new(vec!()));
-        let mut v = [0u8, .. 3];
-        rng.fill_bytes(v);
-    }
-}
index fe2ff319c1cadb2ad4ffb0e440fa9d475648278a..09265f28c36fa84f8fb37e59e693b774f4273cfb 100644 (file)
 //! A wrapper around another RNG that reseeds it after it
 //! generates a certain number of random bytes.
 
-use std::default::Default;
+use core::prelude::*;
+
 use {Rng, SeedableRng};
+use core::default::Default;
 
 /// How many bytes of entropy the underling RNG is allowed to generate
 /// before it is reseeded.
@@ -76,13 +78,14 @@ fn fill_bytes(&mut self, dest: &mut [u8]) {
     }
 }
 
-impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R>>
+impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
      SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
     fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
         self.rng.reseed(seed);
         self.reseeder = rsdr;
         self.bytes_generated = 0;
     }
+
     /// Create a new `ReseedingRng` from the given reseeder and
     /// seed. This uses a default value for `generation_threshold`.
     fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
@@ -100,8 +103,8 @@ fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
 /// # Example
 ///
 /// ```rust
-/// use rand::{Rng, SeedableRng, StdRng};
-/// use rand::reseeding::{Reseeder, ReseedingRng};
+/// use std::rand::{Rng, SeedableRng, StdRng};
+/// use std::rand::reseeding::{Reseeder, ReseedingRng};
 ///
 /// struct TickTockReseeder { tick: bool }
 /// impl Reseeder<StdRng> for TickTockReseeder {
@@ -118,7 +121,8 @@ fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
 ///     let mut rng = ReseedingRng::new(inner, 10, rsdr);
 ///
 ///     // this will repeat, because it gets reseeded very regularly.
-///     println!("{}", rng.gen_ascii_str(100));
+///     let s: String = rng.gen_ascii_chars().take(100).collect();
+///     println!("{}", s);
 /// }
 ///
 /// ```
@@ -142,6 +146,9 @@ fn default() -> ReseedWithDefault { ReseedWithDefault }
 
 #[cfg(test)]
 mod test {
+    use std::prelude::*;
+
+    use core::iter::order;
     use super::{ReseedingRng, ReseedWithDefault};
     use std::default::Default;
     use {SeedableRng, Rng};
@@ -187,26 +194,26 @@ fn test_reseeding() {
     fn test_rng_seeded() {
         let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
         let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
-        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
     }
 
     #[test]
     fn test_rng_reseed() {
         let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
-        let string1 = r.gen_ascii_str(100);
+        let string1: String = r.gen_ascii_chars().take(100).collect();
 
         r.reseed((ReseedWithDefault, 3));
 
-        let string2 = r.gen_ascii_str(100);
+        let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
     }
 
     static fill_bytes_v_len: uint = 13579;
     #[test]
     fn test_rng_fill_bytes() {
-        use task_rng;
         let mut v = Vec::from_elem(fill_bytes_v_len, 0u8);
-        task_rng().fill_bytes(v.as_mut_slice());
+        ::test::rng().fill_bytes(v.as_mut_slice());
 
         // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
         // recursed.
index 5958089a8a47d51ee5714bb8184b77248329e21b..61cf1604cd52c725aaf05afa1054725f372bb224 100644 (file)
@@ -425,7 +425,7 @@ pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
     /// # use regex::Captures; fn main() {
     /// let re = regex!(r"([^,\s]+),\s+(\S+)");
     /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
-    ///     format_strbuf!("{} {}", caps.at(2), caps.at(1))
+    ///     format!("{} {}", caps.at(2), caps.at(1))
     /// });
     /// assert_eq!(result.as_slice(), "Bruce Springsteen");
     /// # }
@@ -573,13 +573,13 @@ fn reg_replace<'a>(&'a mut self, _: &Captures) -> MaybeOwned<'a> {
 
 impl<'t> Replacer for &'t str {
     fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> {
-        Owned(caps.expand(*self).into_owned())
+        Owned(caps.expand(*self))
     }
 }
 
 impl<'a> Replacer for |&Captures|: 'a -> String {
     fn reg_replace<'r>(&'r mut self, caps: &Captures) -> MaybeOwned<'r> {
-        Owned((*self)(caps).into_owned())
+        Owned((*self)(caps))
     }
 }
 
@@ -761,9 +761,8 @@ pub fn expand(&self, text: &str) -> String {
         let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
         let text = re.replace_all(text, |refs: &Captures| -> String {
             let (pre, name) = (refs.at(1), refs.at(2));
-            format_strbuf!("{}{}",
-                           pre,
-                           match from_str::<uint>(name.as_slice()) {
+            format!("{}{}", pre,
+                    match from_str::<uint>(name.as_slice()) {
                 None => self.name(name).to_string(),
                 Some(i) => self.at(i).to_string(),
             })
index 8dc6484a13629c02d1535bf4990c3324a2e068cd..7c806ece5c85baaea19b060a44eaea5eac875afb 100644 (file)
@@ -8,9 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use rand::{Rng, task_rng};
-use stdtest::Bencher;
+use std::rand::{Rng, task_rng};
 use std::str;
+use stdtest::Bencher;
+
 use regex::{Regex, NoExpand};
 
 fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
@@ -152,10 +153,10 @@ fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$")
 fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
 fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
 
-#[allow(deprecated_owned_vector)]
 fn gen_text(n: uint) -> String {
     let mut rng = task_rng();
-    let mut bytes = rng.gen_ascii_str(n).into_bytes();
+    let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n)
+                       .collect::<Vec<u8>>();
     for (i, b) in bytes.mut_iter().enumerate() {
         if i % 20 == 0 {
             *b = '\n' as u8
index 82cda6f13f108d183905b400141d1e2447827c2e..1c60e4fbe92c912196cbad11326d628e34081675 100644 (file)
@@ -165,7 +165,7 @@ fn add_archive(&mut self, archive: &Path, name: &str,
             if skip.iter().any(|s| *s == filename) { continue }
             if filename.contains(".SYMDEF") { continue }
 
-            let filename = format_strbuf!("r-{}-{}", name, filename);
+            let filename = format!("r-{}-{}", name, filename);
             let new_filename = file.with_filename(filename);
             try!(fs::rename(file, &new_filename));
             inputs.push(new_filename);
@@ -185,8 +185,8 @@ fn find_library(&self, name: &str) -> Path {
         };
         // On Windows, static libraries sometimes show up as libfoo.a and other
         // times show up as foo.lib
-        let oslibname = format_strbuf!("{}{}.{}", osprefix, name, osext);
-        let unixlibname = format_strbuf!("lib{}.a", name);
+        let oslibname = format!("{}{}.{}", osprefix, name, osext);
+        let unixlibname = format!("lib{}.a", name);
 
         let mut rustpath = filesearch::rust_path();
         rustpath.push(self.sess.target_filesearch().get_lib_path());
index e59ce5cbf67ec11bdde67f9c8829f84356d9ccf8..189562df2d0dd8f6ff72a9752a317e1b441b089e 100644 (file)
@@ -751,10 +751,7 @@ pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> Stri
 }
 
 pub fn output_lib_filename(id: &CrateId) -> String {
-    format_strbuf!("{}-{}-{}",
-                   id.name,
-                   crate_id_hash(id),
-                   id.version_or_default())
+    format!("{}-{}-{}", id.name, crate_id_hash(id), id.version_or_default())
 }
 
 pub fn get_cc_prog(sess: &Session) -> String {
@@ -827,7 +824,7 @@ pub fn filename_for_input(sess: &Session, crate_type: config::CrateType,
     let libname = output_lib_filename(id);
     match crate_type {
         config::CrateTypeRlib => {
-            out_filename.with_filename(format_strbuf!("lib{}.rlib", libname))
+            out_filename.with_filename(format!("lib{}.rlib", libname))
         }
         config::CrateTypeDylib => {
             let (prefix, suffix) = match sess.targ_cfg.os {
@@ -837,13 +834,11 @@ pub fn filename_for_input(sess: &Session, crate_type: config::CrateType,
                 abi::OsAndroid => (loader::ANDROID_DLL_PREFIX, loader::ANDROID_DLL_SUFFIX),
                 abi::OsFreebsd => (loader::FREEBSD_DLL_PREFIX, loader::FREEBSD_DLL_SUFFIX),
             };
-            out_filename.with_filename(format_strbuf!("{}{}{}",
-                                                      prefix,
-                                                      libname,
-                                                      suffix))
+            out_filename.with_filename(format!("{}{}{}", prefix, libname,
+                                               suffix))
         }
         config::CrateTypeStaticlib => {
-            out_filename.with_filename(format_strbuf!("lib{}.a", libname))
+            out_filename.with_filename(format!("lib{}.a", libname))
         }
         config::CrateTypeExecutable => out_filename.clone(),
     }
@@ -1360,7 +1355,7 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
                         cmd.arg("-Wl,-Bdynamic");
                     }
                 }
-                cmd.arg(format_strbuf!("-l{}", *l));
+                cmd.arg(format!("-l{}", *l));
             }
             cstore::NativeFramework => {
                 cmd.arg("-framework");
@@ -1524,7 +1519,7 @@ fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) {
         for &(kind, ref lib) in libs.iter() {
             match kind {
                 cstore::NativeUnknown => {
-                    cmd.arg(format_strbuf!("-l{}", *lib));
+                    cmd.arg(format!("-l{}", *lib));
                 }
                 cstore::NativeFramework => {
                     cmd.arg("-framework");
index 372d66003f2dab8d347fb20b3d0d34ce9c182967..09dfc918967956913af0a122d7b118fd3fae41a8 100644 (file)
@@ -85,8 +85,8 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
                                                     ptr as *libc::c_char,
                                                     bc.len() as libc::size_t) {
                 link::llvm_err(sess,
-                               format_strbuf!("failed to load bc of `{}`",
-                                               name.as_slice()));
+                               format!("failed to load bc of `{}`",
+                                       name.as_slice()));
             }
         });
     }
index bc0d8e2f75c1579c4ec6e7f24b2da07920f6ffad..d04df996186dde7c68086c6c60d352648755626e 100644 (file)
@@ -653,14 +653,14 @@ pub fn pretty_print_input(sess: Session,
         PpmFlowGraph(nodeid) => {
             let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
             let node = ast_map.find(nodeid).unwrap_or_else(|| {
-                sess.fatal(format_strbuf!("--pretty flowgraph couldn't find id: {}",
-                                          nodeid).as_slice())
+                sess.fatal(format!("--pretty flowgraph couldn't find id: {}",
+                                   nodeid).as_slice())
             });
             let block = match node {
                 syntax::ast_map::NodeBlock(block) => block,
                 _ => {
-                    let message = format_strbuf!("--pretty=flowgraph needs block, got {:?}",
-                                                 node);
+                    let message = format!("--pretty=flowgraph needs block, got {:?}",
+                                          node);
 
                     // point to what was found, if there's an
                     // accessible span.
@@ -706,7 +706,7 @@ fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
             io::IoError {
                 detail: Some(match orig_detail {
                     None => m.into_string(),
-                    Some(d) => format_strbuf!("{}: {}", m, d)
+                    Some(d) => format!("{}: {}", m, d)
                 }),
                 ..ioerr
             }
index 781720277a980577ec3615e90d7ad1fcc768f643..95a2c5588365ed2889070e6c5f54be1f84a4fcfa 100644 (file)
@@ -1892,7 +1892,7 @@ pub fn type_to_str(&self, ty: Type) -> String {
 
     pub fn types_to_str(&self, tys: &[Type]) -> String {
         let strs: Vec<String> = tys.iter().map(|t| self.type_to_str(*t)).collect();
-        format_strbuf!("[{}]", strs.connect(",").to_string())
+        format!("[{}]", strs.connect(",").to_string())
     }
 
     pub fn val_to_str(&self, val: ValueRef) -> String {
index 60562e55ce68776655e33ef3655a6361e9b68d5b..4012bbfef75b0bf7a0b3ee0543a6fdf781cb5a90 100644 (file)
@@ -140,7 +140,7 @@ fn encode_family(ebml_w: &mut Encoder, c: char) {
 }
 
 pub fn def_to_str(did: DefId) -> String {
-    format_strbuf!("{}:{}", did.krate, did.node)
+    format!("{}:{}", did.krate, did.node)
 }
 
 fn encode_ty_type_param_defs(ebml_w: &mut Encoder,
index 5cc8d9f7a1569e91aa9c495883e4c9cea1edf3f5..471240f10af3099a9c4c37265fe1ca6166615ee6 100644 (file)
@@ -506,7 +506,7 @@ fn get_metadata_section(os: Os, filename: &Path) -> Result<MetadataBlob, String>
 
 fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, String> {
     if !filename.exists() {
-        return Err(format_strbuf!("no such file: '{}'", filename.display()));
+        return Err(format!("no such file: '{}'", filename.display()));
     }
     if filename.filename_str().unwrap().ends_with(".rlib") {
         // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
@@ -516,16 +516,14 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
             Some(ar) => ar,
             None => {
                 debug!("llvm didn't like `{}`", filename.display());
-                return Err(format_strbuf!("failed to read rlib metadata: \
-                                           '{}'",
-                                          filename.display()));
+                return Err(format!("failed to read rlib metadata: '{}'",
+                                   filename.display()));
             }
         };
         return match ArchiveMetadata::new(archive).map(|ar| MetadataArchive(ar)) {
             None => {
-                return Err((format_strbuf!("failed to read rlib metadata: \
-                                            '{}'",
-                                           filename.display())))
+                return Err((format!("failed to read rlib metadata: '{}'",
+                                    filename.display())))
             }
             Some(blob) => return Ok(blob)
         }
@@ -535,15 +533,14 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
             llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
         });
         if mb as int == 0 {
-            return Err(format_strbuf!("error reading library: '{}'",
-                                      filename.display()))
+            return Err(format!("error reading library: '{}'",
+                               filename.display()))
         }
         let of = match ObjectFile::new(mb) {
             Some(of) => of,
             _ => {
-                return Err((format_strbuf!("provided path not an object \
-                                            file: '{}'",
-                                           filename.display())))
+                return Err((format!("provided path not an object file: '{}'",
+                                    filename.display())))
             }
         };
         let si = mk_section_iter(of.llof);
@@ -556,8 +553,7 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
                 let cbuf = llvm::LLVMGetSectionContents(si.llsi);
                 let csz = llvm::LLVMGetSectionSize(si.llsi) as uint;
                 let mut found =
-                    Err(format_strbuf!("metadata not found: '{}'",
-                                       filename.display()));
+                    Err(format!("metadata not found: '{}'", filename.display()));
                 let cvbuf: *u8 = mem::transmute(cbuf);
                 let vlen = encoder::metadata_encoding_version.len();
                 debug!("checking {} bytes of metadata-version stamp",
@@ -566,8 +562,7 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
                 let version_ok = slice::raw::buf_as_slice(cvbuf, minsz,
                     |buf0| buf0 == encoder::metadata_encoding_version);
                 if !version_ok {
-                    return Err((format_strbuf!("incompatible metadata \
-                                                version found: '{}'",
+                    return Err((format!("incompatible metadata version found: '{}'",
                                         filename.display())));
                 }
 
@@ -579,9 +574,9 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
                         Some(inflated) => found = Ok(MetadataVec(inflated)),
                         None => {
                             found =
-                                Err(format_strbuf!("failed to decompress \
-                                                    metadata for: '{}'",
-                                                   filename.display()))
+                                Err(format!("failed to decompress \
+                                             metadata for: '{}'",
+                                            filename.display()))
                         }
                     }
                 });
@@ -591,8 +586,7 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
             }
             llvm::LLVMMoveToNextSection(si.llsi);
         }
-        return Err(format_strbuf!("metadata not found: '{}'",
-                                  filename.display()));
+        return Err(format!("metadata not found: '{}'", filename.display()));
     }
 }
 
index 1b0e2469b055f0fd659b194c9dae0e43e890e201..aa8a8998e2bd52225bc9a3cf1d2f38964eb1d899 100644 (file)
@@ -69,7 +69,7 @@ fn estimate_sz(u: u64) -> u64 {
         cx.abbrevs.borrow_mut().insert(t, ty_abbrev {
             pos: pos as uint,
             len: len as uint,
-            s: format_strbuf!("\\#{:x}:{:x}\\#", pos, len)
+            s: format!("\\#{:x}:{:x}\\#", pos, len)
         });
     }
 }
index 5dd988a82ce42a37b71d1ba9e88617feac1991b9..e52d8ba3975a0580bf2c8478fe4032069440136e 100644 (file)
@@ -94,7 +94,7 @@ pub fn check_crate(tcx: &ty::ctxt,
     fn make_stat(bccx: &BorrowckCtxt, stat: uint) -> String {
         let stat_f = stat as f64;
         let total = bccx.stats.guaranteed_paths.get() as f64;
-        format_strbuf!("{} ({:.0f}%)", stat  , stat_f * 100.0 / total)
+        format!("{} ({:.0f}%)", stat  , stat_f * 100.0 / total)
     }
 }
 
@@ -297,7 +297,7 @@ fn bitand(&self, rhs: &RestrictionSet) -> RestrictionSet {
 
 impl Repr for RestrictionSet {
     fn repr(&self, _tcx: &ty::ctxt) -> String {
-        format_strbuf!("RestrictionSet(0x{:x})", self.bits as uint)
+        format!("RestrictionSet(0x{:x})", self.bits as uint)
     }
 }
 
@@ -579,27 +579,27 @@ pub fn bckerr_to_str(&self, err: &BckError) -> String {
             err_mutbl => {
                 let descr = match opt_loan_path(&err.cmt) {
                     None => {
-                        format_strbuf!("{} {}",
-                                       err.cmt.mutbl.to_user_str(),
-                                       self.cmt_to_str(&*err.cmt))
+                        format!("{} {}",
+                                err.cmt.mutbl.to_user_str(),
+                                self.cmt_to_str(&*err.cmt))
                     }
                     Some(lp) => {
-                        format_strbuf!("{} {} `{}`",
-                                       err.cmt.mutbl.to_user_str(),
-                                       self.cmt_to_str(&*err.cmt),
-                                       self.loan_path_to_str(&*lp))
+                        format!("{} {} `{}`",
+                                err.cmt.mutbl.to_user_str(),
+                                self.cmt_to_str(&*err.cmt),
+                                self.loan_path_to_str(&*lp))
                     }
                 };
 
                 match err.cause {
                     euv::ClosureCapture(_) => {
-                        format_strbuf!("closure cannot assign to {}", descr)
+                        format!("closure cannot assign to {}", descr)
                     }
                     euv::OverloadedOperator |
                     euv::AddrOf |
                     euv::RefBinding |
                     euv::AutoRef => {
-                        format_strbuf!("cannot borrow {} as mutable", descr)
+                        format!("cannot borrow {} as mutable", descr)
                     }
                     euv::ClosureInvocation => {
                         self.tcx.sess.span_bug(err.span,
@@ -611,20 +611,20 @@ pub fn bckerr_to_str(&self, err: &BckError) -> String {
                 let msg = match opt_loan_path(&err.cmt) {
                     None => "borrowed value".to_string(),
                     Some(lp) => {
-                        format_strbuf!("`{}`", self.loan_path_to_str(&*lp))
+                        format!("`{}`", self.loan_path_to_str(&*lp))
                     }
                 };
-                format_strbuf!("{} does not live long enough", msg)
+                format!("{} does not live long enough", msg)
             }
             err_borrowed_pointer_too_short(..) => {
                 let descr = match opt_loan_path(&err.cmt) {
                     Some(lp) => {
-                        format_strbuf!("`{}`", self.loan_path_to_str(&*lp))
+                        format!("`{}`", self.loan_path_to_str(&*lp))
                     }
                     None => self.cmt_to_str(&*err.cmt),
                 };
 
-                format_strbuf!("lifetime of {} is too short to guarantee \
+                format!("lifetime of {} is too short to guarantee \
                                 its contents can be safely reborrowed",
                                descr)
             }
@@ -713,7 +713,7 @@ pub fn note_and_explain_bckerr(&self, err: BckError) {
             err_borrowed_pointer_too_short(loan_scope, ptr_scope, _) => {
                 let descr = match opt_loan_path(&err.cmt) {
                     Some(lp) => {
-                        format_strbuf!("`{}`", self.loan_path_to_str(&*lp))
+                        format!("`{}`", self.loan_path_to_str(&*lp))
                     }
                     None => self.cmt_to_str(&*err.cmt),
                 };
index 3f7bfefe27e578d911dde59fb45f9e2617403ceb..e2b4dde577a060486eede62ed5302964382deb0f 100644 (file)
@@ -113,7 +113,7 @@ fn pat(&mut self, pat: @ast::Pat, pred: CFGIndex) -> CFGIndex {
                 self.add_node(pat.id, [pred])
             }
 
-            ast::PatUniq(subpat) |
+            ast::PatBox(subpat) |
             ast::PatRegion(subpat) |
             ast::PatIdent(_, _, Some(subpat)) => {
                 let subpat_exit = self.pat(subpat, pred);
index bbea1349c14749f167aec8d6ab423e33ecb9ad9c..e21c8348a8b82cd5c4079b54da55166ca1ab9f17 100644 (file)
@@ -190,7 +190,7 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
                 ty::ty_vec(..) | ty::ty_rptr(..) => {
                     match *ctor {
                         vec(n) => {
-                            Some(format_strbuf!("vectors of length {}", n))
+                            Some(format!("vectors of length {}", n))
                         }
                         _ => None
                     }
@@ -199,8 +199,8 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
             }
         }
     };
-    let msg = format_strbuf!("non-exhaustive patterns{}", match ext {
-        Some(ref s) => format_strbuf!(": {} not covered", *s),
+    let msg = format!("non-exhaustive patterns{}", match ext {
+        Some(ref s) => format!(": {} not covered", *s),
         None => "".to_string()
     });
     cx.tcx.sess.span_err(sp, msg.as_slice());
@@ -383,7 +383,7 @@ fn pat_ctor_id(cx: &MatchCheckCtxt, p: @Pat) -> Option<ctor> {
           _ => Some(single)
         }
       }
-      PatUniq(_) | PatTup(_) | PatRegion(..) => {
+      PatBox(_) | PatTup(_) | PatRegion(..) => {
         Some(single)
       }
       PatVec(ref before, slice, ref after) => {
@@ -764,7 +764,7 @@ fn specialize(cx: &MatchCheckCtxt,
             PatTup(args) => {
                 Some(args.iter().map(|x| *x).collect::<Vec<_>>().append(r.tail()))
             }
-            PatUniq(a) | PatRegion(a) => {
+            PatBox(a) | PatRegion(a) => {
                 Some((vec!(a)).append(r.tail()))
             }
             PatLit(expr) => {
@@ -924,7 +924,7 @@ macro_rules! this_pattern {
     }
 
     match pat.node {
-      PatUniq(sub) | PatRegion(sub) | PatIdent(_, _, Some(sub)) => {
+      PatBox(sub) | PatRegion(sub) | PatIdent(_, _, Some(sub)) => {
         find_refutable(cx, sub, spans)
       }
       PatWild | PatWildMulti | PatIdent(_, _, None) => {}
index 4bf56ad11e3b68644032d9d9a5f62896430ad229..42510f58a144f1056c7d6cf94bc5c3f45fbfcd70 100644 (file)
@@ -49,8 +49,7 @@ fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
         return None;
     };
 
-    Some(format_strbuf!("mutable static items are not allowed to have {}",
-                        suffix))
+    Some(format!("mutable static items are not allowed to have {}", suffix))
 }
 
 struct CheckStaticVisitor<'a> {
index 91c1c0bcf9fb1605639227c0694b2e0e23c21b5e..30792da84e05308919180b5dd321a4babcd7e609 100644 (file)
@@ -112,11 +112,8 @@ fn pre(&self,
                 "".to_string()
             };
 
-            try!(ps.synth_comment(format_strbuf!("id {}: {}{}{}",
-                                                 id,
-                                                 entry_str,
-                                                 gens_str,
-                                                 kills_str)));
+            try!(ps.synth_comment(format!("id {}: {}{}{}", id, entry_str,
+                                          gens_str, kills_str)));
             try!(pp::space(&mut ps.s));
         }
         Ok(())
@@ -895,5 +892,5 @@ fn set_bit(words: &mut [uint], bit: uint) -> bool {
 fn bit_str(bit: uint) -> String {
     let byte = bit >> 8;
     let lobits = 1 << (bit & 0xFF);
-    format_strbuf!("[{}:{}-{:02x}]", bit, byte, lobits)
+    format!("[{}:{}-{:02x}]", bit, byte, lobits)
 }
index 5d26947bee3466ac6e571fbcbf7d88eca396ca65..7bdcb679a59a7c92c3735b08707fb034ae09340e 100644 (file)
@@ -361,8 +361,8 @@ fn warn_dead_code(&mut self,
             .add_lint(DeadCode,
                       id,
                       span,
-                      format_strbuf!("code is never used: `{}`",
-                                     token::get_ident(ident)));
+                      format!("code is never used: `{}`",
+                              token::get_ident(ident)));
     }
 }
 
index 3f00950f4cdd3ff03f9c6bc2446a18645011f295..f80c325496dd43f7b0ffa0303f6b44430cdacade 100644 (file)
@@ -78,8 +78,8 @@ pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
         match self.items.get(it as uint) {
             &Some(id) => Ok(id),
             &None => {
-                Err(format_strbuf!("requires `{}` lang_item",
-                                   LanguageItems::item_name(it as uint)))
+                Err(format!("requires `{}` lang_item",
+                            LanguageItems::item_name(it as uint)))
             }
         }
     }
index 5759a1005f093b20b48f6f41a75ba55caa23967e..beb522802fe1337195c9c4406ba51cc93fe7cefb 100644 (file)
@@ -154,13 +154,13 @@ fn live_node_kind_to_str(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
     let cm = cx.sess.codemap();
     match lnk {
         FreeVarNode(s) => {
-            format_strbuf!("Free var node [{}]", cm.span_to_str(s))
+            format!("Free var node [{}]", cm.span_to_str(s))
         }
         ExprNode(s) => {
-            format_strbuf!("Expr node [{}]", cm.span_to_str(s))
+            format!("Expr node [{}]", cm.span_to_str(s))
         }
         VarDefNode(s) => {
-            format_strbuf!("Var def node [{}]", cm.span_to_str(s))
+            format!("Var def node [{}]", cm.span_to_str(s))
         }
         ExitNode => "Exit node".to_string(),
     }
@@ -1594,12 +1594,11 @@ fn warn_about_unused(&self,
 
                 if is_assigned {
                     self.ir.tcx.sess.add_lint(UnusedVariable, id, sp,
-                        format_strbuf!("variable `{}` is assigned to, \
-                                        but never used",
-                                       *name));
+                        format!("variable `{}` is assigned to, but never used",
+                                *name));
                 } else {
                     self.ir.tcx.sess.add_lint(UnusedVariable, id, sp,
-                        format_strbuf!("unused variable: `{}`", *name));
+                        format!("unused variable: `{}`", *name));
                 }
             }
             true
@@ -1617,8 +1616,7 @@ fn warn_about_dead_assign(&self,
             let r = self.should_warn(var);
             for name in r.iter() {
                 self.ir.tcx.sess.add_lint(DeadAssignment, id, sp,
-                    format_strbuf!("value assigned to `{}` is never read",
-                                   *name));
+                    format!("value assigned to `{}` is never read", *name));
             }
         }
     }
index 10357ef3d567754a45417897f65f1cbb02e092a5..1fad7b1e60c967c133849e938dea897665876632 100644 (file)
@@ -1064,7 +1064,7 @@ pub fn cat_pattern(&self,
             }
           }
 
-          ast::PatUniq(subpat) | ast::PatRegion(subpat) => {
+          ast::PatBox(subpat) | ast::PatRegion(subpat) => {
             // @p1, ~p1
             let subcmt = self.cat_deref(pat, cmt, 0);
             if_ok!(self.cat_pattern(subcmt, subpat, op));
@@ -1120,8 +1120,7 @@ pub fn cmt_to_str(&self, cmt: &cmt_) -> String {
                       "captured outer variable".to_string()
                   }
                   _ => {
-                      format_strbuf!("dereference of `{}`-pointer",
-                                     ptr_sigil(pk))
+                      format!("dereference of `{}`-pointer", ptr_sigil(pk))
                   }
               }
           }
@@ -1254,11 +1253,11 @@ pub fn freely_aliasable(&self, ctxt: &ty::ctxt) -> Option<AliasableReason> {
 
 impl Repr for cmt_ {
     fn repr(&self, tcx: &ty::ctxt) -> String {
-        format_strbuf!("\\{{} id:{} m:{:?} ty:{}\\}",
-                       self.cat.repr(tcx),
-                       self.id,
-                       self.mutbl,
-                       self.ty.repr(tcx))
+        format!("\\{{} id:{} m:{:?} ty:{}\\}",
+                self.cat.repr(tcx),
+                self.id,
+                self.mutbl,
+                self.ty.repr(tcx))
     }
 }
 
@@ -1271,19 +1270,16 @@ fn repr(&self, tcx: &ty::ctxt) -> String {
             cat_local(..) |
             cat_upvar(..) |
             cat_arg(..) => {
-                format_strbuf!("{:?}", *self)
+                format!("{:?}", *self)
             }
             cat_deref(ref cmt, derefs, ptr) => {
-                format_strbuf!("{}-{}{}->",
-                               cmt.cat.repr(tcx),
-                               ptr_sigil(ptr),
-                               derefs)
+                format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
             }
             cat_interior(ref cmt, interior) => {
-                format_strbuf!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
+                format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
             }
             cat_downcast(ref cmt) => {
-                format_strbuf!("{}->(enum)", cmt.cat.repr(tcx))
+                format!("{}->(enum)", cmt.cat.repr(tcx))
             }
             cat_discr(ref cmt, _) => {
                 cmt.cat.repr(tcx)
@@ -1309,7 +1305,7 @@ fn repr(&self, _tcx: &ty::ctxt) -> String {
             InteriorField(NamedField(fld)) => {
                 token::get_name(fld).get().to_str().to_string()
             }
-            InteriorField(PositionalField(i)) => format_strbuf!("\\#{:?}", i),
+            InteriorField(PositionalField(i)) => format!("\\#{:?}", i),
             InteriorElement(_) => "[]".to_string(),
         }
     }
index 1f2bb643b3cff40f4e1a61bd6d6bbac2ffa13851..5b47336efe5e8ef2181e8f844a5af457444f7858 100644 (file)
@@ -547,9 +547,7 @@ fn ensure_public(&self, span: Span, to_check: ast::DefId,
                      source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
         let id = match self.def_privacy(to_check) {
             ExternallyDenied => {
-                return Some((span,
-                             format_strbuf!("{} is private", msg),
-                             None))
+                return Some((span, format!("{} is private", msg), None))
             }
             Allowable => return None,
             DisallowedBy(id) => id,
@@ -560,11 +558,9 @@ fn ensure_public(&self, span: Span, to_check: ast::DefId,
         // because the item itself is private or because its parent is private
         // and its parent isn't in our ancestry.
         let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
-            return Some((span,
-                         format_strbuf!("{} is private", msg),
-                         None));
+            return Some((span, format!("{} is private", msg), None));
         } else {
-            (span, format_strbuf!("{} is inaccessible", msg))
+            (span, format!("{} is inaccessible", msg))
         };
         let item = match self.tcx.map.find(id) {
             Some(ast_map::NodeItem(item)) => {
@@ -600,9 +596,8 @@ fn ensure_public(&self, span: Span, to_check: ast::DefId,
             ast::ItemEnum(..) => "enum",
             _ => return Some((err_span, err_msg, None))
         };
-        let msg = format_strbuf!("{} `{}` is private",
-                                 desc,
-                                 token::get_ident(item.ident));
+        let msg = format!("{} `{}` is private", desc,
+                          token::get_ident(item.ident));
         Some((err_span, err_msg, Some((span, msg))))
     }
 
index 6f42769891ea5131d3cdf329ee8e3e85e8243f71..802f2d5ccab76ccc91f568db97dd51c9acea5ef6 100644 (file)
@@ -671,7 +671,7 @@ fn is_binding_pat(pat: &ast::Pat) -> bool {
                 subpats.iter().any(|&p| is_binding_pat(p))
             }
 
-            ast::PatUniq(subpat) => {
+            ast::PatBox(subpat) => {
                 is_binding_pat(subpat)
             }
 
index 8df57e7adfbe82b723d7fcd3b9db796bb1a4bf24..494f6591d39713dcf99efc9ad363391469d5a7b0 100644 (file)
@@ -405,7 +405,7 @@ fn repr(&self, tcx: &ty::ctxt) -> String {
             // for many programs, this just take too long to serialize
             self.pats.repr(tcx)
         } else {
-            format_strbuf!("{} pats", self.pats.len())
+            format!("{} pats", self.pats.len())
         }
     }
 }
@@ -838,7 +838,7 @@ fn enter_uniq<'a, 'b>(
     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
     enter_match(bcx, dm, m, col, val, |p| {
         match p.node {
-            ast::PatUniq(sub) => {
+            ast::PatBox(sub) => {
                 Some(vec!(sub))
             }
             _ => {
@@ -1105,7 +1105,7 @@ macro_rules! any_pat (
 )
 
 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
-    any_pat!(m, ast::PatUniq(_))
+    any_pat!(m, ast::PatBox(_))
 }
 
 fn any_region_pat(m: &[Match], col: uint) -> bool {
@@ -2270,7 +2270,7 @@ fn bind_irrefutable_pat<'a>(
                                            binding_mode, cleanup_scope);
             }
         }
-        ast::PatUniq(inner) => {
+        ast::PatBox(inner) => {
             let llbox = Load(bcx, val);
             bcx = bind_irrefutable_pat(bcx, inner, llbox, binding_mode, cleanup_scope);
         }
index 140f60c1ea9731ca6ded23e0a730b82403e779f5..db19fa521ce31cb4bb54a864b81af776b714ce52 100644 (file)
@@ -72,7 +72,7 @@ pub fn trans_inline_asm<'a>(bcx: &'a Block<'a>, ia: &ast::InlineAsm)
 
     let mut clobbers = getClobbers();
     if !ia.clobbers.get().is_empty() && !clobbers.is_empty() {
-        clobbers = format_strbuf!("{},{}", ia.clobbers.get(), clobbers);
+        clobbers = format!("{},{}", ia.clobbers.get(), clobbers);
     } else {
         clobbers.push_str(ia.clobbers.get());
     }
index 77ce3b3249f3b4adc9f5e533b0a183e3fe56d331..386ad66ebd6c4640555e760f1e4125da8e6d613c 100644 (file)
@@ -698,10 +698,9 @@ fn iter_variant<'r,
                   for variant in (*variants).iter() {
                       let variant_cx =
                           fcx.new_temp_block(
-                              format_strbuf!("enum-iter-variant-{}",
-                                             variant.disr_val
-                                                    .to_str()
-                                                    .as_slice()).as_slice());
+                              format!("enum-iter-variant-{}",
+                                      variant.disr_val.to_str().as_slice())
+                                     .as_slice());
                       match adt::trans_case(cx, &*repr, variant.disr_val) {
                           _match::single_result(r) => {
                               AddCase(llswitch, r.val, variant_cx.llbb)
index 6aecbd2a17e79974e6e10454e0ffd8af8b057297..47d8ecec021309ac024d77a8e47bc1ee14383e51 100644 (file)
@@ -763,9 +763,9 @@ fn block_name(&self, prefix: &str) -> String {
          */
 
         match self.kind {
-            CustomScopeKind => format_strbuf!("{}_custom_", prefix),
-            AstScopeKind(id) => format_strbuf!("{}_ast_{}_", prefix, id),
-            LoopScopeKind(id, _) => format_strbuf!("{}_loop_{}_", prefix, id),
+            CustomScopeKind => format!("{}_custom_", prefix),
+            AstScopeKind(id) => format!("{}_ast_{}_", prefix, id),
+            LoopScopeKind(id, _) => format!("{}_loop_{}_", prefix, id),
         }
     }
 }
index 29ea9157126d8e641e8f5438488d020a1e90ca2a..9e8d6926f12e1e1f12eb3d920b714b31bd5aa87d 100644 (file)
@@ -105,7 +105,7 @@ pub struct EnvValue {
 
 impl EnvValue {
     pub fn to_str(&self, ccx: &CrateContext) -> String {
-        format_strbuf!("{}({})", self.action, self.datum.to_str(ccx))
+        format!("{}({})", self.action, self.datum.to_str(ccx))
     }
 }
 
index 6cd6511b40ad366b93a8617eef82b3c6039f4162..7e63c1a18f74a26959352de51ba497d539def590 100644 (file)
@@ -195,7 +195,7 @@ pub fn validate(&self) {
 }
 
 fn param_substs_to_str(this: &param_substs, tcx: &ty::ctxt) -> String {
-    format_strbuf!("param_substs({})", this.substs.repr(tcx))
+    format!("param_substs({})", this.substs.repr(tcx))
 }
 
 impl Repr for param_substs {
@@ -478,7 +478,7 @@ pub fn ty_to_str(&self, t: ty::t) -> String {
 
     pub fn to_str(&self) -> String {
         let blk: *Block = self;
-        format_strbuf!("[block {}]", blk)
+        format!("[block {}]", blk)
     }
 }
 
index 860c82cc9de6975b1cb67f3a66d45b1e20b8d909..1e0d3e16ab12d2ceee223e825b39a6e2c8454759 100644 (file)
@@ -625,10 +625,10 @@ pub fn shallow_copy_and_take<'a>(&self,
 
     #[allow(dead_code)] // useful for debugging
     pub fn to_str(&self, ccx: &CrateContext) -> String {
-        format_strbuf!("Datum({}, {}, {:?})",
-                       ccx.tn.val_to_str(self.val),
-                       ty_to_str(ccx.tcx(), self.ty),
-                       self.kind)
+        format!("Datum({}, {}, {:?})",
+                ccx.tn.val_to_str(self.val),
+                ty_to_str(ccx.tcx(), self.ty),
+                self.kind)
     }
 
     pub fn appropriate_rvalue_mode(&self, ccx: &CrateContext) -> RvalueMode {
index 744200c80e8a45a1d9bd926f735337ea9bf1893a..17be522b4da600104a82242e0ba6f6a3cda95575 100644 (file)
@@ -1208,33 +1208,108 @@ fn pointer_type_metadata(cx: &CrateContext,
     return ptr_metadata;
 }
 
+//=-------------------------------------------------------------------------------------------------
+// Common facilities for record-like types (structs, enums, tuples)
+//=-------------------------------------------------------------------------------------------------
+
+enum MemberOffset {
+    FixedMemberOffset { bytes: uint },
+    // For ComputedMemberOffset, the offset is read from the llvm type definition
+    ComputedMemberOffset
+}
+
+// Description of a type member, which can either be a regular field (as in structs or tuples) or
+// an enum variant
+struct MemberDescription {
+    name: String,
+    llvm_type: Type,
+    type_metadata: DIType,
+    offset: MemberOffset,
+}
+
+// A factory for MemberDescriptions. It produces a list of member descriptions for some record-like
+// type. MemberDescriptionFactories are used to defer the creation of type member descriptions in
+// order to break cycles arising from recursive type definitions.
 enum MemberDescriptionFactory {
-    StructMD(StructMemberDescriptionFactory),
-    TupleMD(TupleMemberDescriptionFactory),
-    GeneralMD(GeneralMemberDescriptionFactory),
-    EnumVariantMD(EnumVariantMemberDescriptionFactory)
+    StructMDF(StructMemberDescriptionFactory),
+    TupleMDF(TupleMemberDescriptionFactory),
+    EnumMDF(EnumMemberDescriptionFactory),
+    VariantMDF(VariantMemberDescriptionFactory)
 }
 
 impl MemberDescriptionFactory {
-    fn create_member_descriptions(&self, cx: &CrateContext)
-                                  -> Vec<MemberDescription> {
+    fn create_member_descriptions(&self, cx: &CrateContext) -> Vec<MemberDescription> {
         match *self {
-            StructMD(ref this) => {
+            StructMDF(ref this) => {
                 this.create_member_descriptions(cx)
             }
-            TupleMD(ref this) => {
+            TupleMDF(ref this) => {
                 this.create_member_descriptions(cx)
             }
-            GeneralMD(ref this) => {
+            EnumMDF(ref this) => {
                 this.create_member_descriptions(cx)
             }
-            EnumVariantMD(ref this) => {
+            VariantMDF(ref this) => {
                 this.create_member_descriptions(cx)
             }
         }
     }
 }
 
+// A description of some recursive type. It can either be already finished (as with FinalMetadata)
+// or it is not yet finished, but contains all information needed to generate the missing parts of
+// the description. See the documentation section on Recursive Types at the top of this file for
+// more information.
+enum RecursiveTypeDescription {
+    UnfinishedMetadata {
+        cache_id: uint,
+        metadata_stub: DICompositeType,
+        llvm_type: Type,
+        file_metadata: DIFile,
+        member_description_factory: MemberDescriptionFactory,
+    },
+    FinalMetadata(DICompositeType)
+}
+
+impl RecursiveTypeDescription {
+    // Finishes up the description of the type in question (mostly by providing descriptions of the
+    // fields of the given type) and returns the final type metadata.
+    fn finalize(&self, cx: &CrateContext) -> DICompositeType {
+        match *self {
+            FinalMetadata(metadata) => metadata,
+            UnfinishedMetadata {
+                cache_id,
+                metadata_stub,
+                llvm_type,
+                file_metadata,
+                ref member_description_factory
+            } => {
+                // Insert the stub into the cache in order to allow recursive references ...
+                debug_context(cx).created_types.borrow_mut()
+                                 .insert(cache_id, metadata_stub);
+
+                // ... then create the member descriptions ...
+                let member_descriptions = member_description_factory.create_member_descriptions(cx);
+
+                // ... and attach them to the stub to complete it.
+                set_members_of_composite_type(cx,
+                                              metadata_stub,
+                                              llvm_type,
+                                              member_descriptions.as_slice(),
+                                              file_metadata,
+                                              codemap::DUMMY_SP);
+                return metadata_stub;
+            }
+        }
+    }
+}
+
+
+//=-------------------------------------------------------------------------------------------------
+// Structs
+//=-------------------------------------------------------------------------------------------------
+
+// Creates MemberDescriptions for the fields of a struct
 struct StructMemberDescriptionFactory {
     fields: Vec<ty::field>,
     is_simd: bool,
@@ -1248,7 +1323,7 @@ fn create_member_descriptions(&self, cx: &CrateContext) -> Vec<MemberDescription
         }
 
         let field_size = if self.is_simd {
-            machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields.get(0).mt.ty))
+            machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields.get(0).mt.ty)) as uint
         } else {
             0xdeadbeef
         };
@@ -1262,7 +1337,7 @@ fn create_member_descriptions(&self, cx: &CrateContext) -> Vec<MemberDescription
 
             let offset = if self.is_simd {
                 assert!(field_size != 0xdeadbeef);
-                FixedMemberOffset { bytes: i as u64 * field_size }
+                FixedMemberOffset { bytes: i * field_size }
             } else {
                 ComputedMemberOffset
             };
@@ -1305,7 +1380,7 @@ fn prepare_struct_metadata(cx: &CrateContext,
         metadata_stub: struct_metadata_stub,
         llvm_type: struct_llvm_type,
         file_metadata: file_metadata,
-        member_description_factory: StructMD(StructMemberDescriptionFactory {
+        member_description_factory: StructMDF(StructMemberDescriptionFactory {
             fields: fields,
             is_simd: ty::type_is_simd(cx.tcx(), struct_type),
             span: span,
@@ -1313,49 +1388,12 @@ fn prepare_struct_metadata(cx: &CrateContext,
     }
 }
 
-enum RecursiveTypeDescription {
-    UnfinishedMetadata {
-        cache_id: uint,
-        metadata_stub: DICompositeType,
-        llvm_type: Type,
-        file_metadata: DIFile,
-        member_description_factory: MemberDescriptionFactory,
-    },
-    FinalMetadata(DICompositeType)
-}
 
-impl RecursiveTypeDescription {
-
-    fn finalize(&self, cx: &CrateContext) -> DICompositeType {
-        match *self {
-            FinalMetadata(metadata) => metadata,
-            UnfinishedMetadata {
-                cache_id,
-                metadata_stub,
-                llvm_type,
-                file_metadata,
-                ref member_description_factory
-            } => {
-                // Insert the stub into the cache in order to allow recursive references ...
-                debug_context(cx).created_types.borrow_mut()
-                                 .insert(cache_id, metadata_stub);
-
-                // ... then create the member descriptions ...
-                let member_descriptions = member_description_factory.create_member_descriptions(cx);
-
-                // ... and attach them to the stub to complete it.
-                set_members_of_composite_type(cx,
-                                              metadata_stub,
-                                              llvm_type,
-                                              member_descriptions.as_slice(),
-                                              file_metadata,
-                                              codemap::DUMMY_SP);
-                return metadata_stub;
-            }
-        }
-    }
-}
+//=-------------------------------------------------------------------------------------------------
+// Tuples
+//=-------------------------------------------------------------------------------------------------
 
+// Creates MemberDescriptions for the fields of a tuple
 struct TupleMemberDescriptionFactory {
     component_types: Vec<ty::t> ,
     span: Span,
@@ -1396,72 +1434,209 @@ fn prepare_tuple_metadata(cx: &CrateContext,
                                           span),
         llvm_type: tuple_llvm_type,
         file_metadata: file_metadata,
-        member_description_factory: TupleMD(TupleMemberDescriptionFactory {
+        member_description_factory: TupleMDF(TupleMemberDescriptionFactory {
             component_types: Vec::from_slice(component_types),
             span: span,
         })
     }
 }
 
-struct GeneralMemberDescriptionFactory {
+
+//=-------------------------------------------------------------------------------------------------
+// Enums
+//=-------------------------------------------------------------------------------------------------
+
+// Describes the members of an enum value: An enum is described as a union of structs in DWARF. This
+// MemberDescriptionFactory provides the description for the members of this union; so for every
+// variant of the given enum, this factory will produce one MemberDescription (all with no name and
+// a fixed offset of zero bytes).
+struct EnumMemberDescriptionFactory {
     type_rep: Rc<adt::Repr>,
     variants: Rc<Vec<Rc<ty::VariantInfo>>>,
-    discriminant_type_metadata: ValueRef,
+    discriminant_type_metadata: Option<DIType>,
     containing_scope: DIScope,
     file_metadata: DIFile,
     span: Span,
 }
 
-impl GeneralMemberDescriptionFactory {
-    fn create_member_descriptions(&self, cx: &CrateContext)
-                                  -> Vec<MemberDescription> {
-        // Capture type_rep, so we don't have to copy the struct_defs array
-        let struct_defs = match *self.type_rep {
-            adt::General(_, ref struct_defs) => struct_defs,
-            _ => cx.sess().bug("unreachable")
-        };
-
-        struct_defs
-            .iter()
-            .enumerate()
-            .map(|(i, struct_def)| {
-                let (variant_type_metadata, variant_llvm_type, member_desc_factory) =
+impl EnumMemberDescriptionFactory {
+    fn create_member_descriptions(&self, cx: &CrateContext) -> Vec<MemberDescription> {
+        match *self.type_rep {
+            adt::General(_, ref struct_defs) => {
+                let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
+                    .expect(""));
+
+                struct_defs
+                    .iter()
+                    .enumerate()
+                    .map(|(i, struct_def)| {
+                        let (variant_type_metadata, variant_llvm_type, member_desc_factory) =
+                            describe_enum_variant(cx,
+                                                  struct_def,
+                                                  &**self.variants.get(i),
+                                                  discriminant_info,
+                                                  self.containing_scope,
+                                                  self.file_metadata,
+                                                  self.span);
+
+                        let member_descriptions = member_desc_factory
+                            .create_member_descriptions(cx);
+
+                        set_members_of_composite_type(cx,
+                                                      variant_type_metadata,
+                                                      variant_llvm_type,
+                                                      member_descriptions.as_slice(),
+                                                      self.file_metadata,
+                                                      codemap::DUMMY_SP);
+                        MemberDescription {
+                            name: "".to_string(),
+                            llvm_type: variant_llvm_type,
+                            type_metadata: variant_type_metadata,
+                            offset: FixedMemberOffset { bytes: 0 },
+                        }
+                    }).collect()
+            },
+            adt::Univariant(ref struct_def, _) => {
+                assert!(self.variants.len() <= 1);
+
+                if self.variants.len() == 0 {
+                    vec![]
+                } else {
+                    let (variant_type_metadata, variant_llvm_type, member_description_factory) =
+                        describe_enum_variant(cx,
+                                              struct_def,
+                                              &**self.variants.get(0),
+                                              NoDiscriminant,
+                                              self.containing_scope,
+                                              self.file_metadata,
+                                              self.span);
+
+                    let member_descriptions =
+                        member_description_factory.create_member_descriptions(cx);
+
+                    set_members_of_composite_type(cx,
+                                                  variant_type_metadata,
+                                                  variant_llvm_type,
+                                                  member_descriptions.as_slice(),
+                                                  self.file_metadata,
+                                                  codemap::DUMMY_SP);
+                    vec![
+                        MemberDescription {
+                            name: "".to_string(),
+                            llvm_type: variant_llvm_type,
+                            type_metadata: variant_type_metadata,
+                            offset: FixedMemberOffset { bytes: 0 },
+                        }
+                    ]
+                }
+            }
+            adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
+                // As far as debuginfo is concerned, the pointer this enum represents is still
+                // wrapped in a struct. This is to make the DWARF representation of enums uniform.
+
+                // First create a description of the artifical wrapper struct:
+                let non_null_variant = self.variants.get(non_null_variant_index as uint);
+                let non_null_variant_ident = non_null_variant.name;
+                let non_null_variant_name = token::get_ident(non_null_variant_ident);
+
+                // The llvm type and metadata of the pointer
+                let non_null_llvm_type = type_of::type_of(cx, nnty);
+                let non_null_type_metadata = type_metadata(cx, nnty, self.span);
+
+                // The type of the artificial struct wrapping the pointer
+                let artificial_struct_llvm_type = Type::struct_(cx, &[non_null_llvm_type], false);
+
+                // For the metadata of the wrapper struct, we need to create a MemberDescription
+                // of the struct's single field.
+                let sole_struct_member_description = MemberDescription {
+                    name: match non_null_variant.arg_names {
+                        Some(ref names) => token::get_ident(*names.get(0)).get().to_string(),
+                        None => "".to_string()
+                    },
+                    llvm_type: non_null_llvm_type,
+                    type_metadata: non_null_type_metadata,
+                    offset: FixedMemberOffset { bytes: 0 },
+                };
+
+                // Now we can create the metadata of the artificial struct
+                let artificial_struct_metadata =
+                    composite_type_metadata(cx,
+                                            artificial_struct_llvm_type,
+                                            non_null_variant_name.get(),
+                                            &[sole_struct_member_description],
+                                            self.containing_scope,
+                                            self.file_metadata,
+                                            codemap::DUMMY_SP);
+
+                // Encode the information about the null variant in the union member's name
+                let null_variant_index = (1 - non_null_variant_index) as uint;
+                let null_variant_ident = self.variants.get(null_variant_index).name;
+                let null_variant_name = token::get_ident(null_variant_ident);
+                let union_member_name = format!("RUST$ENCODED$ENUM${}${}", 0, null_variant_name);
+
+                // Finally create the (singleton) list of descriptions of union members
+                vec![
+                    MemberDescription {
+                        name: union_member_name,
+                        llvm_type: artificial_struct_llvm_type,
+                        type_metadata: artificial_struct_metadata,
+                        offset: FixedMemberOffset { bytes: 0 },
+                    }
+                ]
+            },
+            adt::StructWrappedNullablePointer { nonnull: ref struct_def, nndiscr, ptrfield, ..} => {
+                // Create a description of the non-null variant
+                let (variant_type_metadata, variant_llvm_type, member_description_factory) =
                     describe_enum_variant(cx,
                                           struct_def,
-                                          &**self.variants.get(i),
-                                          Some(self.discriminant_type_metadata),
+                                          &**self.variants.get(nndiscr as uint),
+                                          OptimizedDiscriminant(ptrfield),
                                           self.containing_scope,
                                           self.file_metadata,
                                           self.span);
 
-                let member_descriptions =
-                    member_desc_factory.create_member_descriptions(cx);
+                let variant_member_descriptions =
+                    member_description_factory.create_member_descriptions(cx);
 
                 set_members_of_composite_type(cx,
                                               variant_type_metadata,
                                               variant_llvm_type,
-                                              member_descriptions.as_slice(),
+                                              variant_member_descriptions.as_slice(),
                                               self.file_metadata,
                                               codemap::DUMMY_SP);
-                MemberDescription {
-                    name: "".to_string(),
-                    llvm_type: variant_llvm_type,
-                    type_metadata: variant_type_metadata,
-                    offset: FixedMemberOffset { bytes: 0 },
-                }
-        }).collect()
+
+                // Encode the information about the null variant in the union member's name
+                let null_variant_index = (1 - nndiscr) as uint;
+                let null_variant_ident = self.variants.get(null_variant_index).name;
+                let null_variant_name = token::get_ident(null_variant_ident);
+                let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
+                                                ptrfield,
+                                                null_variant_name);
+
+                // Create the (singleton) list of descriptions of union members
+                vec![
+                    MemberDescription {
+                        name: union_member_name,
+                        llvm_type: variant_llvm_type,
+                        type_metadata: variant_type_metadata,
+                        offset: FixedMemberOffset { bytes: 0 },
+                    }
+                ]
+            },
+            adt::CEnum(..) => cx.sess().span_bug(self.span, "This should be unreachable.")
+        }
     }
 }
 
-struct EnumVariantMemberDescriptionFactory {
+// Creates MemberDescriptions for the fields of a single enum variant
+struct VariantMemberDescriptionFactory {
     args: Vec<(String, ty::t)> ,
     discriminant_type_metadata: Option<DIType>,
     span: Span,
 }
 
-impl EnumVariantMemberDescriptionFactory {
-    fn create_member_descriptions(&self, cx: &CrateContext)
-                                  -> Vec<MemberDescription> {
+impl VariantMemberDescriptionFactory {
+    fn create_member_descriptions(&self, cx: &CrateContext) -> Vec<MemberDescription> {
         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
             MemberDescription {
                 name: name.to_string(),
@@ -1476,10 +1651,19 @@ fn create_member_descriptions(&self, cx: &CrateContext)
     }
 }
 
+enum EnumDiscriminantInfo {
+    RegularDiscriminant(DIType),
+    OptimizedDiscriminant(uint),
+    NoDiscriminant
+}
+
+// Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type of the variant, and
+// (3) a MemberDescriptionFactory for producing the descriptions of the fields of the variant. This
+// is a rudimentary version of a full RecursiveTypeDescription.
 fn describe_enum_variant(cx: &CrateContext,
                          struct_def: &adt::Struct,
                          variant_info: &ty::VariantInfo,
-                         discriminant_type_metadata: Option<DIType>,
+                         discriminant_info: EnumDiscriminantInfo,
                          containing_scope: DIScope,
                          file_metadata: DIFile,
                          span: Span)
@@ -1491,7 +1675,7 @@ fn describe_enum_variant(cx: &CrateContext,
                                     .collect::<Vec<_>>()
                                     .as_slice(),
                       struct_def.packed);
-    // Could some consistency checks here: size, align, field count, discr type
+    // Could do some consistency checks here: size, align, field count, discr type
 
     // Find the source code location of the variant's definition
     let variant_definition_span = if variant_info.id.krate == ast::LOCAL_CRATE {
@@ -1520,9 +1704,10 @@ fn describe_enum_variant(cx: &CrateContext,
     };
 
     // If this is not a univariant enum, there is also the (unnamed) discriminant field
-    if discriminant_type_metadata.is_some() {
-        arg_names.insert(0, "".to_string());
-    }
+    match discriminant_info {
+        RegularDiscriminant(_) => arg_names.insert(0, "".to_string()),
+        _ => { /* do nothing */ }
+    };
 
     // Build an array of (field name, field type) pairs to be captured in the factory closure.
     let args: Vec<(String, ty::t)> = arg_names.iter()
@@ -1531,9 +1716,12 @@ fn describe_enum_variant(cx: &CrateContext,
         .collect();
 
     let member_description_factory =
-        EnumVariantMD(EnumVariantMemberDescriptionFactory {
+        VariantMDF(VariantMemberDescriptionFactory {
             args: args,
-            discriminant_type_metadata: discriminant_type_metadata,
+            discriminant_type_metadata: match discriminant_info {
+                RegularDiscriminant(discriminant_type_metadata) => Some(discriminant_type_metadata),
+                _ => None
+            },
             span: span,
         });
 
@@ -1551,21 +1739,6 @@ fn prepare_enum_metadata(cx: &CrateContext,
     let loc = span_start(cx, definition_span);
     let file_metadata = file_metadata(cx, loc.file.name.as_slice());
 
-    // For empty enums there is an early exit. Just describe it as an empty struct with the
-    // appropriate type name
-    if ty::type_is_empty(cx.tcx(), enum_type) {
-        let empty_type_metadata = composite_type_metadata(
-            cx,
-            Type::nil(cx),
-            enum_name.as_slice(),
-            [],
-            containing_scope,
-            file_metadata,
-            definition_span);
-
-        return FinalMetadata(empty_type_metadata);
-    }
-
     let variants = ty::enum_variants(cx.tcx(), enum_def_id);
 
     let enumerators_metadata: Vec<DIDescriptor> = variants
@@ -1626,92 +1799,52 @@ fn prepare_enum_metadata(cx: &CrateContext,
 
     let type_rep = adt::represent_type(cx, enum_type);
 
-    return match *type_rep {
+    let discriminant_type_metadata = match *type_rep {
         adt::CEnum(inttype, _, _) => {
-            FinalMetadata(discriminant_type_metadata(inttype))
-        }
-        adt::Univariant(ref struct_def, _) => {
-            assert!(variants.len() == 1);
-            let (metadata_stub,
-                 variant_llvm_type,
-                 member_description_factory) =
-                    describe_enum_variant(cx,
-                                          struct_def,
-                                          &**variants.get(0),
-                                          None,
-                                          containing_scope,
-                                          file_metadata,
-                                          span);
-            UnfinishedMetadata {
-                cache_id: cache_id_for_type(enum_type),
-                metadata_stub: metadata_stub,
-                llvm_type: variant_llvm_type,
-                file_metadata: file_metadata,
-                member_description_factory: member_description_factory
-            }
-        }
-        adt::General(inttype, _) => {
-            let discriminant_type_metadata = discriminant_type_metadata(inttype);
-            let enum_llvm_type = type_of::type_of(cx, enum_type);
-            let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
-            let unique_id = generate_unique_type_id("DI_ENUM_");
-
-            let enum_metadata = enum_name.as_slice().with_c_str(|enum_name| {
-                unique_id.as_slice().with_c_str(|unique_id| {
-                    unsafe {
-                        llvm::LLVMDIBuilderCreateUnionType(
-                        DIB(cx),
-                        containing_scope,
-                        enum_name,
-                        file_metadata,
-                        loc.line as c_uint,
-                        bytes_to_bits(enum_type_size),
-                        bytes_to_bits(enum_type_align),
-                        0, // Flags
-                        ptr::null(),
-                        0, // RuntimeLang
-                        unique_id)
-                    }
-                })
-            });
+            return FinalMetadata(discriminant_type_metadata(inttype))
+        },
+        adt::RawNullablePointer { .. }           |
+        adt::StructWrappedNullablePointer { .. } |
+        adt::Univariant(..)                      => None,
+        adt::General(inttype, _) => Some(discriminant_type_metadata(inttype)),
+    };
 
-            UnfinishedMetadata {
-                cache_id: cache_id_for_type(enum_type),
-                metadata_stub: enum_metadata,
-                llvm_type: enum_llvm_type,
-                file_metadata: file_metadata,
-                member_description_factory: GeneralMD(GeneralMemberDescriptionFactory {
-                    type_rep: type_rep.clone(),
-                    variants: variants,
-                    discriminant_type_metadata: discriminant_type_metadata,
-                    containing_scope: containing_scope,
-                    file_metadata: file_metadata,
-                    span: span,
-                }),
-            }
-        }
-        adt::RawNullablePointer { nnty, .. } => {
-            FinalMetadata(type_metadata(cx, nnty, span))
-        }
-        adt::StructWrappedNullablePointer { nonnull: ref struct_def, nndiscr, .. } => {
-            let (metadata_stub,
-                 variant_llvm_type,
-                 member_description_factory) =
-                    describe_enum_variant(cx,
-                                          struct_def,
-                                          &**variants.get(nndiscr as uint),
-                                          None,
-                                          containing_scope,
-                                          file_metadata,
-                                          span);
-            UnfinishedMetadata {
-                cache_id: cache_id_for_type(enum_type),
-                metadata_stub: metadata_stub,
-                llvm_type: variant_llvm_type,
-                file_metadata: file_metadata,
-                member_description_factory: member_description_factory
+    let enum_llvm_type = type_of::type_of(cx, enum_type);
+    let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
+    let unique_id = generate_unique_type_id("DI_ENUM_");
+
+    let enum_metadata = enum_name.as_slice().with_c_str(|enum_name| {
+        unique_id.as_slice().with_c_str(|unique_id| {
+            unsafe {
+                llvm::LLVMDIBuilderCreateUnionType(
+                DIB(cx),
+                containing_scope,
+                enum_name,
+                file_metadata,
+                loc.line as c_uint,
+                bytes_to_bits(enum_type_size),
+                bytes_to_bits(enum_type_align),
+                0, // Flags
+                ptr::null(),
+                0, // RuntimeLang
+                unique_id)
             }
-        }
+        })
+    });
+
+    return UnfinishedMetadata {
+        cache_id: cache_id_for_type(enum_type),
+        metadata_stub: enum_metadata,
+        llvm_type: enum_llvm_type,
+        file_metadata: file_metadata,
+        member_description_factory: EnumMDF(EnumMemberDescriptionFactory {
+            type_rep: type_rep.clone(),
+            variants: variants,
+            discriminant_type_metadata: discriminant_type_metadata,
+            containing_scope: containing_scope,
+            file_metadata: file_metadata,
+            span: span,
+        }),
     };
 
     fn get_enum_discriminant_name(cx: &CrateContext, def_id: ast::DefId) -> token::InternedString {
@@ -1725,19 +1858,6 @@ fn get_enum_discriminant_name(cx: &CrateContext, def_id: ast::DefId) -> token::I
     }
 }
 
-enum MemberOffset {
-    FixedMemberOffset { bytes: u64 },
-    // For ComputedMemberOffset, the offset is read from the llvm type definition
-    ComputedMemberOffset
-}
-
-struct MemberDescription {
-    name: String,
-    llvm_type: Type,
-    type_metadata: DIType,
-    offset: MemberOffset,
-}
-
 /// Creates debug information for a composite type, that is, anything that results in a LLVM struct.
 ///
 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
@@ -2342,9 +2462,8 @@ fn cache_id_for_type(t: ty::t) -> uint {
 fn generate_unique_type_id(prefix: &'static str) -> String {
     unsafe {
         static mut unique_id_counter: atomics::AtomicUint = atomics::INIT_ATOMIC_UINT;
-        format_strbuf!("{}{}",
-                       prefix,
-                       unique_id_counter.fetch_add(1, atomics::SeqCst))
+        format!("{}{}", prefix,
+                unique_id_counter.fetch_add(1, atomics::SeqCst))
     }
 }
 
@@ -2633,7 +2752,7 @@ fn walk_pattern(cx: &CrateContext,
                 }
             }
 
-            ast::PatUniq(sub_pat) | ast::PatRegion(sub_pat) => {
+            ast::PatBox(sub_pat) | ast::PatRegion(sub_pat) => {
                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
                 walk_pattern(cx, sub_pat, scope_stack, scope_map);
             }
index f254422226fcdeab451b25e0ef099fd344c20a38..b551b9b1fd7cc70c53c8caaaa829274a0fc014e1 100644 (file)
@@ -88,7 +88,7 @@ pub enum Dest {
 impl Dest {
     pub fn to_str(&self, ccx: &CrateContext) -> String {
         match *self {
-            SaveIn(v) => format_strbuf!("SaveIn({})", ccx.tn.val_to_str(v)),
+            SaveIn(v) => format!("SaveIn({})", ccx.tn.val_to_str(v)),
             Ignore => "Ignore".to_string()
         }
     }
index 6d269756931f7a9c76d38736b894d0686b5c372f..80ccf810e5a93b7d3981cf0b5fb2102e66b8161e 100644 (file)
@@ -474,9 +474,7 @@ fn make_generic_glue(ccx: &CrateContext,
                      name: &str)
                      -> ValueRef {
     let _icx = push_ctxt("make_generic_glue");
-    let glue_name = format_strbuf!("glue {} {}",
-                                   name,
-                                   ty_to_short_str(ccx.tcx(), t));
+    let glue_name = format!("glue {} {}", name, ty_to_short_str(ccx.tcx(), t));
     let _s = StatRecorder::new(ccx, glue_name);
 
     let arena = TypedArena::new();
index 487749f9ecba8aef4c4dc7d3bef06e5d470d5183..3cd1a59abef38c1a56b5b06f34f9cf71afc23151 100644 (file)
@@ -19,7 +19,7 @@ pub trait LlvmRepr {
 impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] {
     fn llrepr(&self, ccx: &CrateContext) -> String {
         let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect();
-        format_strbuf!("[{}]", reprs.connect(","))
+        format!("[{}]", reprs.connect(","))
     }
 }
 
index e0fd872fb06a7330a257db8ee175616713c05619..f77cd0ee44d9ac1cd2b617eeae9b27b926a9a555 100644 (file)
@@ -109,10 +109,10 @@ pub fn monomorphic_fn(ccx: &CrateContext,
         ccx.sess(),
         ccx.tcx.map.find(fn_id.node),
         || {
-            format_strbuf!("while monomorphizing {:?}, couldn't find it in \
-                            the item map (may have attempted to monomorphize \
-                            an item defined in a different crate?)",
-                           fn_id)
+            format!("while monomorphizing {:?}, couldn't find it in \
+                     the item map (may have attempted to monomorphize \
+                     an item defined in a different crate?)",
+                    fn_id)
         });
 
     match map_node {
index 4421c84e86f3c93325f1a7925615650331f75f06..446d2967139c1326d1b76df96c435ac3fd82e430 100644 (file)
@@ -74,12 +74,12 @@ pub struct VecTypes {
 
 impl VecTypes {
     pub fn to_str(&self, ccx: &CrateContext) -> String {
-        format_strbuf!("VecTypes \\{unit_ty={}, llunit_ty={}, \
-                        llunit_size={}, llunit_alloc_size={}\\}",
-                       ty_to_str(ccx.tcx(), self.unit_ty),
-                       ccx.tn.type_to_str(self.llunit_ty),
-                       ccx.tn.val_to_str(self.llunit_size),
-                       self.llunit_alloc_size)
+        format!("VecTypes \\{unit_ty={}, llunit_ty={}, \
+                 llunit_size={}, llunit_alloc_size={}\\}",
+                ty_to_str(ccx.tcx(), self.unit_ty),
+                ccx.tn.type_to_str(self.llunit_ty),
+                ccx.tn.val_to_str(self.llunit_size),
+                self.llunit_alloc_size)
     }
 }
 
index f4fa5002fe909aedd7699bc5f9d0ab92f25c9ad3..0f28ce4d972be4d4d9ea37375645e0538e926147 100644 (file)
@@ -316,9 +316,9 @@ pub fn llvm_type_name(cx: &CrateContext,
                                     did,
                                     false);
     if did.krate == 0 {
-        format_strbuf!("{}.{}", name, tstr)
+        format!("{}.{}", name, tstr)
     } else {
-        format_strbuf!("{}.{}[\\#{}]", name, tstr, did.krate)
+        format!("{}.{}[\\#{}]", name, tstr, did.krate)
     }
 }
 
index fe8db6fa8a11fc1443a72274c4a8587dba810ddf..07033d2bd4a665d0bc959ab2cf335cd7457a18c0 100644 (file)
@@ -3236,7 +3236,7 @@ pub fn ty_sort_str(cx: &ctxt, t: t) -> String {
             ::util::ppaux::ty_to_str(cx, t)
         }
 
-        ty_enum(id, _) => format_strbuf!("enum {}", item_path_str(cx, id)),
+        ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
         ty_box(_) => "@-ptr".to_string(),
         ty_uniq(_) => "box".to_string(),
         ty_vec(_, _) => "vector".to_string(),
@@ -3245,10 +3245,10 @@ pub fn ty_sort_str(cx: &ctxt, t: t) -> String {
         ty_bare_fn(_) => "extern fn".to_string(),
         ty_closure(_) => "fn".to_string(),
         ty_trait(ref inner) => {
-            format_strbuf!("trait {}", item_path_str(cx, inner.def_id))
+            format!("trait {}", item_path_str(cx, inner.def_id))
         }
         ty_struct(id, _) => {
-            format_strbuf!("struct {}", item_path_str(cx, id))
+            format!("struct {}", item_path_str(cx, id))
         }
         ty_tup(_) => "tuple".to_string(),
         ty_infer(TyVar(_)) => "inferred type".to_string(),
@@ -3280,24 +3280,24 @@ fn tstore_to_closure(s: &TraitStore) -> String {
     match *err {
         terr_mismatch => "types differ".to_string(),
         terr_fn_style_mismatch(values) => {
-            format_strbuf!("expected {} fn but found {} fn",
-                           values.expected.to_str(),
-                           values.found.to_str())
+            format!("expected {} fn but found {} fn",
+                    values.expected.to_str(),
+                    values.found.to_str())
         }
         terr_abi_mismatch(values) => {
-            format_strbuf!("expected {} fn but found {} fn",
-                           values.expected.to_str(),
-                           values.found.to_str())
+            format!("expected {} fn but found {} fn",
+                    values.expected.to_str(),
+                    values.found.to_str())
         }
         terr_onceness_mismatch(values) => {
-            format_strbuf!("expected {} fn but found {} fn",
-                           values.expected.to_str(),
-                           values.found.to_str())
+            format!("expected {} fn but found {} fn",
+                    values.expected.to_str(),
+                    values.found.to_str())
         }
         terr_sigil_mismatch(values) => {
-            format_strbuf!("expected {}, found {}",
-                           tstore_to_closure(&values.expected),
-                           tstore_to_closure(&values.found))
+            format!("expected {}, found {}",
+                    tstore_to_closure(&values.expected),
+                    tstore_to_closure(&values.found))
         }
         terr_mutability => "values differ in mutability".to_string(),
         terr_box_mutability => {
@@ -3307,31 +3307,31 @@ fn tstore_to_closure(s: &TraitStore) -> String {
         terr_ptr_mutability => "pointers differ in mutability".to_string(),
         terr_ref_mutability => "references differ in mutability".to_string(),
         terr_ty_param_size(values) => {
-            format_strbuf!("expected a type with {} type params \
-                            but found one with {} type params",
-                           values.expected,
-                           values.found)
+            format!("expected a type with {} type params \
+                     but found one with {} type params",
+                    values.expected,
+                    values.found)
         }
         terr_tuple_size(values) => {
-            format_strbuf!("expected a tuple with {} elements \
-                            but found one with {} elements",
-                           values.expected,
-                           values.found)
+            format!("expected a tuple with {} elements \
+                     but found one with {} elements",
+                    values.expected,
+                    values.found)
         }
         terr_record_size(values) => {
-            format_strbuf!("expected a record with {} fields \
-                            but found one with {} fields",
-                           values.expected,
-                           values.found)
+            format!("expected a record with {} fields \
+                     but found one with {} fields",
+                    values.expected,
+                    values.found)
         }
         terr_record_mutability => {
             "record elements differ in mutability".to_string()
         }
         terr_record_fields(values) => {
-            format_strbuf!("expected a record with field `{}` but found one \
-                            with field `{}`",
-                           token::get_ident(values.expected),
-                           token::get_ident(values.found))
+            format!("expected a record with field `{}` but found one \
+                     with field `{}`",
+                    token::get_ident(values.expected),
+                    token::get_ident(values.found))
         }
         terr_arg_count => {
             "incorrect number of function parameters".to_string()
@@ -3346,69 +3346,60 @@ fn tstore_to_closure(s: &TraitStore) -> String {
             "lifetimes do not intersect".to_string()
         }
         terr_regions_insufficiently_polymorphic(br, _) => {
-            format_strbuf!("expected bound lifetime parameter {}, \
-                            but found concrete lifetime",
-                           bound_region_ptr_to_str(cx, br))
+            format!("expected bound lifetime parameter {}, \
+                     but found concrete lifetime",
+                    bound_region_ptr_to_str(cx, br))
         }
         terr_regions_overly_polymorphic(br, _) => {
-            format_strbuf!("expected concrete lifetime, \
-                            but found bound lifetime parameter {}",
-                           bound_region_ptr_to_str(cx, br))
+            format!("expected concrete lifetime, \
+                     but found bound lifetime parameter {}",
+                    bound_region_ptr_to_str(cx, br))
         }
         terr_trait_stores_differ(_, ref values) => {
-            format_strbuf!("trait storage differs: expected `{}` but found \
-                            `{}`",
-                           trait_store_to_str(cx, (*values).expected),
-                           trait_store_to_str(cx, (*values).found))
+            format!("trait storage differs: expected `{}` but found `{}`",
+                    trait_store_to_str(cx, (*values).expected),
+                    trait_store_to_str(cx, (*values).found))
         }
         terr_sorts(values) => {
-            format_strbuf!("expected {} but found {}",
-                           ty_sort_str(cx, values.expected),
-                           ty_sort_str(cx, values.found))
+            format!("expected {} but found {}",
+                    ty_sort_str(cx, values.expected),
+                    ty_sort_str(cx, values.found))
         }
         terr_traits(values) => {
-            format_strbuf!("expected trait `{}` but found trait `{}`",
-                           item_path_str(cx, values.expected),
-                           item_path_str(cx, values.found))
+            format!("expected trait `{}` but found trait `{}`",
+                    item_path_str(cx, values.expected),
+                    item_path_str(cx, values.found))
         }
         terr_builtin_bounds(values) => {
             if values.expected.is_empty() {
-                format_strbuf!("expected no bounds but found `{}`",
-                               values.found.user_string(cx))
+                format!("expected no bounds but found `{}`",
+                        values.found.user_string(cx))
             } else if values.found.is_empty() {
-                format_strbuf!("expected bounds `{}` but found no bounds",
-                               values.expected.user_string(cx))
+                format!("expected bounds `{}` but found no bounds",
+                        values.expected.user_string(cx))
             } else {
-                format_strbuf!("expected bounds `{}` but found bounds `{}`",
-                               values.expected.user_string(cx),
-                               values.found.user_string(cx))
+                format!("expected bounds `{}` but found bounds `{}`",
+                        values.expected.user_string(cx),
+                        values.found.user_string(cx))
             }
         }
         terr_integer_as_char => {
             "expected an integral type but found `char`".to_string()
         }
         terr_int_mismatch(ref values) => {
-            format_strbuf!("expected `{}` but found `{}`",
-                           values.expected.to_str(),
-                           values.found.to_str())
+            format!("expected `{}` but found `{}`",
+                    values.expected.to_str(),
+                    values.found.to_str())
         }
         terr_float_mismatch(ref values) => {
-            format_strbuf!("expected `{}` but found `{}`",
-                           values.expected.to_str(),
-                           values.found.to_str())
+            format!("expected `{}` but found `{}`",
+                    values.expected.to_str(),
+                    values.found.to_str())
         }
         terr_variadic_mismatch(ref values) => {
-            format_strbuf!("expected {} fn but found {} function",
-                           if values.expected {
-                                "variadic"
-                           } else {
-                                "non-variadic"
-                           },
-                           if values.found {
-                               "variadic"
-                           } else {
-                               "non-variadic"
-                           })
+            format!("expected {} fn but found {} function",
+                    if values.expected { "variadic" } else { "non-variadic" },
+                    if values.found { "variadic" } else { "non-variadic" })
         }
     }
 }
index e223f4001dfd6dff6834f86fd01dfcb5de18846c..565b951df25023a556f40a163b76e8f5941bf30f 100644 (file)
@@ -167,10 +167,8 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: &ast::Pat, path: &ast::Path,
                     fcx.infcx().type_error_message_str_with_expected(pat.span,
                                                        |expected, actual| {
                        expected.map_or("".to_string(), |e| {
-                        format_strbuf!("mismatched types: expected `{}` but \
-                                        found {}",
-                                       e,
-                                       actual)
+                        format!("mismatched types: expected `{}` but found {}",
+                                e, actual)
                         })},
                         Some(expected),
                         "a structure pattern".to_string(),
@@ -223,10 +221,8 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: &ast::Pat, path: &ast::Path,
                                                |expected, actual| {
                                                expected.map_or("".to_string(),
                                                               |e| {
-                        format_strbuf!("mismatched types: expected `{}` but \
-                                        found {}",
-                                       e,
-                                       actual)
+                        format!("mismatched types: expected `{}` but found {}",
+                                e, actual)
                     })
                 },
                 Some(expected),
@@ -555,10 +551,8 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) {
                                                                 |expected, actual| {
                             expected.map_or("".to_string(),
                                             |e| {
-                                format_strbuf!("mismatched types: expected \
-                                                `{}` but found {}",
-                                               e,
-                                               actual)
+                                format!("mismatched types: expected \
+                                        `{}` but found {}", e, actual)
                             })},
                             Some(expected),
                             "a structure pattern".to_string(),
@@ -621,10 +615,8 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) {
                                                                  |expected,
                                                                   actual| {
                         expected.map_or("".to_string(), |e| {
-                            format_strbuf!("mismatched types: expected `{}` \
-                                            but found {}",
-                                           e,
-                                           actual)
+                            format!("mismatched types: expected `{}` \
+                                     but found {}", e, actual)
                         }
                     )},
                     Some(expected),
@@ -634,7 +626,7 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) {
             }
         }
       }
-      ast::PatUniq(inner) => {
+      ast::PatBox(inner) => {
           check_pointer_pat(pcx, Send, inner, pat.id, pat.span, expected);
       }
       ast::PatRegion(inner) => {
@@ -661,10 +653,8 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) {
                 |expected, actual| {
                     expected.map_or("".to_string(),
                                     |e| {
-                        format_strbuf!("mismatched types: expected `{}` but \
-                                        found {}",
-                                       e,
-                                       actual)
+                        format!("mismatched types: expected `{}` but found {}",
+                                e, actual)
                     })
                 },
                 Some(expected),
@@ -753,14 +743,12 @@ pub fn check_pointer_pat(pcx: &pat_ctxt,
                 span,
                 |expected, actual| {
                     expected.map_or("".to_string(), |e| {
-                        format_strbuf!("mismatched types: expected `{}` but \
-                                        found {}",
-                                       e,
-                                       actual)
+                        format!("mismatched types: expected `{}` but found {}",
+                                e, actual)
                     })
                 },
                 Some(expected),
-                format_strbuf!("{} pattern", match pointer_kind {
+                format!("{} pattern", match pointer_kind {
                     Send => "a box",
                     Borrowed => "an `&`-pointer",
                 }),
index 6b3d026e0e515bd79fb6cc35b8a8a53dc4488711..ec2fa0dab5512865918595aa6a9b630a73cbae3b 100644 (file)
@@ -1510,12 +1510,12 @@ fn bug(&self, s: &str) -> ! {
 
 impl Repr for Candidate {
     fn repr(&self, tcx: &ty::ctxt) -> String {
-        format_strbuf!("Candidate(rcvr_ty={}, rcvr_substs={}, method_ty={}, \
-                        origin={:?})",
-                       self.rcvr_match_condition.repr(tcx),
-                       self.rcvr_substs.repr(tcx),
-                       self.method_ty.repr(tcx),
-                       self.origin)
+        format!("Candidate(rcvr_ty={}, rcvr_substs={}, method_ty={}, \
+                 origin={:?})",
+                self.rcvr_match_condition.repr(tcx),
+                self.rcvr_substs.repr(tcx),
+                self.method_ty.repr(tcx),
+                self.origin)
     }
 }
 
@@ -1523,10 +1523,10 @@ impl Repr for RcvrMatchCondition {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             RcvrMatchesIfObject(d) => {
-                format_strbuf!("RcvrMatchesIfObject({})", d.repr(tcx))
+                format!("RcvrMatchesIfObject({})", d.repr(tcx))
             }
             RcvrMatchesIfSubtype(t) => {
-                format_strbuf!("RcvrMatchesIfSubtype({})", t.repr(tcx))
+                format!("RcvrMatchesIfSubtype({})", t.repr(tcx))
             }
         }
     }
index cdf8b50a1cd2390b4884cbd58cc34fb302ad7f0f..f3881abead2489a49629ba54a9bcf80a7ce90ce0 100644 (file)
@@ -1101,7 +1101,7 @@ fn anon_regions(&self, span: Span, count: uint)
 
 impl<'a> FnCtxt<'a> {
     pub fn tag(&self) -> String {
-        format_strbuf!("{}", self as *FnCtxt)
+        format!("{}", self as *FnCtxt)
     }
 
     pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> ty::t {
@@ -1877,21 +1877,21 @@ fn check_argument_types(fcx: &FnCtxt,
                     ty::ty_float(ast::TyF32) => {
                         fcx.type_error_message(arg.span,
                                                |t| {
-                            format_strbuf!("can't pass an {} to variadic \
-                                            function, cast to c_double", t)
+                            format!("can't pass an {} to variadic \
+                                     function, cast to c_double", t)
                         }, arg_ty, None);
                     }
                     ty::ty_int(ast::TyI8) | ty::ty_int(ast::TyI16) | ty::ty_bool => {
                         fcx.type_error_message(arg.span, |t| {
-                            format_strbuf!("can't pass {} to variadic \
-                                            function, cast to c_int",
+                            format!("can't pass {} to variadic \
+                                     function, cast to c_int",
                                            t)
                         }, arg_ty, None);
                     }
                     ty::ty_uint(ast::TyU8) | ty::ty_uint(ast::TyU16) => {
                         fcx.type_error_message(arg.span, |t| {
-                            format_strbuf!("can't pass {} to variadic \
-                                            function, cast to c_uint",
+                            format!("can't pass {} to variadic \
+                                     function, cast to c_uint",
                                            t)
                         }, arg_ty, None);
                     }
@@ -1939,7 +1939,7 @@ fn check_call(fcx: &FnCtxt,
             ty::ty_closure(box ty::ClosureTy {sig: ref sig, ..}) => sig,
             _ => {
                 fcx.type_error_message(call_expr.span, |actual| {
-                    format_strbuf!("expected function but found `{}`", actual)
+                    format!("expected function but found `{}`", actual)
                 }, fn_ty, None);
                 &error_fn_sig
             }
@@ -1993,10 +1993,10 @@ fn check_method_call(fcx: &FnCtxt,
 
                 fcx.type_error_message(method_name.span,
                   |actual| {
-                      format_strbuf!("type `{}` does not implement any \
-                                      method in scope named `{}`",
-                                     actual,
-                                     token::get_ident(method_name.node))
+                      format!("type `{}` does not implement any \
+                               method in scope named `{}`",
+                              actual,
+                              token::get_ident(method_name.node))
                   },
                   expr_t,
                   None);
@@ -2148,12 +2148,12 @@ fn check_binop(fcx: &FnCtxt,
                         if ty::type_is_fp(ty::simd_type(tcx, lhs_t)) {
                             fcx.type_error_message(expr.span,
                                 |actual| {
-                                    format_strbuf!("binary comparison \
-                                                    operation `{}` not \
-                                                    supported for floating \
-                                                    point SIMD vector `{}`",
-                                                   ast_util::binop_to_str(op),
-                                                   actual)
+                                    format!("binary comparison \
+                                             operation `{}` not \
+                                             supported for floating \
+                                             point SIMD vector `{}`",
+                                            ast_util::binop_to_str(op),
+                                            actual)
                                 },
                                 lhs_t,
                                 None
@@ -2180,10 +2180,10 @@ fn check_binop(fcx: &FnCtxt,
             fcx.write_error(rhs.id);
             fcx.type_error_message(expr.span,
                                    |actual| {
-                    format_strbuf!("binary operation `{}` cannot be applied \
-                                   to type `{}`",
-                                   ast_util::binop_to_str(op),
-                                   actual)
+                    format!("binary operation `{}` cannot be applied \
+                             to type `{}`",
+                            ast_util::binop_to_str(op),
+                            actual)
                 },
                 lhs_t,
                 None)
@@ -2195,12 +2195,12 @@ fn check_binop(fcx: &FnCtxt,
         } else {
             fcx.type_error_message(expr.span,
                                    |actual| {
-                                        format_strbuf!("binary assignment \
-                                                        operation `{}=` \
-                                                        cannot be applied to \
-                                                        type `{}`",
-                                                 ast_util::binop_to_str(op),
-                                                 actual)
+                                        format!("binary assignment \
+                                                 operation `{}=` \
+                                                 cannot be applied to \
+                                                 type `{}`",
+                                                ast_util::binop_to_str(op),
+                                                actual)
                                    },
                                    lhs_t,
                                    None);
@@ -2247,10 +2247,9 @@ fn check_user_binop(fcx: &FnCtxt,
         lookup_op_method(fcx, ex, lhs_resolved_t, token::intern(name),
                          trait_did, [lhs_expr, rhs], DontAutoderefReceiver, || {
             fcx.type_error_message(ex.span, |actual| {
-                format_strbuf!("binary operation `{}` cannot be applied to \
-                                type `{}`",
-                               ast_util::binop_to_str(op),
-                               actual)
+                format!("binary operation `{}` cannot be applied to type `{}`",
+                        ast_util::binop_to_str(op),
+                        actual)
             }, lhs_resolved_t, None)
         })
     }
@@ -2265,10 +2264,8 @@ fn check_user_unop(fcx: &FnCtxt,
        lookup_op_method(fcx, ex, rhs_t, token::intern(mname),
                         trait_did, [rhs_expr], DontAutoderefReceiver, || {
             fcx.type_error_message(ex.span, |actual| {
-                format_strbuf!("cannot apply unary operator `{}` to type \
-                                `{}`",
-                               op_str,
-                               actual)
+                format!("cannot apply unary operator `{}` to type `{}`",
+                        op_str, actual)
             }, rhs_t, None);
         })
     }
@@ -2427,10 +2424,8 @@ fn check_field(fcx: &FnCtxt,
                 fcx.type_error_message(
                     expr.span,
                     |actual| {
-                        format_strbuf!("attempted to take value of method \
-                                        `{}` on type `{}`",
-                                       token::get_name(field),
-                                       actual)
+                        format!("attempted to take value of method `{}` on type \
+                                 `{}`", token::get_name(field), actual)
                     },
                     expr_t, None);
 
@@ -2442,7 +2437,7 @@ fn check_field(fcx: &FnCtxt,
                 fcx.type_error_message(
                     expr.span,
                     |actual| {
-                        format_strbuf!("attempted access of field `{}` on \
+                        format!("attempted access of field `{}` on \
                                         type `{}`, but no field with that \
                                         name was found",
                                        token::get_name(field),
@@ -2484,10 +2479,8 @@ fn check_struct_or_variant_fields(fcx: &FnCtxt,
                     fcx.type_error_message(
                       field.ident.span,
                       |actual| {
-                          format_strbuf!("structure `{}` has no field named \
-                                          `{}`",
-                                         actual,
-                                         token::get_ident(field.ident.node))
+                          format!("structure `{}` has no field named `{}`",
+                                  actual, token::get_ident(field.ident.node))
                       },
                       struct_ty,
                       None);
@@ -2876,9 +2869,8 @@ fn check_struct_enum_variant(fcx: &FnCtxt,
                                          no longer be dereferenced");
                                 } else {
                                     fcx.type_error_message(expr.span, |actual| {
-                                        format_strbuf!("type `{}` cannot be \
-                                                        dereferenced",
-                                                       actual)
+                                        format!("type `{}` cannot be \
+                                                dereferenced", actual)
                                     }, oprnd_t, None);
                                 }
                                 ty::mk_err()
@@ -3119,15 +3111,15 @@ fn check_struct_enum_variant(fcx: &FnCtxt,
                 _ => {
                     if ty::type_is_nil(t_e) {
                         fcx.type_error_message(expr.span, |actual| {
-                            format_strbuf!("cast from nil: `{}` as `{}`",
-                                           actual,
-                                           fcx.infcx().ty_to_str(t_1))
+                            format!("cast from nil: `{}` as `{}`",
+                                    actual,
+                                    fcx.infcx().ty_to_str(t_1))
                         }, t_e, None);
                     } else if ty::type_is_nil(t_1) {
                         fcx.type_error_message(expr.span, |actual| {
-                            format_strbuf!("cast to nil: `{}` as `{}`",
-                                           actual,
-                                           fcx.infcx().ty_to_str(t_1))
+                            format!("cast to nil: `{}` as `{}`",
+                                    actual,
+                                    fcx.infcx().ty_to_str(t_1))
                         }, t_e, None);
                     }
 
@@ -3147,9 +3139,8 @@ fn check_struct_enum_variant(fcx: &FnCtxt,
                         let te = fcx.infcx().resolve_type_vars_if_possible(te);
                         if ty::get(te).sty != ty::ty_uint(ast::TyU8) {
                             fcx.type_error_message(expr.span, |actual| {
-                                format_strbuf!("only `u8` can be cast as \
-                                                `char`, not `{}`",
-                                               actual)
+                                format!("only `u8` can be cast as \
+                                         `char`, not `{}`", actual)
                             }, t_e, None);
                         }
                     } else if ty::get(t1).sty == ty::ty_bool {
@@ -3211,9 +3202,9 @@ fn types_compatible(fcx: &FnCtxt, sp: Span,
                         record the issue number in this comment.
                         */
                         fcx.type_error_message(expr.span, |actual| {
-                            format_strbuf!("non-scalar cast: `{}` as `{}`",
-                                           actual,
-                                           fcx.infcx().ty_to_str(t_1))
+                            format!("non-scalar cast: `{}` as `{}`",
+                                    actual,
+                                    fcx.infcx().ty_to_str(t_1))
                         }, t_e, None);
                     }
                 }
@@ -3332,12 +3323,9 @@ fn types_compatible(fcx: &FnCtxt, sp: Span,
                                                     || {
                         fcx.type_error_message(expr.span,
                                                |actual| {
-                                                    format_strbuf!("cannot \
-                                                                    index a \
-                                                                    value of \
-                                                                    type \
-                                                                    `{}`",
-                                                                    actual)
+                                                    format!("cannot index a \
+                                                             value of type \
+                                                             `{}`", actual)
                                                },
                                                base_t,
                                                None);
@@ -3364,9 +3352,8 @@ fn types_compatible(fcx: &FnCtxt, sp: Span,
 pub fn require_uint(fcx: &FnCtxt, sp: Span, t: ty::t) {
     if !type_is_uint(fcx, sp, t) {
         fcx.type_error_message(sp, |actual| {
-            format_strbuf!("mismatched types: expected `uint` type but found \
-                           `{}`",
-                           actual)
+            format!("mismatched types: expected `uint` type but found `{}`",
+                    actual)
         }, t, None);
     }
 }
@@ -3374,9 +3361,8 @@ pub fn require_uint(fcx: &FnCtxt, sp: Span, t: ty::t) {
 pub fn require_integral(fcx: &FnCtxt, sp: Span, t: ty::t) {
     if !type_is_integral(fcx, sp, t) {
         fcx.type_error_message(sp, |actual| {
-            format_strbuf!("mismatched types: expected integral type but \
-                            found `{}`",
-                           actual)
+            format!("mismatched types: expected integral type but found `{}`",
+                    actual)
         }, t, None);
     }
 }
@@ -4513,8 +4499,8 @@ fn param(ccx: &CrateCtxt, n: uint) -> ty::t {
                            i_ty.ty,
                            fty,
                            || {
-                format_strbuf!("intrinsic has wrong type: expected `{}`",
-                               ppaux::ty_to_str(ccx.tcx, fty))
+                format!("intrinsic has wrong type: expected `{}`",
+                        ppaux::ty_to_str(ccx.tcx, fty))
             });
     }
 }
index d7e70205f5d480b04e72011bad0fa9ac2fb3319b..ec7f42313bb8dcb354906d9f736467dbc1cf7a41 100644 (file)
@@ -395,9 +395,9 @@ fn expected_found_str<T:UserString+Resolvable>(
             return None;
         }
 
-        Some(format_strbuf!("expected `{}` but found `{}`",
-                            expected.user_string(self.tcx),
-                            found.user_string(self.tcx)))
+        Some(format!("expected `{}` but found `{}`",
+                     expected.user_string(self.tcx),
+                     found.user_string(self.tcx)))
     }
 
     fn report_concrete_failure(&self,
index 107c54115b42aad91f9c9f66f1ebb12b9ac1eabe..e073d4fcbd77838270e05c53e98ad4c5893a384e 100644 (file)
@@ -252,10 +252,8 @@ pub fn fixup_err_to_str(f: fixup_err) -> String {
       cyclic_ty(_) => "cyclic type of infinite size".to_string(),
       unresolved_region(_) => "unconstrained region".to_string(),
       region_var_bound_by_region_var(r1, r2) => {
-        format_strbuf!("region var {:?} bound by another region var {:?}; \
-                        this is a bug in rustc",
-                       r1,
-                       r2)
+        format!("region var {:?} bound by another region var {:?}; \
+                 this is a bug in rustc", r1, r2)
       }
     }
 }
@@ -657,7 +655,7 @@ pub fn ty_to_str(&self, t: ty::t) -> String {
 
     pub fn tys_to_str(&self, ts: &[ty::t]) -> String {
         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_str(*t)).collect();
-        format_strbuf!("({})", tstrs.connect(", "))
+        format!("({})", tstrs.connect(", "))
     }
 
     pub fn trait_ref_to_str(&self, t: &ty::TraitRef) -> String {
@@ -786,10 +784,9 @@ pub fn report_mismatched_types(&self,
             _ => {
                 // if I leave out : String, it infers &str and complains
                 |actual: String| {
-                    format_strbuf!("mismatched types: expected `{}` but \
-                                    found `{}`",
-                                   self.ty_to_str(resolved_expected),
-                                   actual)
+                    format!("mismatched types: expected `{}` but found `{}`",
+                            self.ty_to_str(resolved_expected),
+                            actual)
                 }
             }
         };
@@ -830,7 +827,7 @@ pub fn span(&self) -> Span {
 
 impl Repr for TypeTrace {
     fn repr(&self, tcx: &ty::ctxt) -> String {
-        format_strbuf!("TypeTrace({})", self.origin.repr(tcx))
+        format!("TypeTrace({})", self.origin.repr(tcx))
     }
 }
 
@@ -852,23 +849,23 @@ impl Repr for TypeOrigin {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             MethodCompatCheck(a) => {
-                format_strbuf!("MethodCompatCheck({})", a.repr(tcx))
+                format!("MethodCompatCheck({})", a.repr(tcx))
             }
             ExprAssignable(a) => {
-                format_strbuf!("ExprAssignable({})", a.repr(tcx))
+                format!("ExprAssignable({})", a.repr(tcx))
             }
-            Misc(a) => format_strbuf!("Misc({})", a.repr(tcx)),
+            Misc(a) => format!("Misc({})", a.repr(tcx)),
             RelateTraitRefs(a) => {
-                format_strbuf!("RelateTraitRefs({})", a.repr(tcx))
+                format!("RelateTraitRefs({})", a.repr(tcx))
             }
             RelateSelfType(a) => {
-                format_strbuf!("RelateSelfType({})", a.repr(tcx))
+                format!("RelateSelfType({})", a.repr(tcx))
             }
             MatchExpression(a) => {
-                format_strbuf!("MatchExpression({})", a.repr(tcx))
+                format!("MatchExpression({})", a.repr(tcx))
             }
             IfExpression(a) => {
-                format_strbuf!("IfExpression({})", a.repr(tcx))
+                format!("IfExpression({})", a.repr(tcx))
             }
         }
     }
@@ -901,41 +898,41 @@ impl Repr for SubregionOrigin {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             Subtype(ref a) => {
-                format_strbuf!("Subtype({})", a.repr(tcx))
+                format!("Subtype({})", a.repr(tcx))
             }
             InfStackClosure(a) => {
-                format_strbuf!("InfStackClosure({})", a.repr(tcx))
+                format!("InfStackClosure({})", a.repr(tcx))
             }
             InvokeClosure(a) => {
-                format_strbuf!("InvokeClosure({})", a.repr(tcx))
+                format!("InvokeClosure({})", a.repr(tcx))
             }
             DerefPointer(a) => {
-                format_strbuf!("DerefPointer({})", a.repr(tcx))
+                format!("DerefPointer({})", a.repr(tcx))
             }
             FreeVariable(a, b) => {
-                format_strbuf!("FreeVariable({}, {})", a.repr(tcx), b)
+                format!("FreeVariable({}, {})", a.repr(tcx), b)
             }
             IndexSlice(a) => {
-                format_strbuf!("IndexSlice({})", a.repr(tcx))
+                format!("IndexSlice({})", a.repr(tcx))
             }
             RelateObjectBound(a) => {
-                format_strbuf!("RelateObjectBound({})", a.repr(tcx))
+                format!("RelateObjectBound({})", a.repr(tcx))
             }
-            Reborrow(a) => format_strbuf!("Reborrow({})", a.repr(tcx)),
+            Reborrow(a) => format!("Reborrow({})", a.repr(tcx)),
             ReborrowUpvar(a, b) => {
-                format_strbuf!("ReborrowUpvar({},{:?})", a.repr(tcx), b)
+                format!("ReborrowUpvar({},{:?})", a.repr(tcx), b)
             }
             ReferenceOutlivesReferent(_, a) => {
-                format_strbuf!("ReferenceOutlivesReferent({})", a.repr(tcx))
+                format!("ReferenceOutlivesReferent({})", a.repr(tcx))
             }
             BindingTypeIsNotValidAtDecl(a) => {
-                format_strbuf!("BindingTypeIsNotValidAtDecl({})", a.repr(tcx))
+                format!("BindingTypeIsNotValidAtDecl({})", a.repr(tcx))
             }
-            CallRcvr(a) => format_strbuf!("CallRcvr({})", a.repr(tcx)),
-            CallArg(a) => format_strbuf!("CallArg({})", a.repr(tcx)),
-            CallReturn(a) => format_strbuf!("CallReturn({})", a.repr(tcx)),
-            AddrOf(a) => format_strbuf!("AddrOf({})", a.repr(tcx)),
-            AutoBorrow(a) => format_strbuf!("AutoBorrow({})", a.repr(tcx)),
+            CallRcvr(a) => format!("CallRcvr({})", a.repr(tcx)),
+            CallArg(a) => format!("CallArg({})", a.repr(tcx)),
+            CallReturn(a) => format!("CallReturn({})", a.repr(tcx)),
+            AddrOf(a) => format!("AddrOf({})", a.repr(tcx)),
+            AutoBorrow(a) => format!("AutoBorrow({})", a.repr(tcx)),
         }
     }
 }
@@ -962,39 +959,32 @@ impl Repr for RegionVariableOrigin {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             MiscVariable(a) => {
-                format_strbuf!("MiscVariable({})", a.repr(tcx))
+                format!("MiscVariable({})", a.repr(tcx))
             }
             PatternRegion(a) => {
-                format_strbuf!("PatternRegion({})", a.repr(tcx))
+                format!("PatternRegion({})", a.repr(tcx))
             }
             AddrOfRegion(a) => {
-                format_strbuf!("AddrOfRegion({})", a.repr(tcx))
+                format!("AddrOfRegion({})", a.repr(tcx))
             }
-            AddrOfSlice(a) => format_strbuf!("AddrOfSlice({})", a.repr(tcx)),
-            Autoref(a) => format_strbuf!("Autoref({})", a.repr(tcx)),
-            Coercion(ref a) => format_strbuf!("Coercion({})", a.repr(tcx)),
+            AddrOfSlice(a) => format!("AddrOfSlice({})", a.repr(tcx)),
+            Autoref(a) => format!("Autoref({})", a.repr(tcx)),
+            Coercion(ref a) => format!("Coercion({})", a.repr(tcx)),
             EarlyBoundRegion(a, b) => {
-                format_strbuf!("EarlyBoundRegion({},{})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("EarlyBoundRegion({},{})", a.repr(tcx), b.repr(tcx))
             }
             LateBoundRegion(a, b) => {
-                format_strbuf!("LateBoundRegion({},{})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("LateBoundRegion({},{})", a.repr(tcx), b.repr(tcx))
             }
             BoundRegionInFnType(a, b) => {
-                format_strbuf!("bound_regionInFnType({},{})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("bound_regionInFnType({},{})", a.repr(tcx),
+                b.repr(tcx))
             }
             BoundRegionInCoherence(a) => {
-                format_strbuf!("bound_regionInCoherence({})", a.repr(tcx))
+                format!("bound_regionInCoherence({})", a.repr(tcx))
             }
             UpvarRegion(a, b) => {
-                format_strbuf!("UpvarRegion({}, {})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("UpvarRegion({}, {})", a.repr(tcx), b.repr(tcx))
             }
         }
     }
index 396dd476e8950e5c2c969337c9caa8db7b4644f9..0efbe7333672cc6c08f5c08253fd4849d2138b86 100644 (file)
@@ -1342,24 +1342,16 @@ impl Repr for Constraint {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             ConstrainVarSubVar(a, b) => {
-                format_strbuf!("ConstrainVarSubVar({}, {})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("ConstrainVarSubVar({}, {})", a.repr(tcx), b.repr(tcx))
             }
             ConstrainRegSubVar(a, b) => {
-                format_strbuf!("ConstrainRegSubVar({}, {})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("ConstrainRegSubVar({}, {})", a.repr(tcx), b.repr(tcx))
             }
             ConstrainVarSubReg(a, b) => {
-                format_strbuf!("ConstrainVarSubReg({}, {})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("ConstrainVarSubReg({}, {})", a.repr(tcx), b.repr(tcx))
             }
             ConstrainRegSubReg(a, b) => {
-                format_strbuf!("ConstrainRegSubReg({}, {})",
-                               a.repr(tcx),
-                               b.repr(tcx))
+                format!("ConstrainRegSubReg({}, {})", a.repr(tcx), b.repr(tcx))
             }
         }
     }
index eaca07b782f7df4b95faa1415a285038abeaf5e1..f03ecd9aee158322f0c81d1332a8383851fd4f1f 100644 (file)
@@ -31,12 +31,11 @@ fn inf_str(&self, cx: &InferCtxt) -> String {
 
 impl InferStr for FnSig {
     fn inf_str(&self, cx: &InferCtxt) -> String {
-        format_strbuf!("({}) -> {}",
-                       self.inputs
-                           .iter()
-                           .map(|a| a.inf_str(cx))
-                           .collect::<Vec<String>>().connect(", "),
-                       self.output.inf_str(cx))
+        format!("({}) -> {}",
+                self.inputs.iter()
+                    .map(|a| a.inf_str(cx))
+                    .collect::<Vec<String>>().connect(", "),
+                self.output.inf_str(cx))
     }
 }
 
@@ -48,7 +47,7 @@ fn inf_str(&self, cx: &InferCtxt) -> String {
 
 impl InferStr for ty::Region {
     fn inf_str(&self, _cx: &InferCtxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
@@ -63,18 +62,16 @@ fn inf_str(&self, cx: &InferCtxt) -> String {
 
 impl<T:InferStr> InferStr for Bounds<T> {
     fn inf_str(&self, cx: &InferCtxt) -> String {
-        format_strbuf!("\\{{} <: {}\\}",
-                       self.lb.inf_str(cx),
-                       self.ub.inf_str(cx))
+        format!("\\{{} <: {}\\}", self.lb.inf_str(cx), self.ub.inf_str(cx))
     }
 }
 
 impl<V:Vid + ToStr,T:InferStr> InferStr for VarValue<V, T> {
     fn inf_str(&self, cx: &InferCtxt) -> String {
         match *self {
-          Redirect(ref vid) => format_strbuf!("Redirect({})", vid.to_str()),
+          Redirect(ref vid) => format!("Redirect({})", vid.to_str()),
           Root(ref pt, rk) => {
-              format_strbuf!("Root({}, {})", pt.inf_str(cx), rk)
+              format!("Root({}, {})", pt.inf_str(cx), rk)
           }
         }
     }
index 995ce56078dba09f8ad41c4ba706bcd4ab740b41..bfe09fdd2b2877dbb7ab7bf6a5dd9cfa58e21bf7 100644 (file)
@@ -201,15 +201,15 @@ impl Repr for vtable_origin {
     fn repr(&self, tcx: &ty::ctxt) -> String {
         match *self {
             vtable_static(def_id, ref tys, ref vtable_res) => {
-                format_strbuf!("vtable_static({:?}:{}, {}, {})",
-                               def_id,
-                               ty::item_path_str(tcx, def_id),
-                               tys.repr(tcx),
-                               vtable_res.repr(tcx))
+                format!("vtable_static({:?}:{}, {}, {})",
+                        def_id,
+                        ty::item_path_str(tcx, def_id),
+                        tys.repr(tcx),
+                        vtable_res.repr(tcx))
             }
 
             vtable_param(x, y) => {
-                format_strbuf!("vtable_param({:?}, {:?})", x, y)
+                format!("vtable_param({:?}, {:?})", x, y)
             }
         }
     }
@@ -231,9 +231,9 @@ pub struct impl_res {
 
 impl Repr for impl_res {
     fn repr(&self, tcx: &ty::ctxt) -> String {
-        format_strbuf!("impl_res \\{trait_vtables={}, self_vtables={}\\}",
-                       self.trait_vtables.repr(tcx),
-                       self.self_vtables.repr(tcx))
+        format!("impl_res \\{trait_vtables={}, self_vtables={}\\}",
+                self.trait_vtables.repr(tcx),
+                self.self_vtables.repr(tcx))
     }
 }
 
@@ -354,8 +354,8 @@ fn check_main_fn_ty(ccx: &CrateCtxt,
 
             require_same_types(tcx, None, false, main_span, main_t, se_ty,
                 || {
-                    format_strbuf!("main function expects type: `{}`",
-                                   ppaux::ty_to_str(ccx.tcx, se_ty))
+                    format!("main function expects type: `{}`",
+                            ppaux::ty_to_str(ccx.tcx, se_ty))
                 });
         }
         _ => {
@@ -407,8 +407,8 @@ fn check_start_fn_ty(ccx: &CrateCtxt,
 
             require_same_types(tcx, None, false, start_span, start_t, se_ty,
                 || {
-                    format_strbuf!("start function expects type: `{}`",
-                                   ppaux::ty_to_str(ccx.tcx, se_ty))
+                    format!("start function expects type: `{}`",
+                            ppaux::ty_to_str(ccx.tcx, se_ty))
                 });
 
         }
index 7b8c62fbf88f19cf751d12dab7453b08643701de..f73666bebf6d7c3ec58cc4c025f608b29f3c8e34 100644 (file)
@@ -86,9 +86,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
           }
           Some(_) | None => {
             // this really should not happen
-            (format_strbuf!("unknown scope: {}.  Please report a bug.",
-                            node_id),
-             None)
+            (format!("unknown scope: {}.  Please report a bug.", node_id), None)
           }
         }
       }
@@ -96,29 +94,28 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
       ReFree(ref fr) => {
         let prefix = match fr.bound_region {
           BrAnon(idx) => {
-              format_strbuf!("the anonymous lifetime \\#{} defined on",
-                             idx + 1)
+              format!("the anonymous lifetime \\#{} defined on", idx + 1)
           }
           BrFresh(_) => "an anonymous lifetime defined on".to_string(),
           _ => {
-              format_strbuf!("the lifetime {} as defined on",
-                             bound_region_ptr_to_str(cx, fr.bound_region))
+              format!("the lifetime {} as defined on",
+                      bound_region_ptr_to_str(cx, fr.bound_region))
           }
         };
 
         match cx.map.find(fr.scope_id) {
           Some(ast_map::NodeBlock(ref blk)) => {
             let (msg, opt_span) = explain_span(cx, "block", blk.span);
-            (format_strbuf!("{} {}", prefix, msg), opt_span)
+            (format!("{} {}", prefix, msg), opt_span)
           }
           Some(ast_map::NodeItem(it)) if match it.node {
                 ast::ItemImpl(..) => true, _ => false} => {
             let (msg, opt_span) = explain_span(cx, "impl", it.span);
-            (format_strbuf!("{} {}", prefix, msg), opt_span)
+            (format!("{} {}", prefix, msg), opt_span)
           }
           Some(_) | None => {
             // this really should not happen
-            (format_strbuf!("{} node {}", prefix, fr.scope_id), None)
+            (format!("{} node {}", prefix, fr.scope_id), None)
           }
         }
       }
@@ -130,17 +127,15 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
       // I believe these cases should not occur (except when debugging,
       // perhaps)
       ty::ReInfer(_) | ty::ReEarlyBound(..) | ty::ReLateBound(..) => {
-        (format_strbuf!("lifetime {:?}", region), None)
+        (format!("lifetime {:?}", region), None)
       }
     };
 
     fn explain_span(cx: &ctxt, heading: &str, span: Span)
         -> (String, Option<Span>) {
         let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
-        (format_strbuf!("the {} at {}:{}",
-                        heading,
-                        lo.line,
-                        lo.col.to_uint()), Some(span))
+        (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
+         Some(span))
     }
 }
 
@@ -154,15 +149,12 @@ pub fn bound_region_to_str(cx: &ctxt,
     let space_str = if space { " " } else { "" };
 
     if cx.sess.verbose() {
-        return format_strbuf!("{}{}{}", prefix, br.repr(cx), space_str)
+        return format!("{}{}{}", prefix, br.repr(cx), space_str)
     }
 
     match br {
         BrNamed(_, name) => {
-            format_strbuf!("{}'{}{}",
-                           prefix,
-                           token::get_name(name),
-                           space_str)
+            format!("{}'{}{}", prefix, token::get_name(name), space_str)
         }
         BrAnon(_) => prefix.to_string(),
         BrFresh(_) => prefix.to_string(),
@@ -180,7 +172,7 @@ pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> St
     let space_str = if space { " " } else { "" };
 
     if cx.sess.verbose() {
-        return format_strbuf!("{}{}{}", prefix, region.repr(cx), space_str)
+        return format!("{}{}{}", prefix, region.repr(cx), space_str)
     }
 
     // These printouts are concise.  They do not contain all the information
@@ -198,8 +190,8 @@ pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> St
             bound_region_to_str(cx, prefix, space, br)
         }
         ty::ReInfer(ReVar(_)) => prefix.to_string(),
-        ty::ReStatic => format_strbuf!("{}'static{}", prefix, space_str),
-        ty::ReEmpty => format_strbuf!("{}'<empty>{}", prefix, space_str),
+        ty::ReStatic => format!("{}'static{}", prefix, space_str),
+        ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
     }
 }
 
@@ -211,30 +203,26 @@ pub fn mutability_to_str(m: ast::Mutability) -> String {
 }
 
 pub fn mt_to_str(cx: &ctxt, m: &mt) -> String {
-    format_strbuf!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty))
+    format!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty))
 }
 
 pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> String {
     match s {
         ty::UniqTraitStore => "Box ".to_string(),
         ty::RegionTraitStore(r, m) => {
-            format_strbuf!("{}{}",
-                           region_ptr_to_str(cx, r),
-                           mutability_to_str(m))
+            format!("{}{}", region_ptr_to_str(cx, r), mutability_to_str(m))
         }
     }
 }
 
 pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> String) -> String {
     let tstrs = ts.iter().map(f).collect::<Vec<String>>();
-    format_strbuf!("[{}]", tstrs.connect(", "))
+    format!("[{}]", tstrs.connect(", "))
 }
 
 pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> String {
-    format_strbuf!("fn{}{} -> {}",
-                   typ.binder_id,
-                   typ.inputs.repr(cx),
-                   typ.output.repr(cx))
+    format!("fn{}{} -> {}", typ.binder_id, typ.inputs.repr(cx),
+            typ.output.repr(cx))
 }
 
 pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> String {
@@ -360,9 +348,9 @@ fn push_sig_to_str(cx: &ctxt,
       ty_uint(t) => ast_util::uint_ty_to_str(t, None,
                                              ast_util::AutoSuffix).to_string(),
       ty_float(t) => ast_util::float_ty_to_str(t).to_string(),
-      ty_box(typ) => format_strbuf!("@{}", ty_to_str(cx, typ)),
-      ty_uniq(typ) => format_strbuf!("~{}", ty_to_str(cx, typ)),
-      ty_ptr(ref tm) => format_strbuf!("*{}", mt_to_str(cx, tm)),
+      ty_box(typ) => format!("@{}", ty_to_str(cx, typ)),
+      ty_uniq(typ) => format!("~{}", ty_to_str(cx, typ)),
+      ty_ptr(ref tm) => format!("*{}", mt_to_str(cx, tm)),
       ty_rptr(r, ref tm) => {
           let mut buf = region_ptr_to_str(cx, r);
           buf.push_str(mt_to_str(cx, tm).as_slice());
@@ -370,7 +358,7 @@ fn push_sig_to_str(cx: &ctxt,
       }
       ty_tup(ref elems) => {
         let strs: Vec<String> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
-        format_strbuf!("({})", strs.connect(","))
+        format!("({})", strs.connect(","))
       }
       ty_closure(ref f) => {
           closure_to_str(cx, *f)
@@ -385,12 +373,12 @@ fn push_sig_to_str(cx: &ctxt,
               Some(def) => token::get_ident(def.ident).get().to_string(),
               // This can only happen when a type mismatch error happens and
               // the actual type has more type parameters than the expected one.
-              None => format_strbuf!("<generic \\#{}>", id)
+              None => format!("<generic \\#{}>", id)
           };
           if !cx.sess.verbose() {
               ident
           } else {
-              format_strbuf!("{}:{:?}", ident, did)
+              format!("{}:{:?}", ident, did)
           }
       }
       ty_self(..) => "Self".to_string(),
@@ -411,19 +399,19 @@ fn push_sig_to_str(cx: &ctxt,
                                substs.tps.as_slice(), did, true);
         let bound_sep = if bounds.is_empty() { "" } else { ":" };
         let bound_str = bounds.repr(cx);
-        format_strbuf!("{}{}{}{}",
-                       trait_store_to_str(cx, store),
-                       ty,
-                       bound_sep,
-                       bound_str)
+        format!("{}{}{}{}",
+                trait_store_to_str(cx, store),
+                ty,
+                bound_sep,
+                bound_str)
       }
       ty_str => "str".to_string(),
       ty_vec(ref mt, sz) => {
           match sz {
               Some(n) => {
-                  format_strbuf!("[{}, .. {}]", mt_to_str(cx, mt), n)
+                  format!("[{}, .. {}]", mt_to_str(cx, mt), n)
               }
-              None => format_strbuf!("[{}]", ty_to_str(cx, mt.ty)),
+              None => format!("[{}]", ty_to_str(cx, mt.ty)),
           }
       }
     }
@@ -476,9 +464,9 @@ pub fn parameterized(cx: &ctxt,
     }
 
     if strs.len() > 0u {
-        format_strbuf!("{}<{}>", base, strs.connect(","))
+        format!("{}<{}>", base, strs.connect(","))
     } else {
-        format_strbuf!("{}", base)
+        format!("{}", base)
     }
 }
 
@@ -503,7 +491,7 @@ impl<T:Repr,U:Repr> Repr for Result<T,U> {
     fn repr(&self, tcx: &ctxt) -> String {
         match self {
             &Ok(ref t) => t.repr(tcx),
-            &Err(ref u) => format_strbuf!("Err({})", u.repr(tcx))
+            &Err(ref u) => format!("Err({})", u.repr(tcx))
         }
     }
 }
@@ -558,17 +546,16 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for ty::TypeParameterDef {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("TypeParameterDef({:?}, {})",
-                       self.def_id,
-                       self.bounds.repr(tcx))
+        format!("TypeParameterDef({:?}, {})", self.def_id,
+                self.bounds.repr(tcx))
     }
 }
 
 impl Repr for ty::RegionParameterDef {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("RegionParameterDef({}, {:?})",
-                       token::get_name(self.name),
-                       self.def_id)
+        format!("RegionParameterDef({}, {:?})",
+                token::get_name(self.name),
+                self.def_id)
     }
 }
 
@@ -580,16 +567,16 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for ty::substs {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("substs(regions={}, self_ty={}, tps={})",
-                       self.regions.repr(tcx),
-                       self.self_ty.repr(tcx),
-                       self.tps.repr(tcx))
+        format!("substs(regions={}, self_ty={}, tps={})",
+                self.regions.repr(tcx),
+                self.self_ty.repr(tcx),
+                self.tps.repr(tcx))
     }
 }
 
 impl Repr for ty::ItemSubsts {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("ItemSubsts({})", self.substs.repr(tcx))
+        format!("ItemSubsts({})", self.substs.repr(tcx))
     }
 }
 
@@ -629,40 +616,38 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for ast::Expr {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("expr({}: {})", self.id, pprust::expr_to_str(self))
+        format!("expr({}: {})", self.id, pprust::expr_to_str(self))
     }
 }
 
 impl Repr for ast::Item {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("item({})", tcx.map.node_to_str(self.id))
+        format!("item({})", tcx.map.node_to_str(self.id))
     }
 }
 
 impl Repr for ast::Stmt {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("stmt({}: {})",
-                       ast_util::stmt_id(self),
-                       pprust::stmt_to_str(self))
+        format!("stmt({}: {})",
+                ast_util::stmt_id(self),
+                pprust::stmt_to_str(self))
     }
 }
 
 impl Repr for ast::Pat {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("pat({}: {})", self.id, pprust::pat_to_str(self))
+        format!("pat({}: {})", self.id, pprust::pat_to_str(self))
     }
 }
 
 impl Repr for ty::BoundRegion {
     fn repr(&self, tcx: &ctxt) -> String {
         match *self {
-            ty::BrAnon(id) => format_strbuf!("BrAnon({})", id),
+            ty::BrAnon(id) => format!("BrAnon({})", id),
             ty::BrNamed(id, name) => {
-                format_strbuf!("BrNamed({}, {})",
-                               id.repr(tcx),
-                               token::get_name(name))
+                format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
             }
-            ty::BrFresh(id) => format_strbuf!("BrFresh({})", id),
+            ty::BrFresh(id) => format!("BrFresh({})", id),
         }
     }
 }
@@ -671,26 +656,26 @@ impl Repr for ty::Region {
     fn repr(&self, tcx: &ctxt) -> String {
         match *self {
             ty::ReEarlyBound(id, index, name) => {
-                format_strbuf!("ReEarlyBound({}, {}, {})",
-                               id,
-                               index,
-                               token::get_name(name))
+                format!("ReEarlyBound({}, {}, {})",
+                        id,
+                        index,
+                        token::get_name(name))
             }
 
             ty::ReLateBound(binder_id, ref bound_region) => {
-                format_strbuf!("ReLateBound({}, {})",
-                               binder_id,
-                               bound_region.repr(tcx))
+                format!("ReLateBound({}, {})",
+                        binder_id,
+                        bound_region.repr(tcx))
             }
 
             ty::ReFree(ref fr) => {
-                format_strbuf!("ReFree({}, {})",
-                               fr.scope_id,
-                               fr.bound_region.repr(tcx))
+                format!("ReFree({}, {})",
+                        fr.scope_id,
+                        fr.bound_region.repr(tcx))
             }
 
             ty::ReScope(id) => {
-                format_strbuf!("ReScope({})", id)
+                format!("ReScope({})", id)
             }
 
             ty::ReStatic => {
@@ -698,11 +683,11 @@ fn repr(&self, tcx: &ctxt) -> String {
             }
 
             ty::ReInfer(ReVar(ref vid)) => {
-                format_strbuf!("ReInfer({})", vid.id)
+                format!("ReInfer({})", vid.id)
             }
 
             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
-                format_strbuf!("re_skolemized({}, {})",
+                format!("re_skolemized({}, {})",
                                id,
                                bound_region.repr(tcx))
             }
@@ -728,7 +713,7 @@ fn repr(&self, tcx: &ctxt) -> String {
                     Some(ast_map::NodeTraitMethod(..)) |
                     Some(ast_map::NodeVariant(..)) |
                     Some(ast_map::NodeStructCtor(..)) => {
-                        return format_strbuf!(
+                        return format!(
                                 "{:?}:{}",
                                 *self,
                                 ty::item_path_str(tcx, *self))
@@ -737,35 +722,32 @@ fn repr(&self, tcx: &ctxt) -> String {
                 }
             }
         }
-        return format_strbuf!("{:?}", *self)
+        return format!("{:?}", *self)
     }
 }
 
 impl Repr for ty::ty_param_bounds_and_ty {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("ty_param_bounds_and_ty \\{generics: {}, ty: {}\\}",
-                       self.generics.repr(tcx),
-                       self.ty.repr(tcx))
+        format!("ty_param_bounds_and_ty \\{generics: {}, ty: {}\\}",
+                self.generics.repr(tcx),
+                self.ty.repr(tcx))
     }
 }
 
 impl Repr for ty::Generics {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("Generics(type_param_defs: {}, \
-                           region_param_defs: {})",
-                 self.type_param_defs().repr(tcx),
-                 self.region_param_defs().repr(tcx))
+        format!("Generics(type_param_defs: {}, region_param_defs: {})",
+                self.type_param_defs().repr(tcx),
+                self.region_param_defs().repr(tcx))
     }
 }
 
 impl Repr for ty::ItemVariances {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("IterVariances(self_param={}, \
-                                type_params={}, \
-                                region_params={})",
-                 self.self_param.repr(tcx),
-                 self.type_params.repr(tcx),
-                 self.region_params.repr(tcx))
+        format!("IterVariances(self_param={}, type_params={}, region_params={})",
+                self.self_param.repr(tcx),
+                self.type_params.repr(tcx),
+                self.region_params.repr(tcx))
     }
 }
 
@@ -777,14 +759,14 @@ fn repr(&self, _: &ctxt) -> String {
 
 impl Repr for ty::Method {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("method(ident: {}, generics: {}, fty: {}, \
-                        explicit_self: {}, vis: {}, def_id: {})",
-                       self.ident.repr(tcx),
-                       self.generics.repr(tcx),
-                       self.fty.repr(tcx),
-                       self.explicit_self.repr(tcx),
-                       self.vis.repr(tcx),
-                       self.def_id.repr(tcx))
+        format!("method(ident: {}, generics: {}, fty: {}, \
+                 explicit_self: {}, vis: {}, def_id: {})",
+                self.ident.repr(tcx),
+                self.generics.repr(tcx),
+                self.fty.repr(tcx),
+                self.explicit_self.repr(tcx),
+                self.vis.repr(tcx),
+                self.def_id.repr(tcx))
     }
 }
 
@@ -802,22 +784,22 @@ fn repr(&self, _tcx: &ctxt) -> String {
 
 impl Repr for ast::ExplicitSelf_ {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
 impl Repr for ast::Visibility {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
 impl Repr for ty::BareFnTy {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
-                       self.fn_style,
-                       self.abi.to_str(),
-                       self.sig.repr(tcx))
+        format!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
+                self.fn_style,
+                self.abi.to_str(),
+                self.sig.repr(tcx))
     }
 }
 
@@ -829,10 +811,10 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for typeck::MethodCallee {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("MethodCallee \\{origin: {}, ty: {}, {}\\}",
-                       self.origin.repr(tcx),
-                       self.ty.repr(tcx),
-                       self.substs.repr(tcx))
+        format!("MethodCallee \\{origin: {}, ty: {}, {}\\}",
+                self.origin.repr(tcx),
+                self.ty.repr(tcx),
+                self.substs.repr(tcx))
     }
 }
 
@@ -840,7 +822,7 @@ impl Repr for typeck::MethodOrigin {
     fn repr(&self, tcx: &ctxt) -> String {
         match self {
             &typeck::MethodStatic(def_id) => {
-                format_strbuf!("MethodStatic({})", def_id.repr(tcx))
+                format!("MethodStatic({})", def_id.repr(tcx))
             }
             &typeck::MethodParam(ref p) => {
                 p.repr(tcx)
@@ -854,27 +836,27 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for typeck::MethodParam {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("MethodParam({},{:?},{:?},{:?})",
-                       self.trait_id.repr(tcx),
-                       self.method_num,
-                       self.param_num,
-                       self.bound_num)
+        format!("MethodParam({},{:?},{:?},{:?})",
+                self.trait_id.repr(tcx),
+                self.method_num,
+                self.param_num,
+                self.bound_num)
     }
 }
 
 impl Repr for typeck::MethodObject {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("MethodObject({},{:?},{:?})",
-                       self.trait_id.repr(tcx),
-                       self.method_num,
-                       self.real_index)
+        format!("MethodObject({},{:?},{:?})",
+                self.trait_id.repr(tcx),
+                self.method_num,
+                self.real_index)
     }
 }
 
 
 impl Repr for ty::RegionVid {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
@@ -886,7 +868,7 @@ fn repr(&self, tcx: &ctxt) -> String {
 
 impl Repr for ty::BuiltinBound {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
@@ -980,29 +962,29 @@ fn user_string(&self, _tcx: &ctxt) -> String {
 
 impl Repr for ty::UpvarId {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("UpvarId({};`{}`;{})",
-                       self.var_id,
-                       ty::local_var_name_str(tcx, self.var_id),
-                       self.closure_expr_id)
+        format!("UpvarId({};`{}`;{})",
+                self.var_id,
+                ty::local_var_name_str(tcx, self.var_id),
+                self.closure_expr_id)
     }
 }
 
 impl Repr for ast::Mutability {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
 impl Repr for ty::BorrowKind {
     fn repr(&self, _tcx: &ctxt) -> String {
-        format_strbuf!("{:?}", *self)
+        format!("{:?}", *self)
     }
 }
 
 impl Repr for ty::UpvarBorrow {
     fn repr(&self, tcx: &ctxt) -> String {
-        format_strbuf!("UpvarBorrow({}, {})",
-                       self.kind.repr(tcx),
-                       self.region.repr(tcx))
+        format!("UpvarBorrow({}, {})",
+                self.kind.repr(tcx),
+                self.region.repr(tcx))
     }
 }
index 48e390b35fb103dc81934d7d805c093a14de754a..610cc992eed6e389fa4705a584baaa67c4947c61 100644 (file)
@@ -1000,7 +1000,7 @@ fn clean(&self) -> Type {
             ty::ty_str => String,
             ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
             ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
-                                                   format_strbuf!("{}", i)),
+                                                   format!("{}", i)),
             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
             ty::ty_rptr(r, mt) => BorrowedRef {
                 lifetime: r.clean(),
@@ -1697,8 +1697,8 @@ fn to_src(&self) -> String {
 fn lit_to_str(lit: &ast::Lit) -> String {
     match lit.node {
         ast::LitStr(ref st, _) => st.get().to_string(),
-        ast::LitBinary(ref data) => format_strbuf!("{:?}", data.as_slice()),
-        ast::LitChar(c) => format_strbuf!("'{}'", c),
+        ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
+        ast::LitChar(c) => format!("'{}'", c),
         ast::LitInt(i, _t) => i.to_str().to_string(),
         ast::LitUint(u, _t) => u.to_str().to_string(),
         ast::LitIntUnsuffixed(i) => i.to_str().to_string(),
@@ -1721,7 +1721,7 @@ fn name_from_pat(p: &ast::Pat) -> String {
         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
                                 which is not allowed in function arguments"),
         PatTup(..) => "(tuple arg NYI)".to_string(),
-        PatUniq(p) => name_from_pat(p),
+        PatBox(p) => name_from_pat(p),
         PatRegion(p) => name_from_pat(p),
         PatLit(..) => {
             warn!("tried to get argument name from PatLit, \
@@ -1822,7 +1822,7 @@ pub struct Macro {
 impl Clean<Item> for doctree::Macro {
     fn clean(&self) -> Item {
         Item {
-            name: Some(format_strbuf!("{}!", self.name.clean())),
+            name: Some(format!("{}!", self.name.clean())),
             attrs: self.attrs.clean(),
             source: self.where.clean(),
             visibility: ast::Public.clean(),
index e3221177afe66684aa3f6401b91f1637a6966d6f..3b3f4378d67ad3589ffb42e982b99176965b2f46 100644 (file)
@@ -356,7 +356,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                                     }
                                 }
                            }
-                           ret.into_owned()
+                           ret
                        })
             }
             clean::Proc(ref decl) => {
@@ -366,7 +366,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                        lifetimes = if decl.lifetimes.len() == 0 {
                            "".to_string()
                        } else {
-                           format_strbuf!("&lt;{:#}&gt;", decl.lifetimes)
+                           format!("&lt;{:#}&gt;", decl.lifetimes)
                        },
                        args = decl.decl.inputs,
                        bounds = if decl.bounds.len() == 0 {
@@ -375,7 +375,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                            let mut m = decl.bounds
                                            .iter()
                                            .map(|s| s.to_str().to_string());
-                           format_strbuf!(
+                           format!(
                                ": {}",
                                m.collect::<Vec<String>>().connect(" + "))
                        },
@@ -388,7 +388,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                        match decl.abi.as_slice() {
                            "" => " extern ".to_string(),
                            "\"Rust\"" => "".to_string(),
-                           s => format_strbuf!(" extern {} ", s)
+                           s => format!(" extern {} ", s)
                        },
                        decl.generics,
                        decl.decl)
index d1153db8d30db95f5b9d6e0d633ad53583c952b3..cafbbaa828bc718e2952943bc8a710f8eb26c7ee 100644 (file)
@@ -223,7 +223,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
         let map = used_header_map.get().unwrap();
         let id = match map.borrow_mut().find_mut(&id) {
             None => id,
-            Some(a) => { *a += 1; format_strbuf!("{}-{}", id, *a - 1) }
+            Some(a) => { *a += 1; format!("{}-{}", id, *a - 1) }
         };
         map.borrow_mut().insert(id.clone(), 1);
 
index d0974c25e95319e2ce2a4b6e9a4d46f67b77741e..22619bdbf851766666fa6f7333521fa3c987d2f3 100644 (file)
@@ -578,7 +578,7 @@ fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
                             if s.as_slice().ends_with("/") {
                                 return Remote(s.to_string());
                             }
-                            return Remote(format_strbuf!("{}/", s));
+                            return Remote(format!("{}/", s));
                         }
                         _ => {}
                     }
@@ -1187,12 +1187,12 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
 fn item_path(item: &clean::Item) -> String {
     match item.inner {
         clean::ModuleItem(..) => {
-            format_strbuf!("{}/index.html", item.name.get_ref())
+            format!("{}/index.html", item.name.get_ref())
         }
         _ => {
-            format_strbuf!("{}.{}.html",
-                           shortty(item).to_static_str(),
-                           *item.name.get_ref())
+            format!("{}.{}.html",
+                    shortty(item).to_static_str(),
+                    *item.name.get_ref())
         }
     }
 }
index 212fe006aa1be8a4e494df8dbfbf6d6bebd000d1..aa01247c1b682b0d813e0952cc6e5621f228152a 100644 (file)
@@ -154,7 +154,7 @@ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
                 sec_number.push_str("0.");
             }
             let number = toc.count_entries_with_level(level);
-            sec_number.push_str(format_strbuf!("{}", number + 1).as_slice())
+            sec_number.push_str(format!("{}", number + 1).as_slice())
         }
 
         self.chain.push(TocEntry {
index ae708a7198716eb64151d675e1bcaa6c840c60a4..fe53439703adb39116a8c1bc876197ad621707a3 100644 (file)
@@ -248,7 +248,7 @@ fn acquire_input(input: &str,
     match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
         Some("rust") => Ok(rust_input(input, matches)),
         Some("json") => json_input(input),
-        Some(s) => Err(format_strbuf!("unknown input format: {}", s)),
+        Some(s) => Err(format!("unknown input format: {}", s)),
         None => {
             if input.ends_with(".json") {
                 json_input(input)
@@ -356,7 +356,7 @@ fn json_input(input: &str) -> Result<Output, String> {
     let mut input = match File::open(&Path::new(input)) {
         Ok(f) => f,
         Err(e) => {
-            return Err(format_strbuf!("couldn't open {}: {}", input, e))
+            return Err(format!("couldn't open {}: {}", input, e))
         }
     };
     match json::from_reader(&mut input) {
@@ -367,7 +367,7 @@ fn json_input(input: &str) -> Result<Output, String> {
             match obj.pop(&"schema".to_string()) {
                 Some(json::String(version)) => {
                     if version.as_slice() != SCHEMA_VERSION {
-                        return Err(format_strbuf!(
+                        return Err(format!(
                                 "sorry, but I only understand version {}",
                                 SCHEMA_VERSION))
                     }
index a7abbe0360f94d09e78741a8a3daf506bdcc0f50..e5fc8f1f1a178fffa5ad2aa9f1abef06bd0f862b 100644 (file)
@@ -260,9 +260,9 @@ pub fn new(cratename: String, libs: HashSet<Path>,
     pub fn add_test(&mut self, test: String, should_fail: bool, no_run: bool, should_ignore: bool) {
         let name = if self.use_headers {
             let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
-            format_strbuf!("{}_{}", s, self.cnt)
+            format!("{}_{}", s, self.cnt)
         } else {
-            format_strbuf!("{}_{}", self.names.connect("::"), self.cnt)
+            format!("{}_{}", self.names.connect("::"), self.cnt)
         };
         self.cnt += 1;
         let libs = self.libs.clone();
index 12636a3c490ad0ca64daafe083f8ff9dea0eb5d7..7143f420b08a1b8c5bce0d685f0b1598da356f1c 100644 (file)
@@ -377,7 +377,7 @@ fn base_write(&mut self, buf: &[u8], offset: i64) -> Result<(), IoError> {
         let r = FsRequest::write(&self.loop_, self.fd, buf, offset);
         r.map_err(uv_error_to_io_error)
     }
-    fn seek_common(&mut self, pos: i64, whence: c_int) ->
+    fn seek_common(&self, pos: i64, whence: c_int) ->
         Result<u64, IoError>{
         unsafe {
             match libc::lseek(self.fd, pos as libc::off_t, whence) {
@@ -446,10 +446,8 @@ fn seek(&mut self, pos: i64, whence: io::SeekStyle) -> Result<u64, IoError> {
     }
     fn tell(&self) -> Result<u64, IoError> {
         use libc::SEEK_CUR;
-        // this is temporary
-        // FIXME #13933: Remove/justify all `&T` to `&mut T` transmutes
-        let self_ = unsafe { mem::transmute::<&_, &mut FileWatcher>(self) };
-        self_.seek_common(0, SEEK_CUR)
+
+        self.seek_common(0, SEEK_CUR)
     }
     fn fsync(&mut self) -> Result<(), IoError> {
         let _m = self.fire_homing_missile();
index a119d4832db45d4de9c47ac9507ff3b24ded05e9..51dcc6d3faf55a812f371389648221f7954a610e 100644 (file)
@@ -377,13 +377,13 @@ fn test_ne() {
 
 #[test]
 fn test_show() {
-    assert_eq!(format_strbuf!("{}", parse("1.2.3").unwrap()),
+    assert_eq!(format!("{}", parse("1.2.3").unwrap()),
                "1.2.3".to_string());
-    assert_eq!(format_strbuf!("{}", parse("1.2.3-alpha1").unwrap()),
+    assert_eq!(format!("{}", parse("1.2.3-alpha1").unwrap()),
                "1.2.3-alpha1".to_string());
-    assert_eq!(format_strbuf!("{}", parse("1.2.3+build.42").unwrap()),
+    assert_eq!(format!("{}", parse("1.2.3+build.42").unwrap()),
                "1.2.3+build.42".to_string());
-    assert_eq!(format_strbuf!("{}", parse("1.2.3-alpha1+42").unwrap()),
+    assert_eq!(format!("{}", parse("1.2.3-alpha1+42").unwrap()),
                "1.2.3-alpha1+42".to_string());
 }
 
index 5d2f229beb675e3a7a99a983f17d892207c25bf4..5a8759540c8b5655fbc86dda7034868905b36149 100644 (file)
@@ -261,7 +261,6 @@ fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
 #[cfg(test)]
 mod tests {
     extern crate test;
-    extern crate rand;
     use self::test::Bencher;
     use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE};
 
@@ -335,7 +334,7 @@ fn test_from_base64_invalid_padding() {
 
     #[test]
     fn test_base64_random() {
-        use self::rand::{task_rng, random, Rng};
+        use std::rand::{task_rng, random, Rng};
 
         for _ in range(0, 1000) {
             let times = task_rng().gen_range(1u, 100);
index a127c11f50932e22475d7b5e79cb7ee857007637..67045476f6d8756617a8370da9a173954609875f 100644 (file)
@@ -313,10 +313,8 @@ fn _check_label(&mut self, lbl: &str) -> DecodeResult<()> {
                     self.pos = r_doc.end;
                     let str = r_doc.as_str_slice();
                     if lbl != str {
-                        return Err(Expected(format_strbuf!("Expected label \
-                                                            {} but found {}",
-                                                           lbl,
-                                                           str)));
+                        return Err(Expected(format!("Expected label {} but \
+                                                     found {}", lbl, str)));
                     }
                 }
             }
@@ -326,8 +324,8 @@ fn _check_label(&mut self, lbl: &str) -> DecodeResult<()> {
         fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
             debug!(". next_doc(exp_tag={})", exp_tag);
             if self.pos >= self.parent.end {
-                return Err(Expected(format_strbuf!("no more documents in \
-                                                    current node!")));
+                return Err(Expected(format!("no more documents in \
+                                             current node!")));
             }
             let TaggedDoc { tag: r_tag, doc: r_doc } =
                 try!(doc_at(self.parent.data, self.pos));
@@ -339,18 +337,13 @@ fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
                    r_doc.start,
                    r_doc.end);
             if r_tag != (exp_tag as uint) {
-                return Err(Expected(format_strbuf!("expected EBML doc with \
-                                                    tag {} but found tag \
-                                                    {}",
-                                                   exp_tag,
-                                                   r_tag)));
+                return Err(Expected(format!("expected EBML doc with tag {} but \
+                                             found tag {}", exp_tag, r_tag)));
             }
             if r_doc.end > self.parent.end {
-                return Err(Expected(format_strbuf!("invalid EBML, child \
-                                                    extends to {:#x}, parent \
-                                                    to {:#x}",
-                                                   r_doc.end,
-                                                   self.parent.end)));
+                return Err(Expected(format!("invalid EBML, child extends to \
+                                             {:#x}, parent to {:#x}",
+                                            r_doc.end, self.parent.end)));
             }
             self.pos = r_doc.end;
             Ok(r_doc)
@@ -582,8 +575,7 @@ fn read_option<T>(&mut self,
                         0 => f(this, false),
                         1 => f(this, true),
                         _ => {
-                            Err(Expected(format_strbuf!("Expected None or \
-                                                         Some")))
+                            Err(Expected(format!("Expected None or Some")))
                         }
                     }
                 })
@@ -664,7 +656,7 @@ fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult
             _ => Err(io::IoError {
                 kind: io::OtherIoError,
                 desc: "int too big",
-                detail: Some(format_strbuf!("{}", n))
+                detail: Some(format!("{}", n))
             })
         }
     }
@@ -677,7 +669,7 @@ fn write_vuint<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
         Err(io::IoError {
             kind: io::OtherIoError,
             desc: "int too big",
-            detail: Some(format_strbuf!("{}", n))
+            detail: Some(format!("{}", n))
         })
     }
 
index 373bff8b0cc6136a960c5a86b659f43081c0bdd2..8ae3336c342b4aed27428b04efcf1a5355b45f9d 100644 (file)
@@ -174,8 +174,7 @@ pub fn test_from_hex_ignores_whitespace() {
     #[test]
     pub fn test_to_hex_all_bytes() {
         for i in range(0, 256) {
-            assert_eq!([i as u8].to_hex(),
-                       format_strbuf!("{:02x}", i as uint));
+            assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint));
         }
     }
 
index 08ac66959bc3c06e8c7785ff4526debe6344d3cf..09ba46bf0c746b90cf12517d2342bb9edc7198cd 100644 (file)
@@ -1819,7 +1819,7 @@ macro_rules! expect(
         match $e {
             Null => Ok(()),
             other => Err(ExpectedError("Null".to_string(),
-                                       format_strbuf!("{}", other)))
+                                       format!("{}", other)))
         }
     });
     ($e:expr, $t:ident) => ({
@@ -1827,7 +1827,7 @@ macro_rules! expect(
             $t(v) => Ok(v),
             other => {
                 Err(ExpectedError(stringify!($t).to_string(),
-                                  format_strbuf!("{}", other)))
+                                  format!("{}", other)))
             }
         }
     })
@@ -1869,7 +1869,7 @@ fn read_f64(&mut self) -> DecodeResult<f64> {
             },
             value => {
                 Err(ExpectedError("Number".to_string(),
-                                  format_strbuf!("{}", value)))
+                                  format!("{}", value)))
             }
         }
     }
@@ -1887,7 +1887,7 @@ fn read_char(&mut self) -> DecodeResult<char> {
             }
         }
         Err(ExpectedError("single character string".to_string(),
-                          format_strbuf!("{}", s)))
+                          format!("{}", s)))
     }
 
     fn read_str(&mut self) -> DecodeResult<String> {
@@ -1914,7 +1914,7 @@ fn read_enum_variant<T>(&mut self,
                     Some(String(s)) => s,
                     Some(val) => {
                         return Err(ExpectedError("String".to_string(),
-                                                 format_strbuf!("{}", val)))
+                                                 format!("{}", val)))
                     }
                     None => {
                         return Err(MissingFieldError("variant".to_string()))
@@ -1928,7 +1928,7 @@ fn read_enum_variant<T>(&mut self,
                     },
                     Some(val) => {
                         return Err(ExpectedError("List".to_string(),
-                                                 format_strbuf!("{}", val)))
+                                                 format!("{}", val)))
                     }
                     None => {
                         return Err(MissingFieldError("fields".to_string()))
@@ -1938,7 +1938,7 @@ fn read_enum_variant<T>(&mut self,
             }
             json => {
                 return Err(ExpectedError("String or Object".to_string(),
-                                         format_strbuf!("{}", json)))
+                                         format!("{}", json)))
             }
         };
         let idx = match names.iter()
index 55bbf4ddf75ab90774f59068a3c3490b921361cd..75b31f9c354307751523a798178fd9ef20225350 100644 (file)
@@ -783,6 +783,6 @@ fn test_to_str() {
     #[test]
     fn test_show() {
         let c = Ascii { chr: 't' as u8 };
-        assert_eq!(format_strbuf!("{}", c), "t".to_string());
+        assert_eq!(format!("{}", c), "t".to_string());
     }
 }
index d53a0f93c9b7cdfacf8f795df251b6ca285feb58..9bca2f4248c7589270c8c61244f5beab7d6c08b9 100644 (file)
@@ -562,13 +562,6 @@ pub fn format(args: &Arguments) -> string::String{
     str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
 }
 
-/// Temporary transition utility
-pub fn format_strbuf(args: &Arguments) -> string::String {
-    let mut output = io::MemWriter::new();
-    let _ = write!(&mut output, "{}", args);
-    str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
-}
-
 #[cfg(stage0)]
 impl<T> Poly for T {
     fn fmt(&self, f: &mut Formatter) -> Result {
index d3e250be9a3234e28014ec6e06f791e2891fc998..a77c7107f282f39785dbf5b795f58eed6f669eaf 100644 (file)
@@ -745,8 +745,7 @@ fn drop(&mut self) {
     pub fn tmpdir() -> TempDir {
         use os;
         use rand;
-        let ret = os::tmpdir().join(
-            format_strbuf!("rust-{}", rand::random::<u32>()));
+        let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>()));
         check!(io::fs::mkdir(&ret, io::UserRWX));
         TempDir(ret)
     }
@@ -953,7 +952,7 @@ pub fn tmpdir() -> TempDir {
         check!(mkdir(dir, io::UserRWX));
         let prefix = "foo";
         for n in range(0,3) {
-            let f = dir.join(format_strbuf!("{}.txt", n));
+            let f = dir.join(format!("{}.txt", n));
             let mut w = check!(File::create(&f));
             let msg_str = format!("{}{}", prefix, n.to_str());
             let msg = msg_str.as_slice().as_bytes();
@@ -1040,7 +1039,7 @@ pub fn tmpdir() -> TempDir {
         let tmpdir = tmpdir();
 
         let mut dirpath = tmpdir.path().clone();
-        dirpath.push(format_strbuf!("test-가一ー你好"));
+        dirpath.push(format!("test-가一ー你好"));
         check!(mkdir(&dirpath, io::UserRWX));
         assert!(dirpath.is_dir());
 
@@ -1057,7 +1056,7 @@ pub fn tmpdir() -> TempDir {
 
         let tmpdir = tmpdir();
         let unicode = tmpdir.path();
-        let unicode = unicode.join(format_strbuf!("test-각丁ー再见"));
+        let unicode = unicode.join(format!("test-각丁ー再见"));
         check!(mkdir(&unicode, io::UserRWX));
         assert!(unicode.exists());
         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
index 806df838c919e36d491b15913543d2539144382e..5ca7e417af695cf21331ec6509e770f863fe621f 100644 (file)
@@ -43,10 +43,10 @@ pub fn new_in(tmpdir: &Path, suffix: &str) -> Option<TempDir> {
 
         for _ in range(0u, 1000) {
             let filename =
-                format_strbuf!("rs-{}-{}-{}",
-                               unsafe { libc::getpid() },
-                               unsafe { CNT.fetch_add(1, atomics::SeqCst) },
-                               suffix);
+                format!("rs-{}-{}-{}",
+                        unsafe { libc::getpid() },
+                        unsafe { CNT.fetch_add(1, atomics::SeqCst) },
+                        suffix);
             let p = tmpdir.join(filename);
             match fs::mkdir(&p, io::UserRWX) {
                 Err(..) => {}
index bc52bc9946c087c15fafe4ed8fb6538dcad7c2f4..4d3dde46b57b57516f71fbc62fe37c8d0e291f76 100644 (file)
@@ -67,14 +67,14 @@ pub fn next_test_unix() -> Path {
     // base port and pid are an attempt to be unique between multiple
     // test-runners of different configurations running on one
     // buildbot, the count is to be unique within this executable.
-    let string = format_strbuf!("rust-test-unix-path-{}-{}-{}",
-                                base_port(),
-                                unsafe {libc::getpid()},
-                                unsafe {COUNT.fetch_add(1, Relaxed)});
+    let string = format!("rust-test-unix-path-{}-{}-{}",
+                         base_port(),
+                         unsafe {libc::getpid()},
+                         unsafe {COUNT.fetch_add(1, Relaxed)});
     if cfg!(unix) {
         os::tmpdir().join(string)
     } else {
-        Path::new(format_strbuf!("{}{}", r"\\.\pipe\", string))
+        Path::new(format!("{}{}", r"\\.\pipe\", string))
     }
 }
 
index c1bc68b3e1293cbd3776c2692cd042c93fa7225b..b63ccbef55faadbdf2f12fc8f9424576ed37173f 100644 (file)
 #[cfg(test)] extern crate debug;
 #[cfg(test)] #[phase(syntax, link)] extern crate log;
 
-// Make and rand accessible for benchmarking/testcases
-#[cfg(test)] extern crate rand;
-
 extern crate alloc;
 extern crate core;
 extern crate libc;
+extern crate core_rand = "rand";
 
 // Make std testable by not duplicating lang items. See #2912
 #[cfg(test)] extern crate realstd = "std";
@@ -208,6 +206,7 @@ fn start(argc: int, argv: **u8) -> int {
 pub mod vec;
 pub mod str;
 pub mod string;
+pub mod rand;
 
 pub mod ascii;
 
index 28b4552fd4c011ba5ae575a9bdde62659fdaf41c..0b9fc250636f43b49f1ed16273f761cc769ea539 100644 (file)
@@ -229,14 +229,6 @@ macro_rules! format(
     )
 )
 
-/// Temporary transitionary thing.
-#[macro_export]
-macro_rules! format_strbuf(
-    ($($arg:tt)*) => (
-        format_args!(::std::fmt::format_strbuf, $($arg)*)
-    )
-)
-
 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
 /// See `std::fmt` for more information.
 ///
index 7ed00e3dd9d6fa8e6720a2ef07801fdebf0f2ace..889a42ec00eaa457e2ab64bb394e043ece938fe8 100644 (file)
@@ -78,7 +78,7 @@ impl ToStrRadix for $T {
     /// Convert to a string in a given base.
     #[inline]
     fn to_str_radix(&self, radix: uint) -> String {
-        format_strbuf!("{}", ::fmt::radix(*self, radix as u8))
+        format!("{}", ::fmt::radix(*self, radix as u8))
     }
 }
 
index 1efe83217f48d3b4042f98aa364f47e5be733057..20f5927c9bd503a3abd759a97b43e3e7d0539d35 100644 (file)
@@ -819,84 +819,84 @@ mod bench {
 
     mod uint {
         use super::test::Bencher;
-        use rand::{XorShiftRng, Rng};
+        use rand::{weak_rng, Rng};
         use num::ToStrRadix;
 
         #[bench]
         fn to_str_bin(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<uint>().to_str_radix(2); })
         }
 
         #[bench]
         fn to_str_oct(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<uint>().to_str_radix(8); })
         }
 
         #[bench]
         fn to_str_dec(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<uint>().to_str_radix(10); })
         }
 
         #[bench]
         fn to_str_hex(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<uint>().to_str_radix(16); })
         }
 
         #[bench]
         fn to_str_base_36(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<uint>().to_str_radix(36); })
         }
     }
 
     mod int {
         use super::test::Bencher;
-        use rand::{XorShiftRng, Rng};
+        use rand::{weak_rng, Rng};
         use num::ToStrRadix;
 
         #[bench]
         fn to_str_bin(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<int>().to_str_radix(2); })
         }
 
         #[bench]
         fn to_str_oct(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<int>().to_str_radix(8); })
         }
 
         #[bench]
         fn to_str_dec(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<int>().to_str_radix(10); })
         }
 
         #[bench]
         fn to_str_hex(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<int>().to_str_radix(16); })
         }
 
         #[bench]
         fn to_str_base_36(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { rng.gen::<int>().to_str_radix(36); })
         }
     }
 
     mod f64 {
         use super::test::Bencher;
-        use rand::{XorShiftRng, Rng};
+        use rand::{weak_rng, Rng};
         use f64;
 
         #[bench]
         fn float_to_str(b: &mut Bencher) {
-            let mut rng = XorShiftRng::new().unwrap();
+            let mut rng = weak_rng();
             b.iter(|| { f64::to_str(rng.gen()); })
         }
     }
index 43048453717464959516ecece10fb7942a2e4544..769588d0bcb06aa9cb32f5bf2a962c6b202fff97 100644 (file)
@@ -79,7 +79,7 @@ impl ToStrRadix for $T {
     /// Convert to a string in a given base.
     #[inline]
     fn to_str_radix(&self, radix: uint) -> String {
-        format_strbuf!("{}", ::fmt::radix(*self, radix as u8))
+        format!("{}", ::fmt::radix(*self, radix as u8))
     }
 }
 
index 7d3758d621d32249627a723cab852ec5dd4159d8..f6b9a7b24bc9338f7328bad8a0b5891fcdc0427e 100644 (file)
@@ -437,7 +437,7 @@ pub fn pipe() -> Pipe {
 
 /// Returns the proper dll filename for the given basename of a file.
 pub fn dll_filename(base: &str) -> String {
-    format_strbuf!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
+    format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
 }
 
 /// Optionally returns the filesystem path of the current executable which is
@@ -1513,7 +1513,8 @@ pub fn last_os_error() {
 
     fn make_rand_name() -> String {
         let mut rng = rand::task_rng();
-        let n = format_strbuf!("TEST{}", rng.gen_ascii_str(10u).as_slice());
+        let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
+                                     .collect::<String>());
         assert!(getenv(n.as_slice()).is_none());
         n
     }
index 1fc2fa1d221dc6c3d5184fcf5b588d4f28efbb6d..88c3e9def8cf41d8e661ea9f3367869f54fbc1f6 100644 (file)
@@ -900,7 +900,7 @@ pub fn make_non_verbatim(path: &Path) -> Option<Path> {
         }
         Some(VerbatimUNCPrefix(_,_)) => {
             // \\?\UNC\server\share
-            Path::new(format_strbuf!(r"\\{}", repr.slice_from(7)))
+            Path::new(format!(r"\\{}", repr.slice_from(7)))
         }
     };
     if new_path.prefix.is_none() {
diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs
new file mode 100644 (file)
index 0000000..61a2ffd
--- /dev/null
@@ -0,0 +1,525 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+/*!
+
+Utilities for random number generation
+
+The key functions are `random()` and `Rng::gen()`. These are polymorphic
+and so can be used to generate any type that implements `Rand`. Type inference
+means that often a simple call to `rand::random()` or `rng.gen()` will
+suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
+
+See the `distributions` submodule for sampling random numbers from
+distributions like normal and exponential.
+
+# Task-local RNG
+
+There is built-in support for a RNG associated with each task stored
+in task-local storage. This RNG can be accessed via `task_rng`, or
+used implicitly via `random`. This RNG is normally randomly seeded
+from an operating-system source of randomness, e.g. `/dev/urandom` on
+Unix systems, and will automatically reseed itself from this source
+after generating 32 KiB of random data.
+
+# Cryptographic security
+
+An application that requires an entropy source for cryptographic purposes
+must use `OsRng`, which reads randomness from the source that the operating
+system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
+The other random number generators provided by this module are not suitable
+for such purposes.
+
+*Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
+This module uses `/dev/urandom` for the following reasons:
+
+-   On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
+    This does not mean that `/dev/random` provides better output than
+    `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
+    number generator (CSPRNG) based on entropy pool for random number generation,
+    so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
+    However, this means that `/dev/urandom` can yield somewhat predictable randomness
+    if the entropy pool is very small, such as immediately after first booting.
+    If an application likely to be run soon after first booting, or on a system with very
+    few entropy sources, one should consider using `/dev/random` via `ReaderRng`.
+-   On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
+    between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
+    and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
+
+# Examples
+
+```rust
+use std::rand;
+use std::rand::Rng;
+
+let mut rng = rand::task_rng();
+if rng.gen() { // bool
+    println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
+}
+```
+
+```rust
+use std::rand;
+
+let tuple = rand::random::<(f64, char)>();
+println!("{}", tuple)
+```
+*/
+
+use cell::RefCell;
+use clone::Clone;
+use io::IoResult;
+use iter::Iterator;
+use mem;
+use option::{Some, None};
+use rc::Rc;
+use result::{Ok, Err};
+use vec::Vec;
+
+#[cfg(not(target_word_size="64"))]
+use IsaacWordRng = core_rand::IsaacRng;
+#[cfg(target_word_size="64")]
+use IsaacWordRng = core_rand::Isaac64Rng;
+
+pub use core_rand::{Rand, Rng, SeedableRng, Open01, Closed01};
+pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
+pub use core_rand::{distributions, reseeding};
+pub use rand::os::OsRng;
+
+pub mod os;
+pub mod reader;
+
+/// The standard RNG. This is designed to be efficient on the current
+/// platform.
+pub struct StdRng { rng: IsaacWordRng }
+
+impl StdRng {
+    /// Create a randomly seeded instance of `StdRng`.
+    ///
+    /// This is a very expensive operation as it has to read
+    /// randomness from the operating system and use this in an
+    /// expensive seeding operation. If one is only generating a small
+    /// number of random numbers, or doesn't need the utmost speed for
+    /// generating each number, `task_rng` and/or `random` may be more
+    /// appropriate.
+    ///
+    /// Reading the randomness from the OS may fail, and any error is
+    /// propagated via the `IoResult` return value.
+    pub fn new() -> IoResult<StdRng> {
+        OsRng::new().map(|mut r| StdRng { rng: r.gen() })
+    }
+}
+
+impl Rng for StdRng {
+    #[inline]
+    fn next_u32(&mut self) -> u32 {
+        self.rng.next_u32()
+    }
+
+    #[inline]
+    fn next_u64(&mut self) -> u64 {
+        self.rng.next_u64()
+    }
+}
+
+impl<'a> SeedableRng<&'a [uint]> for StdRng {
+    fn reseed(&mut self, seed: &'a [uint]) {
+        // the internal RNG can just be seeded from the above
+        // randomness.
+        self.rng.reseed(unsafe {mem::transmute(seed)})
+    }
+
+    fn from_seed(seed: &'a [uint]) -> StdRng {
+        StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
+    }
+}
+
+/// Create a weak random number generator with a default algorithm and seed.
+///
+/// It returns the fastest `Rng` algorithm currently available in Rust without
+/// consideration for cryptography or security. If you require a specifically
+/// seeded `Rng` for consistency over time you should pick one algorithm and
+/// create the `Rng` yourself.
+///
+/// This will read randomness from the operating system to seed the
+/// generator.
+pub fn weak_rng() -> XorShiftRng {
+    match OsRng::new() {
+        Ok(mut r) => r.gen(),
+        Err(e) => fail!("weak_rng: failed to create seeded RNG: {}", e)
+    }
+}
+
+/// Controls how the task-local RNG is reseeded.
+struct TaskRngReseeder;
+
+impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
+    fn reseed(&mut self, rng: &mut StdRng) {
+        *rng = match StdRng::new() {
+            Ok(r) => r,
+            Err(e) => fail!("could not reseed task_rng: {}", e)
+        }
+    }
+}
+static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
+type TaskRngInner = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
+
+/// The task-local RNG.
+pub struct TaskRng {
+    rng: Rc<RefCell<TaskRngInner>>,
+}
+
+/// Retrieve the lazily-initialized task-local random number
+/// generator, seeded by the system. Intended to be used in method
+/// chaining style, e.g. `task_rng().gen::<int>()`.
+///
+/// The RNG provided will reseed itself from the operating system
+/// after generating a certain amount of randomness.
+///
+/// The internal RNG used is platform and architecture dependent, even
+/// if the operating system random number generator is rigged to give
+/// the same sequence always. If absolute consistency is required,
+/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
+pub fn task_rng() -> TaskRng {
+    // used to make space in TLS for a random number generator
+    local_data_key!(TASK_RNG_KEY: Rc<RefCell<TaskRngInner>>)
+
+    match TASK_RNG_KEY.get() {
+        None => {
+            let r = match StdRng::new() {
+                Ok(r) => r,
+                Err(e) => fail!("could not initialize task_rng: {}", e)
+            };
+            let rng = reseeding::ReseedingRng::new(r,
+                                                   TASK_RNG_RESEED_THRESHOLD,
+                                                   TaskRngReseeder);
+            let rng = Rc::new(RefCell::new(rng));
+            TASK_RNG_KEY.replace(Some(rng.clone()));
+
+            TaskRng { rng: rng }
+        }
+        Some(rng) => TaskRng { rng: rng.clone() }
+    }
+}
+
+impl Rng for TaskRng {
+    fn next_u32(&mut self) -> u32 {
+        self.rng.borrow_mut().next_u32()
+    }
+
+    fn next_u64(&mut self) -> u64 {
+        self.rng.borrow_mut().next_u64()
+    }
+
+    #[inline]
+    fn fill_bytes(&mut self, bytes: &mut [u8]) {
+        self.rng.borrow_mut().fill_bytes(bytes)
+    }
+}
+
+/// Generate a random value using the task-local random number
+/// generator.
+///
+/// # Example
+///
+/// ```rust
+/// use std::rand::random;
+///
+/// if random() {
+///     let x = random();
+///     println!("{}", 2u * x);
+/// } else {
+///     println!("{}", random::<f64>());
+/// }
+/// ```
+#[inline]
+pub fn random<T: Rand>() -> T {
+    task_rng().gen()
+}
+
+/// Randomly sample up to `n` elements from an iterator.
+///
+/// # Example
+///
+/// ```rust
+/// use std::rand::{task_rng, sample};
+///
+/// let mut rng = task_rng();
+/// let sample = sample(&mut rng, range(1, 100), 5);
+/// println!("{}", sample);
+/// ```
+pub fn sample<T, I: Iterator<T>, R: Rng>(rng: &mut R,
+                                         mut iter: I,
+                                         amt: uint) -> Vec<T> {
+    let mut reservoir: Vec<T> = iter.by_ref().take(amt).collect();
+    for (i, elem) in iter.enumerate() {
+        let k = rng.gen_range(0, i + 1 + amt);
+        if k < amt {
+            *reservoir.get_mut(k) = elem;
+        }
+    }
+    return reservoir;
+}
+
+#[cfg(test)]
+mod test {
+    use prelude::*;
+    use super::{Rng, task_rng, random, SeedableRng, StdRng, sample};
+    use iter::order;
+
+    struct ConstRng { i: u64 }
+    impl Rng for ConstRng {
+        fn next_u32(&mut self) -> u32 { self.i as u32 }
+        fn next_u64(&mut self) -> u64 { self.i }
+
+        // no fill_bytes on purpose
+    }
+
+    #[test]
+    fn test_fill_bytes_default() {
+        let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 };
+
+        // check every remainder mod 8, both in small and big vectors.
+        let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
+                       80, 81, 82, 83, 84, 85, 86, 87];
+        for &n in lengths.iter() {
+            let mut v = Vec::from_elem(n, 0u8);
+            r.fill_bytes(v.as_mut_slice());
+
+            // use this to get nicer error messages.
+            for (i, &byte) in v.iter().enumerate() {
+                if byte == 0 {
+                    fail!("byte {} of {} is zero", i, n)
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn test_gen_range() {
+        let mut r = task_rng();
+        for _ in range(0, 1000) {
+            let a = r.gen_range(-3i, 42);
+            assert!(a >= -3 && a < 42);
+            assert_eq!(r.gen_range(0, 1), 0);
+            assert_eq!(r.gen_range(-12, -11), -12);
+        }
+
+        for _ in range(0, 1000) {
+            let a = r.gen_range(10, 42);
+            assert!(a >= 10 && a < 42);
+            assert_eq!(r.gen_range(0, 1), 0);
+            assert_eq!(r.gen_range(3_000_000u, 3_000_001), 3_000_000);
+        }
+
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_gen_range_fail_int() {
+        let mut r = task_rng();
+        r.gen_range(5i, -2);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_gen_range_fail_uint() {
+        let mut r = task_rng();
+        r.gen_range(5u, 2u);
+    }
+
+    #[test]
+    fn test_gen_f64() {
+        let mut r = task_rng();
+        let a = r.gen::<f64>();
+        let b = r.gen::<f64>();
+        debug!("{}", (a, b));
+    }
+
+    #[test]
+    fn test_gen_weighted_bool() {
+        let mut r = task_rng();
+        assert_eq!(r.gen_weighted_bool(0u), true);
+        assert_eq!(r.gen_weighted_bool(1u), true);
+    }
+
+    #[test]
+    fn test_gen_ascii_str() {
+        let mut r = task_rng();
+        assert_eq!(r.gen_ascii_chars().take(0).len(), 0u);
+        assert_eq!(r.gen_ascii_chars().take(10).len(), 10u);
+        assert_eq!(r.gen_ascii_chars().take(16).len(), 16u);
+    }
+
+    #[test]
+    fn test_gen_vec() {
+        let mut r = task_rng();
+        assert_eq!(r.gen_iter::<u8>().take(0).len(), 0u);
+        assert_eq!(r.gen_iter::<u8>().take(10).len(), 10u);
+        assert_eq!(r.gen_iter::<f64>().take(16).len(), 16u);
+    }
+
+    #[test]
+    fn test_choose() {
+        let mut r = task_rng();
+        assert_eq!(r.choose([1, 1, 1]).map(|&x|x), Some(1));
+
+        let v: &[int] = &[];
+        assert_eq!(r.choose(v), None);
+    }
+
+    #[test]
+    fn test_shuffle() {
+        let mut r = task_rng();
+        let empty: &mut [int] = &mut [];
+        r.shuffle(empty);
+        let mut one = [1];
+        r.shuffle(one);
+        assert_eq!(one.as_slice(), &[1]);
+
+        let mut two = [1, 2];
+        r.shuffle(two);
+        assert!(two == [1, 2] || two == [2, 1]);
+
+        let mut x = [1, 1, 1];
+        r.shuffle(x);
+        assert_eq!(x.as_slice(), &[1, 1, 1]);
+    }
+
+    #[test]
+    fn test_task_rng() {
+        let mut r = task_rng();
+        r.gen::<int>();
+        let mut v = [1, 1, 1];
+        r.shuffle(v);
+        assert_eq!(v.as_slice(), &[1, 1, 1]);
+        assert_eq!(r.gen_range(0u, 1u), 0u);
+    }
+
+    #[test]
+    fn test_random() {
+        // not sure how to test this aside from just getting some values
+        let _n : uint = random();
+        let _f : f32 = random();
+        let _o : Option<Option<i8>> = random();
+        let _many : ((),
+                     (uint,
+                      int,
+                      Option<(u32, (bool,))>),
+                     (u8, i8, u16, i16, u32, i32, u64, i64),
+                     (f32, (f64, (f64,)))) = random();
+    }
+
+    #[test]
+    fn test_sample() {
+        let min_val = 1;
+        let max_val = 100;
+
+        let mut r = task_rng();
+        let vals = range(min_val, max_val).collect::<Vec<int>>();
+        let small_sample = sample(&mut r, vals.iter(), 5);
+        let large_sample = sample(&mut r, vals.iter(), vals.len() + 5);
+
+        assert_eq!(small_sample.len(), 5);
+        assert_eq!(large_sample.len(), vals.len());
+
+        assert!(small_sample.iter().all(|e| {
+            **e >= min_val && **e <= max_val
+        }));
+    }
+
+    #[test]
+    fn test_std_rng_seeded() {
+        let s = task_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());
+        assert!(order::equals(ra.gen_ascii_chars().take(100),
+                              rb.gen_ascii_chars().take(100)));
+    }
+
+    #[test]
+    fn test_std_rng_reseed() {
+        let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
+        let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
+        let string1 = r.gen_ascii_chars().take(100).collect::<String>();
+
+        r.reseed(s.as_slice());
+
+        let string2 = r.gen_ascii_chars().take(100).collect::<String>();
+        assert_eq!(string1, string2);
+    }
+}
+
+#[cfg(test)]
+static RAND_BENCH_N: u64 = 100;
+
+#[cfg(test)]
+mod bench {
+    extern crate test;
+    use prelude::*;
+
+    use self::test::Bencher;
+    use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N};
+    use super::{OsRng, weak_rng};
+    use mem::size_of;
+
+    #[bench]
+    fn rand_xorshift(b: &mut Bencher) {
+        let mut rng: XorShiftRng = OsRng::new().unwrap().gen();
+        b.iter(|| {
+            for _ in range(0, RAND_BENCH_N) {
+                rng.gen::<uint>();
+            }
+        });
+        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+    }
+
+    #[bench]
+    fn rand_isaac(b: &mut Bencher) {
+        let mut rng: IsaacRng = OsRng::new().unwrap().gen();
+        b.iter(|| {
+            for _ in range(0, RAND_BENCH_N) {
+                rng.gen::<uint>();
+            }
+        });
+        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+    }
+
+    #[bench]
+    fn rand_isaac64(b: &mut Bencher) {
+        let mut rng: Isaac64Rng = OsRng::new().unwrap().gen();
+        b.iter(|| {
+            for _ in range(0, RAND_BENCH_N) {
+                rng.gen::<uint>();
+            }
+        });
+        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+    }
+
+    #[bench]
+    fn rand_std(b: &mut Bencher) {
+        let mut rng = StdRng::new().unwrap();
+        b.iter(|| {
+            for _ in range(0, RAND_BENCH_N) {
+                rng.gen::<uint>();
+            }
+        });
+        b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
+    }
+
+    #[bench]
+    fn rand_shuffle_100(b: &mut Bencher) {
+        let mut rng = weak_rng();
+        let x : &mut[uint] = [1,..100];
+        b.iter(|| {
+            rng.shuffle(x);
+        })
+    }
+}
diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs
new file mode 100644 (file)
index 0000000..3a6c012
--- /dev/null
@@ -0,0 +1,248 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+//! Interfaces to the operating system provided random number
+//! generators.
+
+pub use self::imp::OsRng;
+
+#[cfg(unix)]
+mod imp {
+    use io::{IoResult, File};
+    use path::Path;
+    use rand::Rng;
+    use rand::reader::ReaderRng;
+    use result::{Ok, Err};
+
+    /// A random number generator that retrieves randomness straight from
+    /// the operating system. Platform sources:
+    ///
+    /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
+    ///   `/dev/urandom`.
+    /// - Windows: calls `CryptGenRandom`, using the default cryptographic
+    ///   service provider with the `PROV_RSA_FULL` type.
+    ///
+    /// This does not block.
+    #[cfg(unix)]
+    pub struct OsRng {
+        inner: ReaderRng<File>
+    }
+
+    impl OsRng {
+        /// Create a new `OsRng`.
+        pub fn new() -> IoResult<OsRng> {
+            let reader = try!(File::open(&Path::new("/dev/urandom")));
+            let reader_rng = ReaderRng::new(reader);
+
+            Ok(OsRng { inner: reader_rng })
+        }
+    }
+
+    impl Rng for OsRng {
+        fn next_u32(&mut self) -> u32 {
+            self.inner.next_u32()
+        }
+        fn next_u64(&mut self) -> u64 {
+            self.inner.next_u64()
+        }
+        fn fill_bytes(&mut self, v: &mut [u8]) {
+            self.inner.fill_bytes(v)
+        }
+    }
+}
+
+#[cfg(windows)]
+mod imp {
+    extern crate libc;
+
+    use container::Container;
+    use io::{IoResult, IoError};
+    use mem;
+    use ops::Drop;
+    use os;
+    use rand::Rng;
+    use result::{Ok, Err};
+    use rt::stack;
+    use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
+    use slice::MutableVector;
+
+    type HCRYPTPROV = c_ulong;
+
+    /// A random number generator that retrieves randomness straight from
+    /// the operating system. Platform sources:
+    ///
+    /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
+    ///   `/dev/urandom`.
+    /// - Windows: calls `CryptGenRandom`, using the default cryptographic
+    ///   service provider with the `PROV_RSA_FULL` type.
+    ///
+    /// This does not block.
+    pub struct OsRng {
+        hcryptprov: HCRYPTPROV
+    }
+
+    static PROV_RSA_FULL: DWORD = 1;
+    static CRYPT_SILENT: DWORD = 64;
+    static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
+    static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
+
+    extern "system" {
+        fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
+                                pszContainer: LPCSTR,
+                                pszProvider: LPCSTR,
+                                dwProvType: DWORD,
+                                dwFlags: DWORD) -> BOOL;
+        fn CryptGenRandom(hProv: HCRYPTPROV,
+                          dwLen: DWORD,
+                          pbBuffer: *mut BYTE) -> BOOL;
+        fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
+    }
+
+    impl OsRng {
+        /// Create a new `OsRng`.
+        pub fn new() -> IoResult<OsRng> {
+            let mut hcp = 0;
+            let mut ret = unsafe {
+                CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
+                                     PROV_RSA_FULL,
+                                     CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
+            };
+
+            // FIXME #13259:
+            // It turns out that if we can't acquire a context with the
+            // NTE_BAD_SIGNATURE error code, the documentation states:
+            //
+            //     The provider DLL signature could not be verified. Either the
+            //     DLL or the digital signature has been tampered with.
+            //
+            // Sounds fishy, no? As it turns out, our signature can be bad
+            // because our Thread Information Block (TIB) isn't exactly what it
+            // expects. As to why, I have no idea. The only data we store in the
+            // TIB is the stack limit for each thread, but apparently that's
+            // enough to make the signature valid.
+            //
+            // Furthermore, this error only happens the *first* time we call
+            // CryptAcquireContext, so we don't have to worry about future
+            // calls.
+            //
+            // Anyway, the fix employed here is that if we see this error, we
+            // pray that we're not close to the end of the stack, temporarily
+            // set the stack limit to 0 (what the TIB originally was), acquire a
+            // context, and then reset the stack limit.
+            //
+            // Again, I'm not sure why this is the fix, nor why we're getting
+            // this error. All I can say is that this seems to allow libnative
+            // to progress where it otherwise would be hindered. Who knew?
+            if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
+                unsafe {
+                    let limit = stack::get_sp_limit();
+                    stack::record_sp_limit(0);
+                    ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
+                                               PROV_RSA_FULL,
+                                               CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
+                    stack::record_sp_limit(limit);
+                }
+            }
+
+            if ret == 0 {
+                Err(IoError::last_error())
+            } else {
+                Ok(OsRng { hcryptprov: hcp })
+            }
+        }
+    }
+
+    impl Rng for OsRng {
+        fn next_u32(&mut self) -> u32 {
+            let mut v = [0u8, .. 4];
+            self.fill_bytes(v);
+            unsafe { mem::transmute(v) }
+        }
+        fn next_u64(&mut self) -> u64 {
+            let mut v = [0u8, .. 8];
+            self.fill_bytes(v);
+            unsafe { mem::transmute(v) }
+        }
+        fn fill_bytes(&mut self, v: &mut [u8]) {
+            let ret = unsafe {
+                CryptGenRandom(self.hcryptprov, v.len() as DWORD,
+                               v.as_mut_ptr())
+            };
+            if ret == 0 {
+                fail!("couldn't generate random bytes: {}", os::last_os_error());
+            }
+        }
+    }
+
+    impl Drop for OsRng {
+        fn drop(&mut self) {
+            let ret = unsafe {
+                CryptReleaseContext(self.hcryptprov, 0)
+            };
+            if ret == 0 {
+                fail!("couldn't release context: {}", os::last_os_error());
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use prelude::*;
+
+    use super::OsRng;
+    use rand::Rng;
+    use task;
+
+    #[test]
+    fn test_os_rng() {
+        let mut r = OsRng::new().unwrap();
+
+        r.next_u32();
+        r.next_u64();
+
+        let mut v = [0u8, .. 1000];
+        r.fill_bytes(v);
+    }
+
+    #[test]
+    fn test_os_rng_tasks() {
+
+        let mut txs = vec!();
+        for _ in range(0, 20) {
+            let (tx, rx) = channel();
+            txs.push(tx);
+            task::spawn(proc() {
+                // wait until all the tasks are ready to go.
+                rx.recv();
+
+                // deschedule to attempt to interleave things as much
+                // as possible (XXX: is this a good test?)
+                let mut r = OsRng::new().unwrap();
+                task::deschedule();
+                let mut v = [0u8, .. 1000];
+
+                for _ in range(0, 100) {
+                    r.next_u32();
+                    task::deschedule();
+                    r.next_u64();
+                    task::deschedule();
+                    r.fill_bytes(v);
+                    task::deschedule();
+                }
+            })
+        }
+
+        // start all the tasks
+        for tx in txs.iter() {
+            tx.send(())
+        }
+    }
+}
diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs
new file mode 100644 (file)
index 0000000..1708840
--- /dev/null
@@ -0,0 +1,123 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+//! A wrapper around any Reader to treat it as an RNG.
+
+use container::Container;
+use io::Reader;
+use rand::Rng;
+use result::{Ok, Err};
+
+/// An RNG that reads random bytes straight from a `Reader`. This will
+/// work best with an infinite reader, but this is not required.
+///
+/// It will fail if it there is insufficient data to fulfill a request.
+///
+/// # Example
+///
+/// ```rust
+/// use std::rand::{reader, Rng};
+/// use std::io::MemReader;
+///
+/// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8)));
+/// println!("{:x}", rng.gen::<uint>());
+/// ```
+pub struct ReaderRng<R> {
+    reader: R
+}
+
+impl<R: Reader> ReaderRng<R> {
+    /// Create a new `ReaderRng` from a `Reader`.
+    pub fn new(r: R) -> ReaderRng<R> {
+        ReaderRng {
+            reader: r
+        }
+    }
+}
+
+impl<R: Reader> Rng for ReaderRng<R> {
+    fn next_u32(&mut self) -> u32 {
+        // This is designed for speed: reading a LE integer on a LE
+        // platform just involves blitting the bytes into the memory
+        // of the u32, similarly for BE on BE; avoiding byteswapping.
+        if cfg!(target_endian="little") {
+            self.reader.read_le_u32().unwrap()
+        } else {
+            self.reader.read_be_u32().unwrap()
+        }
+    }
+    fn next_u64(&mut self) -> u64 {
+        // see above for explanation.
+        if cfg!(target_endian="little") {
+            self.reader.read_le_u64().unwrap()
+        } else {
+            self.reader.read_be_u64().unwrap()
+        }
+    }
+    fn fill_bytes(&mut self, v: &mut [u8]) {
+        if v.len() == 0 { return }
+        match self.reader.read_at_least(v.len(), v) {
+            Ok(_) => {}
+            Err(e) => fail!("ReaderRng.fill_bytes error: {}", e)
+        }
+    }
+}
+
+#[cfg(test)]
+#[allow(deprecated_owned_vector)]
+mod test {
+    use prelude::*;
+
+    use super::ReaderRng;
+    use io::MemReader;
+    use mem;
+    use rand::Rng;
+
+    #[test]
+    fn test_reader_rng_u64() {
+        // transmute from the target to avoid endianness concerns.
+        let v = box [1u64, 2u64, 3u64];
+        let bytes: ~[u8] = unsafe {mem::transmute(v)};
+        let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
+
+        assert_eq!(rng.next_u64(), 1);
+        assert_eq!(rng.next_u64(), 2);
+        assert_eq!(rng.next_u64(), 3);
+    }
+    #[test]
+    fn test_reader_rng_u32() {
+        // transmute from the target to avoid endianness concerns.
+        let v = box [1u32, 2u32, 3u32];
+        let bytes: ~[u8] = unsafe {mem::transmute(v)};
+        let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
+
+        assert_eq!(rng.next_u32(), 1);
+        assert_eq!(rng.next_u32(), 2);
+        assert_eq!(rng.next_u32(), 3);
+    }
+    #[test]
+    fn test_reader_rng_fill_bytes() {
+        let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
+        let mut w = [0u8, .. 8];
+
+        let mut rng = ReaderRng::new(MemReader::new(Vec::from_slice(v)));
+        rng.fill_bytes(w);
+
+        assert!(v == w);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_reader_rng_insufficient_bytes() {
+        let mut rng = ReaderRng::new(MemReader::new(vec!()));
+        let mut v = [0u8, .. 3];
+        rng.fill_bytes(v);
+    }
+}
index be05bfceaac3e1da8024b8db55b0330d101712c3..f34dcaaa427ed0ecea61e84f2a03c44bc0bb5982 100644 (file)
@@ -354,7 +354,7 @@ pub fn begin_unwind_fmt(msg: &fmt::Arguments, file: &'static str,
     // required with the current scheme, and (b) we don't handle
     // failure + OOM properly anyway (see comment in begin_unwind
     // below).
-    begin_unwind_inner(box fmt::format_strbuf(msg), file, line)
+    begin_unwind_inner(box fmt::format(msg), file, line)
 }
 
 /// This is the entry point of unwinding for fail!() and assert!().
index e5c0cc3babd0377dadc41e5c32b3118b1e07ffcb..55bea068641e128266028140f62b08198f477bb5 100644 (file)
@@ -1303,7 +1303,8 @@ fn test_sort() {
         use realstd::clone::Clone;
         for len in range(4u, 25) {
             for _ in range(0, 100) {
-                let mut v = task_rng().gen_vec::<uint>(len);
+                let mut v = task_rng().gen_iter::<uint>().take(len)
+                                      .collect::<Vec<uint>>();
                 let mut v1 = v.clone();
 
                 v.as_mut_slice().sort();
@@ -2321,7 +2322,7 @@ fn random_removes(b: &mut Bencher) {
     fn sort_random_small(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<u64>(5);
+            let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
             v.as_mut_slice().sort();
         });
         b.bytes = 5 * mem::size_of::<u64>() as u64;
@@ -2331,7 +2332,7 @@ fn sort_random_small(b: &mut Bencher) {
     fn sort_random_medium(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<u64>(100);
+            let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
             v.as_mut_slice().sort();
         });
         b.bytes = 100 * mem::size_of::<u64>() as u64;
@@ -2341,7 +2342,7 @@ fn sort_random_medium(b: &mut Bencher) {
     fn sort_random_large(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<u64>(10000);
+            let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
             v.as_mut_slice().sort();
         });
         b.bytes = 10000 * mem::size_of::<u64>() as u64;
@@ -2362,7 +2363,8 @@ fn sort_sorted(b: &mut Bencher) {
     fn sort_big_random_small(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<BigSortable>(5);
+            let mut v = rng.gen_iter::<BigSortable>().take(5)
+                           .collect::<Vec<BigSortable>>();
             v.sort();
         });
         b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
@@ -2372,7 +2374,8 @@ fn sort_big_random_small(b: &mut Bencher) {
     fn sort_big_random_medium(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<BigSortable>(100);
+            let mut v = rng.gen_iter::<BigSortable>().take(100)
+                           .collect::<Vec<BigSortable>>();
             v.sort();
         });
         b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
@@ -2382,7 +2385,8 @@ fn sort_big_random_medium(b: &mut Bencher) {
     fn sort_big_random_large(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_vec::<BigSortable>(10000);
+            let mut v = rng.gen_iter::<BigSortable>().take(10000)
+                           .collect::<Vec<BigSortable>>();
             v.sort();
         });
         b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
index eb97f0f6a280808735aab22a1852a0b1566d70cc..6538809c8f12d27894fd5e22819de7742c342628 100644 (file)
@@ -79,7 +79,7 @@ fn main() {
 use option::{None, Option, Some};
 use result::Result;
 use slice::Vector;
-use slice::{ImmutableVector, MutableVector, CloneableVector};
+use slice::{ImmutableVector, MutableVector};
 use string::String;
 use vec::Vec;
 
@@ -503,7 +503,7 @@ macro_rules! error(() => ({
             res.push_bytes(v.slice(subseqidx, total))
         };
     }
-    Owned(res.into_owned())
+    Owned(res.into_string())
 }
 
 /*
@@ -608,7 +608,7 @@ fn as_slice<'b>(&'b self) -> &'b str {
 
 impl<'a> StrAllocating for MaybeOwned<'a> {
     #[inline]
-    fn into_owned(self) -> String {
+    fn into_string(self) -> String {
         match self {
             Slice(s) => s.to_string(),
             Owned(s) => s
@@ -723,7 +723,7 @@ fn test_from_buf_len() {
 /// Any string that can be represented as a slice
 pub trait StrAllocating: Str {
     /// Convert `self` into a `String`, not making a copy if possible.
-    fn into_owned(self) -> String;
+    fn into_string(self) -> String;
 
     /// Convert `self` into a `String`.
     #[inline]
@@ -731,10 +731,10 @@ fn to_string(&self) -> String {
         String::from_str(self.as_slice())
     }
 
-    /// Convert `self` into a `String`, not making a copy if possible.
-    #[inline]
-    fn into_string(self) -> String {
-        self.into_owned()
+    #[allow(missing_doc)]
+    #[deprecated = "replaced by .into_string()"]
+    fn into_owned(self) -> String {
+        self.into_string()
     }
 
     /// Escape each char in `s` with `char::escape_default`.
@@ -889,7 +889,7 @@ fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
 
 impl<'a> StrAllocating for &'a str {
     #[inline]
-    fn into_owned(self) -> String {
+    fn into_string(self) -> String {
         self.to_string()
     }
 }
@@ -1045,7 +1045,7 @@ fn t(a: &str, b: &str, start: uint) {
     #[test]
     fn test_concat() {
         fn t(v: &[String], s: &str) {
-            assert_eq!(v.concat(), s.to_str().into_owned());
+            assert_eq!(v.concat(), s.to_str().into_string());
         }
         t(["you".to_string(), "know".to_string(), "I'm".to_string(),
           "no".to_string(), "good".to_string()], "youknowI'mnogood");
@@ -1057,7 +1057,7 @@ fn t(v: &[String], s: &str) {
     #[test]
     fn test_connect() {
         fn t(v: &[String], sep: &str, s: &str) {
-            assert_eq!(v.connect(sep), s.to_str().into_owned());
+            assert_eq!(v.connect(sep), s.to_str().into_string());
         }
         t(["you".to_string(), "know".to_string(), "I'm".to_string(),
            "no".to_string(), "good".to_string()],
@@ -1070,7 +1070,7 @@ fn t(v: &[String], sep: &str, s: &str) {
     #[test]
     fn test_concat_slices() {
         fn t(v: &[&str], s: &str) {
-            assert_eq!(v.concat(), s.to_str().into_owned());
+            assert_eq!(v.concat(), s.to_str().into_string());
         }
         t(["you", "know", "I'm", "no", "good"], "youknowI'mnogood");
         let v: &[&str] = [];
@@ -1081,7 +1081,7 @@ fn t(v: &[&str], s: &str) {
     #[test]
     fn test_connect_slices() {
         fn t(v: &[&str], sep: &str, s: &str) {
-            assert_eq!(v.connect(sep), s.to_str().into_owned());
+            assert_eq!(v.connect(sep), s.to_str().into_string());
         }
         t(["you", "know", "I'm", "no", "good"],
           " ", "you know I'm no good");
@@ -2123,7 +2123,7 @@ fn test_maybe_owned_traits() {
         assert_eq!(s.len(), 5);
         assert_eq!(s.as_slice(), "abcde");
         assert_eq!(s.to_str(), "abcde".to_string());
-        assert_eq!(format_strbuf!("{}", s), "abcde".to_string());
+        assert_eq!(format!("{}", s), "abcde".to_string());
         assert!(s.lt(&Owned("bcdef".to_string())));
         assert_eq!(Slice(""), Default::default());
 
@@ -2131,7 +2131,7 @@ fn test_maybe_owned_traits() {
         assert_eq!(o.len(), 5);
         assert_eq!(o.as_slice(), "abcde");
         assert_eq!(o.to_str(), "abcde".to_string());
-        assert_eq!(format_strbuf!("{}", o), "abcde".to_string());
+        assert_eq!(format!("{}", o), "abcde".to_string());
         assert!(o.lt(&Slice("bcdef")));
         assert_eq!(Owned("".to_string()), Default::default());
 
@@ -2162,9 +2162,9 @@ fn test_maybe_owned_clone() {
     }
 
     #[test]
-    fn test_maybe_owned_into_owned() {
-        assert_eq!(Slice("abcde").into_owned(), "abcde".to_string());
-        assert_eq!(Owned("abcde".to_string()).into_owned(), "abcde".to_string());
+    fn test_maybe_owned_into_string() {
+        assert_eq!(Slice("abcde").into_string(), "abcde".to_string());
+        assert_eq!(Owned("abcde".to_string()).into_string(), "abcde".to_string());
     }
 
     #[test]
index dce96cb2e8f3276afa2805768984af1fe3efe6fc..0edbaf99210034bfa345af26054ab09dbc6bceb7 100644 (file)
@@ -322,11 +322,6 @@ fn as_slice<'a>(&'a self) -> &'a str {
 }
 
 impl StrAllocating for String {
-    #[inline]
-    fn into_owned(self) -> String {
-        self
-    }
-
     #[inline]
     fn into_string(self) -> String {
         self
index c2100111e126803788fcda483c25764a834bc43b..3b223b68ee666204d7d7412ef6c85317e3f9fa02 100644 (file)
@@ -31,7 +31,7 @@ pub trait IntoStr {
 
 impl<T: fmt::Show> ToStr for T {
     fn to_str(&self) -> String {
-        format_strbuf!("{}", *self)
+        format!("{}", *self)
     }
 }
 
index edeff1229bd91ee1ad954d2751f62b8ee6bf588b..d6af10ddc1855cd7b4f0bb33ce290f27a9016c4c 100644 (file)
@@ -347,7 +347,7 @@ pub enum Pat_ {
                                      * we don't bind the fields to names */
     PatStruct(Path, Vec<FieldPat> , bool),
     PatTup(Vec<@Pat> ),
-    PatUniq(@Pat),
+    PatBox(@Pat),
     PatRegion(@Pat), // reference pattern
     PatLit(@Expr),
     PatRange(@Expr, @Expr),
index 5b61cd45483ac2d2eac0a35654c6ad6299a31d4e..e4f2f7f26cf0da1c328147bb919527a24ef56af4 100644 (file)
@@ -657,7 +657,7 @@ pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
         PatEnum(_, Some(ref s)) | PatTup(ref s) => {
             s.iter().advance(|&p| walk_pat(p, |p| it(p)))
         }
-        PatUniq(s) | PatRegion(s) => {
+        PatBox(s) | PatRegion(s) => {
             walk_pat(s, it)
         }
         PatVec(ref before, ref slice, ref after) => {
index 92b3788c247443c53791a8eecbb6e8480ac52d09..4a8c64f870b7b2ae3e54aebd2867513c6cca1c05 100644 (file)
@@ -53,7 +53,7 @@ macro_rules! md (
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "cmp", "Eq")),
+        path: Path::new(vec!("std", "cmp", "PartialEq")),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
index dd2f90cfa5fae9ac21880ad8a78513c6567d063d..5d5619a740ff904ce1c6122e7f650ee78103efdf 100644 (file)
@@ -43,7 +43,7 @@ macro_rules! md (
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "cmp", "Ord")),
+        path: Path::new(vec!("std", "cmp", "PartialOrd")),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
index aeff36a49e60e70b0b66fa4c07a0e6b1aa62618b..e5da7330a6cdab1f4ab03934567e23c95e47e4df 100644 (file)
@@ -77,9 +77,10 @@ macro_rules! expand(($func:path) => ($func(cx, titem.span,
                             "Encodable" => expand!(encodable::expand_deriving_encodable),
                             "Decodable" => expand!(decodable::expand_deriving_decodable),
 
-                            "Eq" => expand!(eq::expand_deriving_eq),
+                            // NOTE this needs treatment after a stage0 snap
+                            "PartialEq" | "Eq" => expand!(eq::expand_deriving_eq),
                             "TotalEq" => expand!(totaleq::expand_deriving_totaleq),
-                            "Ord" => expand!(ord::expand_deriving_ord),
+                            "PartialOrd" | "Ord" => expand!(ord::expand_deriving_ord),
                             "TotalOrd" => expand!(totalord::expand_deriving_totalord),
 
                             "Rand" => expand!(rand::expand_deriving_rand),
index 397b99925c8ec6a33e57e350f7d1dd3c65bddc3f..5314b39f8056dce9b897cbe0978db2c618c41974 100644 (file)
@@ -23,7 +23,7 @@ pub fn expand_deriving_rand(cx: &mut ExtCtxt,
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("rand", "Rand")),
+        path: Path::new(vec!("std", "rand", "Rand")),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -33,7 +33,7 @@ pub fn expand_deriving_rand(cx: &mut ExtCtxt,
                     lifetimes: Vec::new(),
                     bounds: vec!(("R",
                                   ast::StaticSize,
-                                  vec!( Path::new(vec!("rand", "Rng")) )))
+                                  vec!( Path::new(vec!("std", "rand", "Rng")) )))
                 },
                 explicit_self: None,
                 args: vec!(
@@ -58,6 +58,7 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure)
         _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`")
     };
     let rand_ident = vec!(
+        cx.ident_of("std"),
         cx.ident_of("rand"),
         cx.ident_of("Rand"),
         cx.ident_of("rand")
index f21239af6afc84a4b2f26e44c70645ad36d59ae7..c05fc8ce6d9e679dc42d1a5efd860d90f5fefab7 100644 (file)
@@ -895,8 +895,8 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
     match parser.errors.shift() {
         Some(error) => {
             cx.ecx.span_err(efmt.span,
-                            format_strbuf!("invalid format string: {}",
-                                           error).as_slice());
+                            format!("invalid format string: {}",
+                                    error).as_slice());
             return DummyResult::raw_expr(sp);
         }
         None => {}
index b66d1f7eae58258cd448c12aa399be6e35ce3c8d..8903eb80829b4d7efd61bf0b48401d8a797470bb 100644 (file)
@@ -760,7 +760,7 @@ pub fn noop_fold_pat<T: Folder>(p: @Pat, folder: &mut T) -> @Pat {
             PatStruct(pth_, fs, etc)
         }
         PatTup(ref elts) => PatTup(elts.iter().map(|x| folder.fold_pat(*x)).collect()),
-        PatUniq(inner) => PatUniq(folder.fold_pat(inner)),
+        PatBox(inner) => PatBox(folder.fold_pat(inner)),
         PatRegion(inner) => PatRegion(folder.fold_pat(inner)),
         PatRange(e1, e2) => {
             PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
index 65ad83d4b4fb15948635ab7cf55fc8adc6605bc1..1902df30b99667f0208e744a8830074d0f0cc708 100644 (file)
@@ -39,7 +39,7 @@
 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
-use ast::{PatTup, PatUniq, PatWild, PatWildMulti};
+use ast::{PatTup, PatBox, PatWild, PatWildMulti};
 use ast::{BiRem, Required};
 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
 use ast::{Sized, DynSize, StaticSize};
@@ -2784,7 +2784,7 @@ pub fn parse_pat(&mut self) -> @Pat {
             // parse ~pat
             self.bump();
             let sub = self.parse_pat();
-            pat = PatUniq(sub);
+            pat = PatBox(sub);
             hi = self.last_span.hi;
             self.obsolete(self.last_span, ObsoleteOwnedPattern);
             return @ast::Pat {
@@ -2888,7 +2888,7 @@ pub fn parse_pat(&mut self) -> @Pat {
             // FIXME(#13910): Rename to `PatBox` and extend to full DST
             // support.
             let sub = self.parse_pat();
-            pat = PatUniq(sub);
+            pat = PatBox(sub);
             hi = self.last_span.hi;
             return @ast::Pat {
                 id: ast::DUMMY_NODE_ID,
index 3127085ffedca2684a070b01cd97abe6eb3e7050..90436faca23c19405b2a5e5492a4dee186690cb1 100644 (file)
@@ -1721,7 +1721,7 @@ pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
                 }
                 try!(self.pclose());
             }
-            ast::PatUniq(inner) => {
+            ast::PatBox(inner) => {
                 try!(word(&mut self.s, "box "));
                 try!(self.print_pat(inner));
             }
index eb7aeb0e327a0e116386ecfb18c32c69de2df2b1..efa8c8e66640fe92d377c431d3dd459b24cbdafd 100644 (file)
@@ -429,7 +429,7 @@ pub fn walk_pat<E: Clone, V: Visitor<E>>(visitor: &mut V, pattern: &Pat, env: E)
                 visitor.visit_pat(*tuple_element, env.clone())
             }
         }
-        PatUniq(subpattern) |
+        PatBox(subpattern) |
         PatRegion(subpattern) => {
             visitor.visit_pat(subpattern, env)
         }
index db9509a9dd2114c85479af8737ee823b74db1f48..3da8d7672f5639895e6158ccaae7fc83da083ada 100644 (file)
@@ -281,9 +281,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
                     ';' => (),
 
                     _ => {
-                        return Err(format_strbuf!("unrecognized format \
-                                                   option {}",
-                                                  cur))
+                        return Err(format!("unrecognized format option {}", cur))
                     }
                 }
             },
@@ -549,8 +547,8 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
                     s
                 }
                 _ => {
-                    return Err(format_strbuf!("non-string on stack with %{}",
-                                              op.to_char()))
+                    return Err(format!("non-string on stack with %{}",
+                                       op.to_char()))
                 }
             }
         }
index 1a42addb4bd13455255185869028990fc2dd424e..b155753191c824f67d718311be72a84003137ed4 100644 (file)
@@ -164,7 +164,7 @@ pub fn parse(file: &mut io::Reader, longnames: bool)
     macro_rules! try( ($e:expr) => (
         match $e {
             Ok(e) => e,
-            Err(e) => return Err(format_strbuf!("{}", e))
+            Err(e) => return Err(format!("{}", e))
         }
     ) )
 
@@ -185,10 +185,8 @@ macro_rules! try( ($e:expr) => (
     // Check magic number
     let magic = try!(file.read_le_u16());
     if magic != 0x011A {
-        return Err(format_strbuf!("invalid magic number: expected {:x} but \
-                                   found {:x}",
-                                  0x011A,
-                                  magic as uint));
+        return Err(format!("invalid magic number: expected {:x} but found {:x}",
+                           0x011A, magic as uint));
     }
 
     let names_bytes          = try!(file.read_le_i16()) as int;
index 84f0a4e3565f2c1e4085bbbc4141a8600532c55f..6b8ebb670e7b37963f1d3caf37546b124c99db08 100644 (file)
@@ -81,11 +81,11 @@ pub fn open(term: &str) -> Result<File, String> {
         Some(x) => {
             match File::open(x) {
                 Ok(file) => Ok(file),
-                Err(e) => Err(format_strbuf!("error opening file: {}", e)),
+                Err(e) => Err(format!("error opening file: {}", e)),
             }
         }
         None => {
-            Err(format_strbuf!("could not find terminfo entry for {}", term))
+            Err(format!("could not find terminfo entry for {}", term))
         }
     }
 }
index f02bc144d153cd6cbcdea5116f61f120a58bd76d..1de7f90c8069dce183f99ce7f401eb61570b7bef 100644 (file)
@@ -374,7 +374,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
         let s = matches.free.get(0).as_slice();
         match Regex::new(s) {
             Ok(re) => Some(re),
-            Err(e) => return Some(Err(format_strbuf!("could not parse /{}/: {}", s, e)))
+            Err(e) => return Some(Err(format!("could not parse /{}/: {}", s, e)))
         }
     } else {
         None
@@ -739,22 +739,20 @@ pub fn write_run_finish(&mut self,
 pub fn fmt_metrics(mm: &MetricMap) -> String {
     let MetricMap(ref mm) = *mm;
     let v : Vec<String> = mm.iter()
-        .map(|(k,v)| format_strbuf!("{}: {} (+/- {})",
-                          *k,
-                          v.value as f64,
-                          v.noise as f64))
+        .map(|(k,v)| format!("{}: {} (+/- {})", *k,
+                             v.value as f64, v.noise as f64))
         .collect();
     v.connect(", ").to_string()
 }
 
 pub fn fmt_bench_samples(bs: &BenchSamples) -> String {
     if bs.mb_s != 0 {
-        format_strbuf!("{:>9} ns/iter (+/- {}) = {} MB/s",
+        format!("{:>9} ns/iter (+/- {}) = {} MB/s",
              bs.ns_iter_summ.median as uint,
              (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as uint,
              bs.mb_s)
     } else {
-        format_strbuf!("{:>9} ns/iter (+/- {})",
+        format!("{:>9} ns/iter (+/- {})",
              bs.ns_iter_summ.median as uint,
              (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as uint)
     }
index 9b5bbbadc9c5eb0b3e0ef6157552179a38bee3f8..e9b20c0117d98d3e7afe5834c45a40299e761f44 100644 (file)
@@ -363,7 +363,7 @@ pub fn rfc3339(&self) -> String {
             let mut m = num::abs(self.tm_gmtoff) / 60_i32;
             let h = m / 60_i32;
             m -= h * 60_i32;
-            format_strbuf!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
+            format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
         }
     }
 }
@@ -469,7 +469,7 @@ fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
         if c == range.ch {
             Ok(range.next)
         } else {
-            Err(format_strbuf!("Expected {}, found {}",
+            Err(format!("Expected {}, found {}",
                 str::from_char(c),
                 str::from_char(range.ch)))
         }
@@ -772,8 +772,7 @@ fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
           }
           '%' => parse_char(s, pos, '%'),
           ch => {
-            Err(format_strbuf!("unknown formatting type: {}",
-                               str::from_char(ch)))
+            Err(format!("unknown formatting type: {}", str::from_char(ch)))
           }
         }
     }
@@ -889,16 +888,16 @@ fn iso_week(ch:char, tm: &Tm) -> String {
         }
 
         match ch {
-            'G' => format_strbuf!("{}", year),
-            'g' => format_strbuf!("{:02d}", (year % 100 + 100) % 100),
-            'V' => format_strbuf!("{:02d}", days / 7 + 1),
+            'G' => format!("{}", year),
+            'g' => format!("{:02d}", (year % 100 + 100) % 100),
+            'V' => format!("{:02d}", days / 7 + 1),
             _ => "".to_string()
         }
     }
 
     fn parse_type(ch: char, tm: &Tm) -> String {
       let die = || {
-          format_strbuf!("strftime: can't understand this format {} ", ch)
+          format!("strftime: can't understand this format {} ", ch)
       };
         match ch {
           'A' => match tm.tm_wday as int {
@@ -951,9 +950,9 @@ fn parse_type(ch: char, tm: &Tm) -> String {
             11 => "Dec".to_string(),
             _  => die()
           },
-          'C' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) / 100),
+          'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
           'c' => {
-            format_strbuf!("{} {} {} {} {}",
+            format!("{} {} {} {} {}",
                 parse_type('a', tm),
                 parse_type('b', tm),
                 parse_type('e', tm),
@@ -961,89 +960,89 @@ fn parse_type(ch: char, tm: &Tm) -> String {
                 parse_type('Y', tm))
           }
           'D' | 'x' => {
-            format_strbuf!("{}/{}/{}",
+            format!("{}/{}/{}",
                 parse_type('m', tm),
                 parse_type('d', tm),
                 parse_type('y', tm))
           }
-          'd' => format_strbuf!("{:02d}", tm.tm_mday),
-          'e' => format_strbuf!("{:2d}", tm.tm_mday),
-          'f' => format_strbuf!("{:09d}", tm.tm_nsec),
+          'd' => format!("{:02d}", tm.tm_mday),
+          'e' => format!("{:2d}", tm.tm_mday),
+          'f' => format!("{:09d}", tm.tm_nsec),
           'F' => {
-            format_strbuf!("{}-{}-{}",
+            format!("{}-{}-{}",
                 parse_type('Y', tm),
                 parse_type('m', tm),
                 parse_type('d', tm))
           }
           'G' => iso_week('G', tm),
           'g' => iso_week('g', tm),
-          'H' => format_strbuf!("{:02d}", tm.tm_hour),
+          'H' => format!("{:02d}", tm.tm_hour),
           'I' => {
             let mut h = tm.tm_hour;
             if h == 0 { h = 12 }
             if h > 12 { h -= 12 }
-            format_strbuf!("{:02d}", h)
+            format!("{:02d}", h)
           }
-          'j' => format_strbuf!("{:03d}", tm.tm_yday + 1),
-          'k' => format_strbuf!("{:2d}", tm.tm_hour),
+          'j' => format!("{:03d}", tm.tm_yday + 1),
+          'k' => format!("{:2d}", tm.tm_hour),
           'l' => {
             let mut h = tm.tm_hour;
             if h == 0 { h = 12 }
             if h > 12 { h -= 12 }
-            format_strbuf!("{:2d}", h)
+            format!("{:2d}", h)
           }
-          'M' => format_strbuf!("{:02d}", tm.tm_min),
-          'm' => format_strbuf!("{:02d}", tm.tm_mon + 1),
+          'M' => format!("{:02d}", tm.tm_min),
+          'm' => format!("{:02d}", tm.tm_mon + 1),
           'n' => "\n".to_string(),
           'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
           'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
           'R' => {
-            format_strbuf!("{}:{}",
+            format!("{}:{}",
                 parse_type('H', tm),
                 parse_type('M', tm))
           }
           'r' => {
-            format_strbuf!("{}:{}:{} {}",
+            format!("{}:{}:{} {}",
                 parse_type('I', tm),
                 parse_type('M', tm),
                 parse_type('S', tm),
                 parse_type('p', tm))
           }
-          'S' => format_strbuf!("{:02d}", tm.tm_sec),
-          's' => format_strbuf!("{}", tm.to_timespec().sec),
+          'S' => format!("{:02d}", tm.tm_sec),
+          's' => format!("{}", tm.to_timespec().sec),
           'T' | 'X' => {
-            format_strbuf!("{}:{}:{}",
+            format!("{}:{}:{}",
                 parse_type('H', tm),
                 parse_type('M', tm),
                 parse_type('S', tm))
           }
           't' => "\t".to_string(),
-          'U' => format_strbuf!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
+          'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
           'u' => {
             let i = tm.tm_wday as int;
             (if i == 0 { 7 } else { i }).to_str().to_string()
           }
           'V' => iso_week('V', tm),
           'v' => {
-            format_strbuf!("{}-{}-{}",
+            format!("{}-{}-{}",
                 parse_type('e', tm),
                 parse_type('b', tm),
                 parse_type('Y', tm))
           }
           'W' => {
-              format_strbuf!("{:02d}",
+              format!("{:02d}",
                              (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
           }
           'w' => (tm.tm_wday as int).to_str().to_string(),
           'Y' => (tm.tm_year as int + 1900).to_str().to_string(),
-          'y' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) % 100),
+          'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
           'Z' => "".to_string(),    // FIXME(pcwalton): Implement this.
           'z' => {
             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
             let h = m / 60_i32;
             m -= h * 60_i32;
-            format_strbuf!("{}{:02d}{:02d}", sign, h, m)
+            format!("{}{:02d}{:02d}", sign, h, m)
           }
           '+' => tm.rfc3339(),
           '%' => "%".to_string(),
index a9c80c90fd6c8f601ddbdf6cc4daa98c9240223f..8263fcda314f8b3ddb4703272ff9cbdc0b058a36 100644 (file)
@@ -67,21 +67,19 @@ fn main() {
 // test harness access
 #[cfg(test)]
 extern crate test;
-
-extern crate rand;
 extern crate serialize;
 
-use std::mem::{transmute,transmute_copy};
 use std::char::Char;
 use std::default::Default;
 use std::fmt;
 use std::from_str::FromStr;
 use std::hash::Hash;
+use std::mem::{transmute,transmute_copy};
 use std::num::FromStrRadix;
-use std::str;
+use std::rand;
+use std::rand::Rng;
 use std::slice;
-
-use rand::Rng;
+use std::str;
 
 use serialize::{Encoder, Encodable, Decoder, Decodable};
 
@@ -194,7 +192,7 @@ pub fn new(v: UuidVersion) -> Option<Uuid> {
     /// of random numbers. Use the rand::Rand trait to supply
     /// a custom generator if required.
     pub fn new_v4() -> Uuid {
-        let ub = rand::task_rng().gen_vec(16);
+        let ub = rand::task_rng().gen_iter::<u8>().take(16).collect::<Vec<_>>();
         let mut uuid = Uuid{ bytes: [0, .. 16] };
         slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
         uuid.set_variant(VariantRFC4122);
@@ -346,8 +344,8 @@ pub fn to_hyphenated_str(&self) -> String {
         uf.data1 = to_be32(uf.data1);
         uf.data2 = to_be16(uf.data2);
         uf.data3 = to_be16(uf.data3);
-        let s = format_strbuf!("{:08x}-{:04x}-{:04x}-{:02x}{:02x}-\
-                                {:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
+        let s = format!("{:08x}-{:04x}-{:04x}-{:02x}{:02x}-\
+                         {:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
             uf.data1,
             uf.data2, uf.data3,
             uf.data4[0], uf.data4[1],
@@ -362,7 +360,7 @@ pub fn to_hyphenated_str(&self) -> String {
     ///
     /// Example: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
     pub fn to_urn_str(&self) -> String {
-        format_strbuf!("urn:uuid:{}", self.to_hyphenated_str())
+        format!("urn:uuid:{}", self.to_hyphenated_str())
     }
 
     /// Parses a UUID from a string of hexadecimal digits with optional hyphens
@@ -510,7 +508,7 @@ fn decode(d: &mut T) -> Result<Uuid, E> {
 impl rand::Rand for Uuid {
     #[inline]
     fn rand<R: rand::Rng>(rng: &mut R) -> Uuid {
-        let ub = rng.gen_vec(16);
+        let ub = rng.gen_iter::<u8>().take(16).collect::<Vec<_>>();
         let mut uuid = Uuid{ bytes: [0, .. 16] };
         slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
         uuid.set_variant(VariantRFC4122);
@@ -522,13 +520,13 @@ fn rand<R: rand::Rng>(rng: &mut R) -> Uuid {
 #[cfg(test)]
 mod test {
     extern crate collections;
-    extern crate rand;
 
     use super::{Uuid, VariantMicrosoft, VariantNCS, VariantRFC4122,
                 Version1Mac, Version2Dce, Version3Md5, Version4Random,
                 Version5Sha1};
     use std::str;
     use std::io::MemWriter;
+    use std::rand;
 
     #[test]
     fn test_nil() {
@@ -788,7 +786,7 @@ fn test_operator_eq() {
     #[test]
     fn test_rand_rand() {
         let mut rng = rand::task_rng();
-        let u: Box<Uuid> = rand::Rand::rand(&mut rng);
+        let u: Uuid = rand::Rand::rand(&mut rng);
         let ub = u.as_bytes();
 
         assert!(ub.len() == 16);
index d53a89684213d19446ad7197101f4f4021d3d0a5..bf50736b7e6d1bfef9887fd828699e4993f907bc 100644 (file)
 
 #![feature(macro_rules)]
 
-extern crate rand;
 extern crate time;
 
 use time::precise_time_s;
-use rand::Rng;
+use std::rand;
+use std::rand::Rng;
 use std::mem::swap;
 use std::os;
 use std::str;
index 27540cc5bbf945baecb2d3409d9d49baa7700337..816a752921222b5594add561527501a0e68fba84 100644 (file)
 // Multi-language Perlin noise benchmark.
 // See https://github.com/nsf/pnoise for timings and alternative implementations.
 
-extern crate rand;
-
 use std::f32::consts::PI;
-use rand::{Rng, StdRng};
+use std::rand::{Rng, StdRng};
 
 struct Vec2 {
     x: f32,
index db68edc73ba80beb4303f93fcb9d6450d7739b8a..1dc52166965778bb7ce37043f86423e32b75df7d 100644 (file)
@@ -74,8 +74,8 @@ fn main() {
                     let b = bottom_up_tree(&arena, -i, depth);
                     chk += item_check(a) + item_check(b);
                 }
-                format_strbuf!("{}\t trees of depth {}\t check: {}",
-                               iterations * 2, depth, chk)
+                format!("{}\t trees of depth {}\t check: {}",
+                        iterations * 2, depth, chk)
             })
         }).collect::<Vec<Future<String>>>();
 
index 2c8b23f2acdf1274049976cbcfbe1770c6a85436..baf02feb5b80a827510c6c16725a40976662a25d 100644 (file)
@@ -134,9 +134,7 @@ fn creature(
         }
     }
     // log creatures met and evil clones of self
-    let report = format_strbuf!("{}{}",
-                                creatures_met,
-                                Number(evil_clones_met));
+    let report = format!("{}{}", creatures_met, Number(evil_clones_met));
     to_rendezvous_log.send(report);
 }
 
index 8be6439d88c413499a5743a9e7356dd48fae1336..e39c51dd73a9f3d17f1e2ccaddda593a6239f97c 100644 (file)
@@ -129,11 +129,11 @@ fn make_sequence_processor(sz: uint,
    let buffer = match sz {
        1u => { sort_and_fmt(&freqs, total) }
        2u => { sort_and_fmt(&freqs, total) }
-       3u => { format_strbuf!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
-       4u => { format_strbuf!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
-       6u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
-      12u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
-      18u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
+       3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
+       4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
+       6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
+      12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
+      18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
                        "GGTATTTTAATTTATAGT") }
         _ => { "".to_string() }
    };
index 85bad9f8d60121adb29d1f29e54e5ac85d063a6c..de558401aa6f07c69cecf3ead5ce4e11985fb4a4 100644 (file)
@@ -11,8 +11,8 @@
 // Regression test for #13428
 
 fn foo() -> String {  //~ ERROR not all control paths return a value
-    format_strbuf!("Hello {}",
-                   "world")
+    format!("Hello {}",
+            "world")
     // Put the trailing semicolon on its own line to test that the
     // note message gets the offending semicolon exactly
     ;   //~ NOTE consider removing this semicolon
index 8b9d4de9f04c1d3194a439c1bbcd43e61150aef1..366e1fd4dcae4b7e9ca41f132e2506de7aeac13e 100644 (file)
 
 // ensure that the TaskRng isn't/doesn't become accidentally sendable.
 
-extern crate rand;
+use std::rand;
 
 fn test_send<S: Send>() {}
 
 pub fn main() {
-    test_send::<::rand::TaskRng>();
-    //~^ ERROR: incompatible type `rand::TaskRng`, which does not fulfill `Send`
+    test_send::<rand::TaskRng>();
+    //~^ ERROR: incompatible type `std::rand::TaskRng`, which does not fulfill `Send`
 }
index 7126aec239177853e7f0597386936cd0436bc943..a377d68a33d8cbd9502a69848d8f1ab36714baae 100644 (file)
@@ -22,7 +22,7 @@
 // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}}
 
 // gdb-command:print *univariant_ref
-// gdb-check:$3 = {4820353753753434}
+// gdb-check:$3 = {{4820353753753434}}
 
 #![allow(unused_variable)]
 #![feature(struct_variant)]
index 498d0981e35d0ada080966e2f3f93e764a565fc8..eddf4dfd7553ec4a905cdf3839a1f0928283d134 100644 (file)
@@ -27,7 +27,7 @@
 // gdb-check:$3 = {{Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {Case3, a = 0, b = 1499027801, c = 1499027801}, {Case3, a = 0, b = 6438275382588823897}}
 
 // gdb-command:print univariant
-// gdb-check:$4 = {a = -1}
+// gdb-check:$4 = {{a = -1}}
 
 #![feature(struct_variant)]
 
index 16a665ca8c67e8ed89c1c910270687d6207d5239..07f7546068ca9f7fc12125638e26c221b1c20e0a 100644 (file)
@@ -27,7 +27,7 @@
 // gdb-check:$3 = {{Case3, 0, 22873, 22873, 22873, 22873}, {Case3, 0, 1499027801, 1499027801}, {Case3, 0, 6438275382588823897}}
 
 // gdb-command:print univariant
-// gdb-check:$4 = {-1}
+// gdb-check:$4 = {{-1}}
 
 
 // NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
index 7899e0c6a9b539fb6447c9c251d122e1b7742b69..36e75812debdff0b03f00e50290179c340740fb2 100644 (file)
@@ -22,7 +22,7 @@
 // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}}
 
 // gdb-command:print univariant->val
-// gdb-check:$3 = {-9747455}
+// gdb-check:$3 = {{-9747455}}
 
 #![allow(unused_variable)]
 #![feature(struct_variant, managed_boxes)]
index 803d0aed593a3d8439e2cb379ecfb9c16b7371b6..04cd7e1386324312ff7ad2325105a5ddadecfa2a 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// ignore-tidy-linelength
 // ignore-android: FIXME(#10381)
 
 // compile-flags:-g
 // gdb-command:finish
 
 // gdb-command:print some
-// gdb-check:$1 = (u32 *) 0x12345678
+// gdb-check:$1 = {RUST$ENCODED$ENUM$0$None = {0x12345678}}
 
 // gdb-command:print none
-// gdb-check:$2 = (u32 *) 0x0
+// gdb-check:$2 = {RUST$ENCODED$ENUM$0$None = {0x0}}
 
 // gdb-command:print full
-// gdb-check:$3 = {454545, 0x87654321, 9988}
+// gdb-check:$3 = {RUST$ENCODED$ENUM$1$Empty = {454545, 0x87654321, 9988}}
 
 // gdb-command:print empty->discr
 // gdb-check:$4 = (int *) 0x0
 
 // gdb-command:print droid
-// gdb-check:$5 = {id = 675675, range = 10000001, internals = 0x43218765}
+// gdb-check:$5 = {RUST$ENCODED$ENUM$2$Void = {id = 675675, range = 10000001, internals = 0x43218765}}
 
 // gdb-command:print void_droid->internals
 // gdb-check:$6 = (int *) 0x0
index aa13072eb5316606935026b6d77aa9ca5ef61478..518ef62fe9a68551c9793306dff2201d88d99e48 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// ignore-tidy-linelength
 // ignore-android: FIXME(#10381)
 
 #![feature(managed_boxes)]
 
 // gdb-command:print stack_unique.value
 // gdb-check:$1 = 0
-// gdb-command:print stack_unique.next->value
+// gdb-command:print stack_unique.next.RUST$ENCODED$ENUM$0$Empty.val->value
 // gdb-check:$2 = 1
 
 // gdb-command:print unique_unique->value
 // gdb-check:$3 = 2
-// gdb-command:print unique_unique->next->value
+// gdb-command:print unique_unique->next.RUST$ENCODED$ENUM$0$Empty.val->value
 // gdb-check:$4 = 3
 
 // gdb-command:print box_unique->val.value
 // gdb-check:$5 = 4
-// gdb-command:print box_unique->val.next->value
+// gdb-command:print box_unique->val.next.RUST$ENCODED$ENUM$0$Empty.val->value
 // gdb-check:$6 = 5
 
 // gdb-command:print vec_unique[0].value
 // gdb-check:$7 = 6.5
-// gdb-command:print vec_unique[0].next->value
+// gdb-command:print vec_unique[0].next.RUST$ENCODED$ENUM$0$Empty.val->value
 // gdb-check:$8 = 7.5
 
 // gdb-command:print borrowed_unique->value
 // gdb-check:$9 = 8.5
-// gdb-command:print borrowed_unique->next->value
+// gdb-command:print borrowed_unique->next.RUST$ENCODED$ENUM$0$Empty.val->value
 // gdb-check:$10 = 9.5
 
 // MANAGED
 // gdb-command:print stack_managed.value
 // gdb-check:$11 = 10
-// gdb-command:print stack_managed.next.val->value
+// gdb-command:print stack_managed.next.RUST$ENCODED$ENUM$0$Empty.val->val.value
 // gdb-check:$12 = 11
 
 // gdb-command:print unique_managed->value
 // gdb-check:$13 = 12
-// gdb-command:print unique_managed->next.val->value
+// gdb-command:print unique_managed->next.RUST$ENCODED$ENUM$0$Empty.val->val.value
 // gdb-check:$14 = 13
 
 // gdb-command:print box_managed.val->value
 // gdb-check:$15 = 14
-// gdb-command:print box_managed->val->next.val->value
+// gdb-command:print box_managed->val->next.RUST$ENCODED$ENUM$0$Empty.val->val.value
 // gdb-check:$16 = 15
 
 // gdb-command:print vec_managed[0].value
 // gdb-check:$17 = 16.5
-// gdb-command:print vec_managed[0].next.val->value
+// gdb-command:print vec_managed[0].next.RUST$ENCODED$ENUM$0$Empty.val->val.value
 // gdb-check:$18 = 17.5
 
 // gdb-command:print borrowed_managed->value
 // gdb-check:$19 = 18.5
-// gdb-command:print borrowed_managed->next.val->value
+// gdb-command:print borrowed_managed->next.RUST$ENCODED$ENUM$0$Empty.val->val.value
 // gdb-check:$20 = 19.5
 
 // LONG CYCLE
@@ -97,7 +98,7 @@
 // gdb-command:print (*****long_cycle_w_anonymous_types).value
 // gdb-check:$31 = 30
 
-// gdb-command:print (*****((*****long_cycle_w_anonymous_types).next)).value
+// gdb-command:print (*****((*****long_cycle_w_anonymous_types).next.RUST$ENCODED$ENUM$0$Empty.val)).value
 // gdb-check:$32 = 31
 
 // gdb-command:continue
index ee971d71cfcf15b078a310bd4ac1ffe7b72ab416..0cba56ad320ec834ce77cda38252487f0823a26c 100644 (file)
@@ -24,7 +24,7 @@
 // gdb-check:$2 = {{Case2, 0, {x = 286331153, y = 286331153, z = 4369}}, {Case2, 0, 1229782938247303441, 4369}}
 
 // gdb-command:print univariant
-// gdb-check:$3 = {{x = 123, y = 456, z = 789}}
+// gdb-check:$3 = {{{x = 123, y = 456, z = 789}}}
 
 #![allow(unused_variable)]
 
index 1a51db1a005bddd5f3eee6597d360b7fbe3fd7b0..70d4d709d23c81547ad410057f09d40027a8866e 100644 (file)
@@ -27,7 +27,7 @@
 // gdb-check:$3 = {{Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {Case3, a = 0, b = 1499027801, c = 1499027801}, {Case3, a = 0, b = 6438275382588823897}}
 
 // gdb-command:print univariant
-// gdb-check:$4 = {a = -1}
+// gdb-check:$4 = {{a = -1}}
 
 #![allow(unused_variable)]
 #![feature(struct_variant)]
index dc922b450051e49d7e2354a9419395c8960bf053..81c72d16886439bc468288a3087ff198286a8ffe 100644 (file)
@@ -27,7 +27,7 @@
 // gdb-check:$3 = {{Case3, 0, 22873, 22873, 22873, 22873}, {Case3, 0, 1499027801, 1499027801}, {Case3, 0, 6438275382588823897}}
 
 // gdb-command:print univariant
-// gdb-check:$4 = {-1}
+// gdb-check:$4 = {{-1}}
 
 #![allow(unused_variable)]
 
index f85ec6a8da3a223901dd7b302627ccbe5af8fbc5..3949a315adca2b79783cca5175e6f8ec672f06f5 100644 (file)
@@ -22,7 +22,7 @@
 // gdb-check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}}
 
 // gdb-command:print *univariant
-// gdb-check:$3 = {123234}
+// gdb-check:$3 = {{123234}}
 
 #![allow(unused_variable)]
 #![feature(struct_variant)]
index 9160b760c92d60a7e46ef7f4693593914f49466b..f860fdffba1a329da93e3be96b830279f5f659ac 100644 (file)
@@ -15,5 +15,5 @@
 fn main() {
     let mut a = 1;
     if 1 == 1 { a = 2; }
-    fail!(format_strbuf!("woooo{}", "o"));
+    fail!(format!("woooo{}", "o"));
 }
index 00183aa674fa455435a702b80c1c33032e022dc9..336df3ff965264ce9ace2c3740bdb6a99a7a2126 100644 (file)
@@ -20,10 +20,10 @@ fn main() {
         macerate((*tasties).clone());
     });
     result(carrots, |food| {
-        let mush = format_strbuf!("{}{}", food, cheese);
+        let mush = format!("{}{}", food, cheese);
         let cheese = cheese.clone();
         let f: || = || {
-            let _chew = format_strbuf!("{}{}", mush, cheese);
+            let _chew = format!("{}{}", mush, cheese);
             fail!("so yummy")
         };
         f();
index e41c5d1b6266e5c86c4e0f9f661599f43c05a7a7..3711503ee2b590889380d019d74225d55cb583f5 100644 (file)
@@ -8,11 +8,9 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-extern crate rand;
-use rand::{task_rng, Rng};
-
 use std::{char, os, str};
 use std::io::{File, Command};
+use std::rand::{task_rng, Rng};
 
 // creates unicode_input_multiple_files_{main,chars}.rs, where the
 // former imports the latter. `_chars` just contains an indentifier
index b875f676982dc0928e7e899855f0332847814127..ebb03435fe4d9226b5eb6ce324b42cbdf49c0288 100644 (file)
@@ -8,11 +8,9 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-extern crate rand;
-use rand::{task_rng, Rng};
-
 use std::{char, os, str};
 use std::io::{File, Command};
+use std::rand::{task_rng, Rng};
 
 // creates a file with `fn main() { <random ident> }` and checks the
 // compiler emits a span of the appropriate length (for the
index e10428e3c5dc24453afddbbdb7fcd489c87ed3eb..270f85114ea4934034734c46d8ee463f4f66e314 100644 (file)
@@ -16,13 +16,13 @@ trait Foo {
 
 impl<T:Foo> Foo for @T {
     fn foo(&self) -> String {
-        format_strbuf!("@{}", (**self).foo())
+        format!("@{}", (**self).foo())
     }
 }
 
 impl Foo for uint {
     fn foo(&self) -> String {
-        format_strbuf!("{}", *self)
+        format!("{}", *self)
     }
 }
 
index 7ed5f5aef9fb767c1e566b9d90ca0c0ad2938e47..239247cdd18a67eca9f823ec347b376a9cc39f01 100644 (file)
@@ -19,15 +19,15 @@ fn hello<S:Speak>(s:&S) -> String{
 
 impl Speak for int {
     fn say(&self, s:&str) -> String {
-        format_strbuf!("{}: {}", s, *self)
+        format!("{}: {}", s, *self)
     }
 }
 
 impl<T: Speak> Speak for Option<T> {
     fn say(&self, s:&str) -> String {
         match *self {
-            None => format_strbuf!("{} - none", s),
-            Some(ref x) => { format_strbuf!("something!{}", x.say(s)) }
+            None => format!("{} - none", s),
+            Some(ref x) => { format!("something!{}", x.say(s)) }
         }
     }
 }
index 5de7aee4aa4866aadb00c3642185a3d5e1f41e41..c05f2502a893ae44514ee9c483aa742d69ce521c 100644 (file)
@@ -50,15 +50,15 @@ pub fn main() {
 
     let greeting = "Hello ".to_string();
     call_it(proc(s) {
-        format_strbuf!("{}{}", greeting, s)
+        format!("{}{}", greeting, s)
     });
 
     let greeting = "Goodbye ".to_string();
-    call_it(proc(s) format_strbuf!("{}{}", greeting, s));
+    call_it(proc(s) format!("{}{}", greeting, s));
 
     let greeting = "How's life, ".to_string();
     call_it(proc(s: String) -> String {
-        format_strbuf!("{}{}", greeting, s)
+        format!("{}{}", greeting, s)
     });
 
     // Closures
index c455aebbe46ed348c5d85fd62c92eac2462983d0..4e9592950d3da20027ff64c0f591a1c5ca8d9015 100644 (file)
@@ -8,10 +8,9 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-
 #![feature(struct_variant)]
 
-extern crate rand;
+use std::rand;
 
 #[deriving(Rand)]
 struct A;
index fa5cd97202928ab382bc764dcc7bc56823b87c76..4e5dea82cf44f9e6ca8ba352b5dedbc5ab893e70 100644 (file)
@@ -45,7 +45,7 @@ fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String,
             let name = lookup((*interface).clone(),
                               "ifDescr".to_string(),
                               "".to_string());
-            let label = format_strbuf!("{}-{}", managed_ip, name);
+            let label = format!("{}-{}", managed_ip, name);
 
             (label, bool_value(false))
         }
index ac0ac95c73bbe0a682b654a88168d85402b0d45c..323fff76efbb7723a5506e3a480432f28f232f4e 100644 (file)
@@ -13,7 +13,7 @@
 extern crate debug;
 
 fn assert_repr_eq<T>(obj : T, expected : String) {
-    assert_eq!(expected, format_strbuf!("{:?}", obj));
+    assert_eq!(expected, format!("{:?}", obj));
 }
 
 pub fn main() {
index d26075af3cedee665795c723d5bfd3ef6fa22f63..cb7a5989430a0874085b79034ffeca9d596cf32e 100644 (file)
@@ -17,19 +17,19 @@ enum foo {
 }
 
 fn check_log<T>(exp: String, v: T) {
-    assert_eq!(exp, format_strbuf!("{:?}", v));
+    assert_eq!(exp, format!("{:?}", v));
 }
 
 pub fn main() {
     let mut x = Some(a(22u));
     let exp = "Some(a(22u))".to_string();
-    let act = format_strbuf!("{:?}", x);
+    let act = format!("{:?}", x);
     assert_eq!(act, exp);
     check_log(exp, x);
 
     x = None;
     let exp = "None".to_string();
-    let act = format_strbuf!("{:?}", x);
+    let act = format!("{:?}", x);
     assert_eq!(act, exp);
     check_log(exp, x);
 }
index 2956a030faa55458f49827ee2d3c4337a461206f..e6a23d9929059c19b0d46565949b10a57b54cf39 100644 (file)
@@ -21,7 +21,7 @@ enum bar {
 }
 
 pub fn main() {
-    assert_eq!("a(22u)".to_string(), format_strbuf!("{:?}", a(22u)));
-    assert_eq!("c".to_string(), format_strbuf!("{:?}", c));
-    assert_eq!("d".to_string(), format_strbuf!("{:?}", d));
+    assert_eq!("a(22u)".to_string(), format!("{:?}", a(22u)));
+    assert_eq!("c".to_string(), format!("{:?}", c));
+    assert_eq!("d".to_string(), format!("{:?}", d));
 }
index a74f3e8332636c5b3cf68b7743e9a36e016dca65..b359614fa9adb2c365ec34174d72d8a2c858ae00 100644 (file)
@@ -22,7 +22,7 @@ fn f2(ref_string: &str) -> String {
     match ref_string {
         "a" => "found a".to_string(),
         "b" => "found b".to_string(),
-        s => format_strbuf!("not found ({})", s)
+        s => format!("not found ({})", s)
     }
 }
 
@@ -38,7 +38,7 @@ fn g2(ref_1: &str, ref_2: &str) -> String {
     match (ref_1, ref_2) {
         ("a", "b") => "found a,b".to_string(),
         ("b", "c") => "found b,c".to_string(),
-        (s1, s2) => format_strbuf!("not found ({}, {})", s1, s2)
+        (s1, s2) => format!("not found ({}, {})", s1, s2)
     }
 }
 
index 4642978d46c78cadbb964b2de31825d79a06c984..3ad5da317013fd05f7422798338c6d5bfd8da4a3 100644 (file)
@@ -45,8 +45,8 @@ pub fn main() {
     assert_eq!(transform(Some(10)), Some("11".to_string()));
     assert_eq!(transform(None), None);
     assert!((vec!("hi".to_string()))
-        .bind(|x| vec!(x.clone(), format_strbuf!("{}!", x)) )
-        .bind(|x| vec!(x.clone(), format_strbuf!("{}?", x)) ) ==
+        .bind(|x| vec!(x.clone(), format!("{}!", x)) )
+        .bind(|x| vec!(x.clone(), format!("{}?", x)) ) ==
         vec!("hi".to_string(),
              "hi?".to_string(),
              "hi!".to_string(),
index 0bfa2a75cf51f19e21c5b4f5d1aabde327799485..70839c1884791f5b987fa2f56127694fd954414a 100644 (file)
@@ -36,8 +36,7 @@ fn main() {
     let blah       = "\u03c0\u042f\u97f3\u00e6\u221e";
 
     let child_name = "child";
-    let child_dir  = format_strbuf!("process-spawn-with-unicode-params-{}",
-                                    blah);
+    let child_dir  = format!("process-spawn-with-unicode-params-{}", blah);
 
     // parameters sent to child / expected to be received from parent
     let arg = blah;
index 9c727314ffbf50900f5ffaf2b210ee0b925f9624..5604093ea9c8add7e0e0c4930b17a76c36bb2b49 100644 (file)
@@ -61,7 +61,7 @@ pub fn main() {
     assert_eq!(map.find(&Owned("def".to_string())), Some(&d));
 
     assert!(map.pop(&Slice("foo")).is_some());
-    assert_eq!(map.move_iter().map(|(k, v)| format_strbuf!("{}{}", k, v))
+    assert_eq!(map.move_iter().map(|(k, v)| format!("{}{}", k, v))
                               .collect::<Vec<String>>()
                               .concat(),
                "abc50bcd51cde52def53".to_string());
index 51831a7b1cd035b53f3621c79ebbbbb2a3470261..7141d0b9df5250e85decc2cbe02924024289ec37 100644 (file)
@@ -14,7 +14,7 @@
 pub fn main() {
     let a: String = "hello".to_string();
     let b: String = "world".to_string();
-    let s: String = format_strbuf!("{}{}", a, b);
+    let s: String = format!("{}{}", a, b);
     println!("{}", s.clone());
     assert_eq!(s.as_slice()[9], 'd' as u8);
 }
index 4610d1ccfcc4ae8cb34b0c9a9b814c118a06c674..612483f69094d832bb86cc28bb69dba2d05b817c 100644 (file)
@@ -16,7 +16,7 @@ pub fn main() {
     while i > 0 {
         println!("{}", a.len());
         assert_eq!(a.len(), expected_len);
-        a = format_strbuf!("{}{}", a, a);
+        a = format!("{}{}", a, a);
         i -= 1;
         expected_len *= 2u;
     }
index 7f0f857090fca66795dac068bde17fa8ab784333..454cf4c8eda21294b382ddd8089c181e6391ba3a 100644 (file)
@@ -29,7 +29,7 @@ impl<T:to_str> to_str for Option<T> {
     fn to_str_(&self) -> String {
         match *self {
           None => { "none".to_string() }
-          Some(ref t) => format_strbuf!("some({})", t.to_str_()),
+          Some(ref t) => format!("some({})", t.to_str_()),
         }
     }
 }
@@ -46,10 +46,7 @@ fn to_str_(&self) -> String {
         let this = t.borrow();
         let (l, r) = (this.left, this.right);
         let val = &this.val;
-        format_strbuf!("[{}, {}, {}]",
-                       val.to_str_(),
-                       l.to_str_(),
-                       r.to_str_())
+        format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
     }
 }
 
index 7fe5b327f2f88216d1bcd7a3f743c58f14f1890e..ea5e0a9ee910b7698e6c80ffbca72356d362aab6 100644 (file)
@@ -20,11 +20,11 @@ fn to_string(&self) -> String { self.to_str().to_string() }
 
 impl<T:to_str> to_str for Vec<T> {
     fn to_string(&self) -> String {
-        format_strbuf!("[{}]",
-                       self.iter()
-                           .map(|e| e.to_string())
-                           .collect::<Vec<String>>()
-                           .connect(", "))
+        format!("[{}]",
+                self.iter()
+                    .map(|e| e.to_string())
+                    .collect::<Vec<String>>()
+                    .connect(", "))
     }
 }
 
@@ -33,7 +33,7 @@ pub fn main() {
     assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_string());
 
     fn indirect<T:to_str>(x: T) -> String {
-        format_strbuf!("{}!", x.to_string())
+        format!("{}!", x.to_string())
     }
     assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_string());
 
index 8b0d8533c56406a0192dcbcbacdfa35f39c82ef9..29fc2fd5a7a021d2ec1baeb627005f6e54ccb6e0 100644 (file)
@@ -11,7 +11,7 @@
 
 trait Foo {
     fn bar(&self) -> String {
-        format_strbuf!("test")
+        format!("test")
     }
 }
 
index 00bc95b36f7a70b2b1f14771d12792eac16bd622..e5f1c48464de34030e60b65ff1c3489e21013981 100644 (file)
@@ -8,10 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-extern crate rand;
-
 use std::task;
-use rand::{task_rng, Rng};
+use std::rand::{task_rng, Rng};
 
 static MAX_LEN: uint = 20;
 static mut drop_counts: [uint, .. MAX_LEN] = [0, .. MAX_LEN];
@@ -46,7 +44,9 @@ pub fn main() {
     // len can't go above 64.
     for len in range(2u, MAX_LEN) {
         for _ in range(0, 10) {
-            let main = task_rng().gen_vec::<DropCounter>(len);
+            let main = task_rng().gen_iter::<DropCounter>()
+                                 .take(len)
+                                 .collect::<Vec<DropCounter>>();
 
             // work out the total number of comparisons required to sort
             // this array...