diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index d02b88ae74e..4ae9ad81daf 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -21,7 +21,10 @@ use util; use util::logv; use std::cell::Cell; -use std::io; +use std::rt::io; +use std::rt::io::Writer; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; use std::os; use std::str; use std::task::{spawn_sched, SingleThreaded}; @@ -60,7 +63,7 @@ pub fn run(config: config, testfile: ~str) { pub fn run_metrics(config: config, testfile: ~str, mm: &mut MetricMap) { if config.verbose { // We're going to be dumping a lot of info. Start on a new line. - io::stdout().write_str("\n\n"); + print!("\n\n"); } let testfile = Path::new(testfile); debug!("running {}", testfile.display()); @@ -170,7 +173,9 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) { let rounds = match props.pp_exact { Some(_) => 1, None => 2 }; - let mut srcs = ~[io::read_whole_file_str(testfile).unwrap()]; + let src = testfile.open_reader(io::Open).read_to_end(); + let src = str::from_utf8_owned(src); + let mut srcs = ~[src]; let mut round = 0; while round < rounds { @@ -190,7 +195,8 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) { let mut expected = match props.pp_exact { Some(ref file) => { let filepath = testfile.dir_path().join(file); - io::read_whole_file_str(&filepath).unwrap() + let s = filepath.open_reader(io::Open).read_to_end(); + str::from_utf8_owned(s) } None => { srcs[srcs.len() - 2u].clone() } }; @@ -228,8 +234,7 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) { fn compare_source(expected: &str, actual: &str) { if expected != actual { error(~"pretty-printed source does not match expected source"); - let msg = - format!("\n\ + println!("\n\ expected:\n\ ------------------------------------------\n\ {}\n\ @@ -240,7 +245,6 @@ actual:\n\ ------------------------------------------\n\ \n", expected, actual); - io::stdout().write_str(msg); fail!(); } } @@ -741,9 +745,7 @@ fn dump_output(config: &config, testfile: &Path, out: &str, err: &str) { fn dump_output_file(config: &config, testfile: &Path, out: &str, extension: &str) { let outfile = make_out_name(config, testfile, extension); - let writer = - io::file_writer(&outfile, [io::Create, io::Truncate]).unwrap(); - writer.write_str(out); + outfile.open_writer(io::CreateOrTruncate).write(out.as_bytes()); } fn make_out_name(config: &config, testfile: &Path, extension: &str) -> Path { @@ -771,24 +773,20 @@ fn output_base_name(config: &config, testfile: &Path) -> Path { fn maybe_dump_to_stdout(config: &config, out: &str, err: &str) { if config.verbose { - let sep1 = format!("------{}------------------------------", "stdout"); - let sep2 = format!("------{}------------------------------", "stderr"); - let sep3 = ~"------------------------------------------"; - io::stdout().write_line(sep1); - io::stdout().write_line(out); - io::stdout().write_line(sep2); - io::stdout().write_line(err); - io::stdout().write_line(sep3); + println!("------{}------------------------------", "stdout"); + println!("{}", out); + println!("------{}------------------------------", "stderr"); + println!("{}", err); + println!("------------------------------------------"); } } -fn error(err: ~str) { io::stdout().write_line(format!("\nerror: {}", err)); } +fn error(err: ~str) { println!("\nerror: {}", err); } fn fatal(err: ~str) -> ! { error(err); fail!(); } fn fatal_ProcRes(err: ~str, ProcRes: &ProcRes) -> ! { - let msg = - format!("\n\ + print!("\n\ error: {}\n\ command: {}\n\ stdout:\n\ @@ -801,7 +799,6 @@ stderr:\n\ ------------------------------------------\n\ \n", err, ProcRes.cmdline, ProcRes.stdout, ProcRes.stderr); - io::stdout().write_str(msg); fail!(); } @@ -821,9 +818,9 @@ fn _arm_exec_compiled_test(config: &config, props: &TestProps, ~[(~"",~"")], Some(~"")); if config.verbose { - io::stdout().write_str(format!("push ({}) {} {} {}", + println!("push ({}) {} {} {}", config.target, args.prog, - copy_result.out, copy_result.err)); + copy_result.out, copy_result.err); } logv(config, format!("executing ({}) {}", config.target, cmdline)); @@ -913,9 +910,9 @@ fn _arm_push_aux_shared_library(config: &config, testfile: &Path) { ~[(~"",~"")], Some(~"")); if config.verbose { - io::stdout().write_str(format!("push ({}) {} {} {}", + println!("push ({}) {} {} {}", config.target, file.display(), - copy_result.out, copy_result.err)); + copy_result.out, copy_result.err); } } } @@ -999,7 +996,8 @@ fn disassemble_extract(config: &config, _props: &TestProps, fn count_extracted_lines(p: &Path) -> uint { - let x = io::read_whole_file_str(&p.with_extension("ll")).unwrap(); + let x = p.with_extension("ll").open_reader(io::Open).read_to_end(); + let x = str::from_utf8_owned(x); x.line_iter().len() } diff --git a/src/compiletest/util.rs b/src/compiletest/util.rs index 04ef180299d..ae4a25b8008 100644 --- a/src/compiletest/util.rs +++ b/src/compiletest/util.rs @@ -10,7 +10,6 @@ use common::config; -use std::io; use std::os::getenv; /// Conversion table from triple OS name to Rust SYSNAME @@ -64,5 +63,5 @@ pub fn path_div() -> ~str { ~";" } pub fn logv(config: &config, s: ~str) { debug!("{}", s); - if config.verbose { io::println(s); } + if config.verbose { println(s); } } diff --git a/src/etc/combine-tests.py b/src/etc/combine-tests.py index 25976410c7c..dc5e11dabdf 100755 --- a/src/etc/combine-tests.py +++ b/src/etc/combine-tests.py @@ -56,15 +56,15 @@ d.write("#[feature(globs, managed_boxes)];\n") d.write("extern mod extra;\n") d.write("extern mod run_pass_stage2;\n") d.write("use run_pass_stage2::*;\n") -d.write("use std::io::WriterUtil;\n"); -d.write("use std::io;\n"); +d.write("use std::rt::io;\n"); +d.write("use std::rt::io::Writer;\n"); d.write("fn main() {\n"); -d.write(" let out = io::stdout();\n"); +d.write(" let mut out = io::stdout();\n"); i = 0 for t in stage2_tests: p = os.path.join("test", "run-pass", t) p = p.replace("\\", "\\\\") - d.write(" out.write_str(\"run-pass [stage2]: %s\\n\");\n" % p) + d.write(" out.write(\"run-pass [stage2]: %s\\n\".as_bytes());\n" % p) d.write(" t_%d::main();\n" % i) i += 1 d.write("}\n") diff --git a/src/libextra/extra.rs b/src/libextra/extra.rs index 79a5b555c29..3ea164fb456 100644 --- a/src/libextra/extra.rs +++ b/src/libextra/extra.rs @@ -45,7 +45,6 @@ pub use std::os; // Utility modules pub mod c_vec; -pub mod io_util; // Concurrency @@ -104,7 +103,6 @@ pub mod rational; pub mod complex; pub mod stats; pub mod semver; -pub mod fileinput; pub mod flate; pub mod hex; pub mod uuid; diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs deleted file mode 100644 index 49072dab6d0..00000000000 --- a/src/libextra/fileinput.rs +++ /dev/null @@ -1,629 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -A library for iterating through the lines in a series of -files. Very similar to [the Python module of the same -name](http://docs.python.org/3.3/library/fileinput.html). - -It allows the programmer to automatically take filenames from the -command line arguments (via `input` and `input_state`), as well as -specify them as a vector directly (`input_vec` and -`input_vec_state`). The files are opened as necessary, so any files -that can't be opened only cause an error when reached in the -iteration. - -On the command line, `stdin` is represented by a filename of `-` (a -single hyphen) and in the functions that take a vector directly -(e.g. `input_vec`) it is represented by `None`. Note `stdin` is *not* -reset once it has been finished, so attempting to iterate on `[None, -None]` will only take input once unless `io::stdin().seek(0, SeekSet)` -is called between. - -The `make_path_option_vec` function handles converting a list of file paths as -strings to the appropriate format, including the (optional) conversion -of `"-"` to `stdin`. - -# Basic - -In many cases, one can use the `input_*` functions without having -to handle any `FileInput` structs. E.g. a simple `cat` program - - for input |line| { - io::println(line) - } - -or a program that numbers lines after concatenating two files - - for input_vec_state(make_path_option_vec([~"a.txt", ~"b.txt"])) |line, state| { - io::println(format!("{}: %s", state.line_num, - line)); - } - -The two `input_vec*` functions take a vec of file names (where empty -means read from `stdin`), the other two functions use the command line -arguments. - -# Advanced - -For more complicated uses (e.g. if one needs to pause iteration and -resume it later), a `FileInput` instance can be constructed via the -`from_vec`, `from_vec_raw` and `from_args` functions. - -Once created, the `each_line` (from the `std::io::ReaderUtil` trait) -and `each_line_state` methods allow one to iterate on the lines; the -latter provides more information about the position within the -iteration to the caller. - -It is possible (and safe) to skip lines and files using the -`read_line` and `next_file` methods. Also, `FileInput` implements -`std::io::Reader`, and the state will be updated correctly while -using any of those methods. - -E.g. the following program reads until an empty line, pauses for user -input, skips the current file and then numbers the remaining lines -(where the numbers are from the start of each file, rather than the -total line count). - - let input = FileInput::from_vec(pathify([~"a.txt", ~"b.txt", ~"c.txt"], - true)); - - for input.each_line |line| { - if line.is_empty() { - break - } - io::println(line); - } - - io::println("Continue?"); - - if io::stdin().read_line() == ~"yes" { - input.next_file(); // skip! - - for input.each_line_state |line, state| { - io::println(format!("{}: %s", state.line_num_file, - line)) - } - } -*/ - -#[allow(missing_doc)]; - - -use std::io::ReaderUtil; -use std::io; -use std::os; - -/** -A summary of the internal state of a `FileInput` object. `line_num` -and `line_num_file` represent the number of lines read in total and in -the current file respectively. `current_path` is `None` if the current -file is `stdin`. -*/ -#[deriving(Clone)] -pub struct FileInputState { - current_path: Option, - line_num: uint, - line_num_file: uint -} - -impl FileInputState { - fn is_stdin(&self) -> bool { - self.current_path.is_none() - } - - fn is_first_line(&self) -> bool { - self.line_num_file == 1 - } -} - -struct FileInput_ { - /** - `Some(path)` is the file represented by `path`, `None` is - `stdin`. Consumed as the files are read. - */ - files: ~[Option], - /** - The current file: `Some(r)` for an open file, `None` before - starting and after reading everything. - */ - current_reader: Option<@io::Reader>, - state: FileInputState, - - /** - Used to keep track of whether we need to insert the newline at the - end of a file that is missing it, which is needed to separate the - last and first lines. - */ - previous_was_newline: bool -} - - -// FIXME #5723: remove this when Reader has &mut self. -// Removing it would mean giving read_byte in the Reader impl for -// FileInput &mut self, which in turn means giving most of the -// io::Reader trait methods &mut self. That can't be done right now -// because of io::with_bytes_reader and #5723. -// Should be removable via -// "self.fi" -> "self." and renaming FileInput_. Documentation above -// will likely have to be updated to use `let mut in = ...`. -pub struct FileInput { - priv fi: @mut FileInput_ -} - -impl FileInput { - /** - Create a `FileInput` object from a vec of files. An empty - vec means lines are read from `stdin` (use `from_vec_raw` to stop - this behaviour). Any occurrence of `None` represents `stdin`. - */ - pub fn from_vec(files: ~[Option]) -> FileInput { - FileInput::from_vec_raw( - if files.is_empty() { - ~[None] - } else { - files - }) - } - - /** - Identical to `from_vec`, but an empty `files` vec stays - empty. (`None` is `stdin`.) - */ - pub fn from_vec_raw(files: ~[Option]) - -> FileInput { - FileInput{ - fi: @mut FileInput_ { - files: files, - current_reader: None, - state: FileInputState { - current_path: None, - line_num: 0, - line_num_file: 0 - }, - // there was no previous unended line - previous_was_newline: true - } - } - } - - /** - Create a `FileInput` object from the command line - arguments. `"-"` represents `stdin`. - */ - pub fn from_args() -> FileInput { - let args = os::args(); - let pathed = make_path_option_vec(args.tail(), true); - FileInput::from_vec(pathed) - } - - fn current_file_eof(&self) -> bool { - match self.fi.current_reader { - None => false, - Some(r) => r.eof() - } - } - - /** - Skip to the next file in the queue. Can `fail` when opening - a file. - - Returns `false` if there is no more files, and `true` when it - successfully opens the next file. - */ - - pub fn next_file(&self) -> bool { - // No more files - - if self.fi.files.is_empty() { - self.fi.current_reader = None; - return false; - } - - let path_option = self.fi.files.shift(); - let file = match path_option { - None => io::stdin(), - Some(ref path) => io::file_reader(path).unwrap() - }; - - self.fi.current_reader = Some(file); - self.fi.state.current_path = path_option; - self.fi.state.line_num_file = 0; - true - } - - /** - Attempt to open the next file if there is none currently open, - or if the current one is EOF'd. - - Returns `true` if it had to move to the next file and did - so successfully. - */ - fn next_file_if_eof(&self) -> bool { - match self.fi.current_reader { - None => self.next_file(), - Some(r) => { - if r.eof() { - self.next_file() - } else { - false - } - } - } - } - - /** - Apply `f` to each line successively, along with some state - (line numbers and file names, see documentation for - `FileInputState`). Otherwise identical to `lines_each`. - */ - pub fn each_line_state(&self, - f: &fn(&str, FileInputState) -> bool) -> bool { - self.each_line(|line| f(line, self.fi.state.clone())) - } - - - /** - Retrieve the current `FileInputState` information. - */ - pub fn state(&self) -> FileInputState { - self.fi.state.clone() - } -} - -impl io::Reader for FileInput { - fn read_byte(&self) -> int { - loop { - let stepped = self.next_file_if_eof(); - - // if we moved to the next file, and the previous - // character wasn't \n, then there is an unfinished line - // from the previous file. This library models - // line-by-line processing and the trailing line of the - // previous file and the leading of the current file - // should be considered different, so we need to insert a - // fake line separator - if stepped && !self.fi.previous_was_newline { - self.fi.state.line_num += 1; - self.fi.state.line_num_file += 1; - self.fi.previous_was_newline = true; - return '\n' as int; - } - - match self.fi.current_reader { - None => return -1, - Some(r) => { - let b = r.read_byte(); - - if b < 0 { - continue; - } - - if b == '\n' as int { - self.fi.state.line_num += 1; - self.fi.state.line_num_file += 1; - self.fi.previous_was_newline = true; - } else { - self.fi.previous_was_newline = false; - } - - return b; - } - } - } - } - fn read(&self, buf: &mut [u8], len: uint) -> uint { - let mut count = 0; - while count < len { - let b = self.read_byte(); - if b < 0 { break } - - buf[count] = b as u8; - count += 1; - } - - count - } - fn eof(&self) -> bool { - // we've run out of files, and current_reader is either None or eof. - - self.fi.files.is_empty() && - match self.fi.current_reader { None => true, Some(r) => r.eof() } - - } - fn seek(&self, offset: int, whence: io::SeekStyle) { - match self.fi.current_reader { - None => {}, - Some(r) => r.seek(offset, whence) - } - } - fn tell(&self) -> uint { - match self.fi.current_reader { - None => 0, - Some(r) => r.tell() - } - } -} - -/** -Convert a list of strings to an appropriate form for a `FileInput` -instance. `stdin_hyphen` controls whether `-` represents `stdin` or -a literal `-`. -*/ -pub fn make_path_option_vec(vec: &[~str], stdin_hyphen : bool) -> ~[Option] { - vec.iter().map(|s| { - if stdin_hyphen && "-" == *s { - None - } else { - Some(Path::new(s.as_slice())) - } - }).collect() -} - -/** -Iterate directly over the command line arguments (no arguments implies -reading from `stdin`). - -Fails when attempting to read from a file that can't be opened. -*/ -pub fn input(f: &fn(&str) -> bool) -> bool { - let i = FileInput::from_args(); - i.each_line(f) -} - -/** -Iterate directly over the command line arguments (no arguments -implies reading from `stdin`) with the current state of the iteration -provided at each call. - -Fails when attempting to read from a file that can't be opened. -*/ -pub fn input_state(f: &fn(&str, FileInputState) -> bool) -> bool { - let i = FileInput::from_args(); - i.each_line_state(f) -} - -/** -Iterate over a vector of files (an empty vector implies just `stdin`). - -Fails when attempting to read from a file that can't be opened. -*/ -pub fn input_vec(files: ~[Option], f: &fn(&str) -> bool) -> bool { - let i = FileInput::from_vec(files); - i.each_line(f) -} - -/** -Iterate over a vector of files (an empty vector implies just `stdin`) -with the current state of the iteration provided at each call. - -Fails when attempting to read from a file that can't be opened. -*/ -pub fn input_vec_state(files: ~[Option], - f: &fn(&str, FileInputState) -> bool) -> bool { - let i = FileInput::from_vec(files); - i.each_line_state(f) -} - -#[cfg(test)] -mod test { - - use super::{FileInput, make_path_option_vec, input_vec, input_vec_state}; - - use std::rt::io; - use std::rt::io::Writer; - use std::rt::io::file; - use std::vec; - - fn make_file(path : &Path, contents: &[~str]) { - let mut file = file::open(path, io::CreateOrTruncate, io::Write).unwrap(); - - for str in contents.iter() { - file.write(str.as_bytes()); - file.write(['\n' as u8]); - } - } - - #[test] - fn test_make_path_option_vec() { - let strs = [~"some/path", - ~"some/other/path"]; - let paths = ~[Some(Path::new("some/path")), - Some(Path::new("some/other/path"))]; - - assert_eq!(make_path_option_vec(strs, true), paths.clone()); - assert_eq!(make_path_option_vec(strs, false), paths); - - assert_eq!(make_path_option_vec([~"-"], true), ~[None]); - assert_eq!(make_path_option_vec([~"-"], false), ~[Some(Path::new("-"))]); - } - - #[test] - fn test_fileinput_read_byte() { - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-fileinput-read-byte-{}.tmp", i)), true); - - // 3 files containing 0\n, 1\n, and 2\n respectively - for (i, filename) in filenames.iter().enumerate() { - make_file(filename.get_ref(), [format!("{}", i)]); - } - - let fi = FileInput::from_vec(filenames.clone()); - - for (line, c) in "012".iter().enumerate() { - assert_eq!(fi.read_byte(), c as int); - assert_eq!(fi.state().line_num, line); - assert_eq!(fi.state().line_num_file, 0); - assert_eq!(fi.read_byte(), '\n' as int); - assert_eq!(fi.state().line_num, line + 1); - assert_eq!(fi.state().line_num_file, 1); - - assert_eq!(fi.state().current_path.clone(), filenames[line].clone()); - } - - assert_eq!(fi.read_byte(), -1); - assert!(fi.eof()); - assert_eq!(fi.state().line_num, 3) - - } - - #[test] - fn test_fileinput_read() { - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-fileinput-read-{}.tmp", i)), true); - - // 3 files containing 1\n, 2\n, and 3\n respectively - for (i, filename) in filenames.iter().enumerate() { - make_file(filename.get_ref(), [format!("{}", i)]); - } - - let fi = FileInput::from_vec(filenames); - let mut buf : ~[u8] = vec::from_elem(6, 0u8); - let count = fi.read(buf, 10); - assert_eq!(count, 6); - assert_eq!(buf, "0\n1\n2\n".as_bytes().to_owned()); - assert!(fi.eof()) - assert_eq!(fi.state().line_num, 3); - } - - #[test] - fn test_input_vec() { - let mut all_lines = ~[]; - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-input-vec-{}.tmp", i)), true); - - for (i, filename) in filenames.iter().enumerate() { - let contents = - vec::from_fn(3, |j| format!("{} {}", i, j)); - make_file(filename.get_ref(), contents); - debug!("contents={:?}", contents); - all_lines.push_all(contents); - } - - let mut read_lines = ~[]; - do input_vec(filenames) |line| { - read_lines.push(line.to_owned()); - true - }; - assert_eq!(read_lines, all_lines); - } - - #[test] - fn test_input_vec_state() { - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-input-vec-state-{}.tmp", i)),true); - - for (i, filename) in filenames.iter().enumerate() { - let contents = - vec::from_fn(3, |j| format!("{} {}", i, j + 1)); - make_file(filename.get_ref(), contents); - } - - do input_vec_state(filenames) |line, state| { - let nums: ~[&str] = line.split_iter(' ').collect(); - let file_num = from_str::(nums[0]).unwrap(); - let line_num = from_str::(nums[1]).unwrap(); - assert_eq!(line_num, state.line_num_file); - assert_eq!(file_num * 3 + line_num, state.line_num); - true - }; - } - - #[test] - fn test_empty_files() { - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-empty-files-{}.tmp", i)),true); - - make_file(filenames[0].get_ref(), [~"1", ~"2"]); - make_file(filenames[1].get_ref(), []); - make_file(filenames[2].get_ref(), [~"3", ~"4"]); - - let mut count = 0; - do input_vec_state(filenames.clone()) |line, state| { - let expected_path = match line { - "1" | "2" => filenames[0].clone(), - "3" | "4" => filenames[2].clone(), - _ => fail!("unexpected line") - }; - assert_eq!(state.current_path.clone(), expected_path); - count += 1; - true - }; - assert_eq!(count, 4); - } - - #[test] - fn test_no_trailing_newline() { - let f1 = - Some(Path::new("tmp/lib-fileinput-test-no-trailing-newline-1.tmp")); - let f2 = - Some(Path::new("tmp/lib-fileinput-test-no-trailing-newline-2.tmp")); - - { - let mut wr = file::open(f1.get_ref(), io::CreateOrTruncate, - io::Write).unwrap(); - wr.write("1\n2".as_bytes()); - let mut wr = file::open(f2.get_ref(), io::CreateOrTruncate, - io::Write).unwrap(); - wr.write("3\n4".as_bytes()); - } - - let mut lines = ~[]; - do input_vec(~[f1, f2]) |line| { - lines.push(line.to_owned()); - true - }; - assert_eq!(lines, ~[~"1", ~"2", ~"3", ~"4"]); - } - - - #[test] - fn test_next_file() { - let filenames = make_path_option_vec(vec::from_fn( - 3, - |i| format!("tmp/lib-fileinput-test-next-file-{}.tmp", i)),true); - - for (i, filename) in filenames.iter().enumerate() { - let contents = vec::from_fn(3, |j| format!("{} {}", i, j + 1)); - make_file(filename.get_ref(), contents); - } - - let input = FileInput::from_vec(filenames); - - // read once from 0 - assert_eq!(input.read_line(), ~"0 1"); - input.next_file(); // skip the rest of 1 - - // read all lines from 1 (but don't read any from 2), - for i in range(1u, 4) { - assert_eq!(input.read_line(), format!("1 {}", i)); - } - // 1 is finished, but 2 hasn't been started yet, so this will - // just "skip" to the beginning of 2 (Python's fileinput does - // the same) - input.next_file(); - - assert_eq!(input.read_line(), ~"2 1"); - } - - #[test] - #[should_fail] - fn test_input_vec_missing_file() { - do input_vec(make_path_option_vec([~"this/file/doesnt/exist"], true)) |line| { - println(line); - true - }; - } -} diff --git a/src/libextra/io_util.rs b/src/libextra/io_util.rs deleted file mode 100644 index 27a09be3a62..00000000000 --- a/src/libextra/io_util.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[allow(missing_doc)]; - -use std::io::{Reader, BytesReader}; -use std::io; -use std::cast; - -/// An implementation of the io::Reader interface which reads a buffer of bytes -pub struct BufReader { - /// The buffer of bytes to read - priv buf: ~[u8], - /// The current position in the buffer of bytes - priv pos: @mut uint -} - -impl BufReader { - /// Creates a new buffer reader for the specified buffer - pub fn new(v: ~[u8]) -> BufReader { - BufReader { - buf: v, - pos: @mut 0 - } - } - - fn as_bytes_reader(&self, f: &fn(&BytesReader) -> A) -> A { - // FIXME(#5723) - let bytes = ::std::util::id::<&[u8]>(self.buf); - let bytes: &'static [u8] = unsafe { cast::transmute(bytes) }; - // Recreating the BytesReader state every call since - // I can't get the borrowing to work correctly - let bytes_reader = BytesReader { - bytes: bytes, - pos: @mut *self.pos - }; - - let res = f(&bytes_reader); - - // FIXME #4429: This isn't correct if f fails - *self.pos = *bytes_reader.pos; - - return res; - } -} - -impl Reader for BufReader { - fn read(&self, bytes: &mut [u8], len: uint) -> uint { - self.as_bytes_reader(|r| r.read(bytes, len) ) - } - fn read_byte(&self) -> int { - self.as_bytes_reader(|r| r.read_byte() ) - } - fn eof(&self) -> bool { - self.as_bytes_reader(|r| r.eof() ) - } - fn seek(&self, offset: int, whence: io::SeekStyle) { - self.as_bytes_reader(|r| r.seek(offset, whence) ) - } - fn tell(&self) -> uint { - self.as_bytes_reader(|r| r.tell() ) - } -} diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 90260282e4b..0aab7b743ba 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -20,8 +20,10 @@ use std::char; use std::cast::transmute; use std::f64; use std::hashmap::HashMap; -use std::io::WriterUtil; -use std::io; +use std::rt::io; +use std::rt::io::Decorator; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::mem::MemWriter; use std::num; use std::str; use std::to_str; @@ -86,19 +88,17 @@ fn spaces(n: uint) -> ~str { /// A structure for implementing serialization to JSON. pub struct Encoder { - priv wr: @io::Writer, + priv wr: @mut io::Writer, } /// Creates a new JSON encoder whose output will be written to the writer /// specified. -pub fn Encoder(wr: @io::Writer) -> Encoder { - Encoder { - wr: wr - } +pub fn Encoder(wr: @mut io::Writer) -> Encoder { + Encoder { wr: wr } } impl serialize::Encoder for Encoder { - fn emit_nil(&mut self) { self.wr.write_str("null") } + fn emit_nil(&mut self) { write!(self.wr, "null") } fn emit_uint(&mut self, v: uint) { self.emit_f64(v as f64); } fn emit_u64(&mut self, v: u64) { self.emit_f64(v as f64); } @@ -114,17 +114,21 @@ impl serialize::Encoder for Encoder { fn emit_bool(&mut self, v: bool) { if v { - self.wr.write_str("true"); + write!(self.wr, "true"); } else { - self.wr.write_str("false"); + write!(self.wr, "false"); } } - fn emit_f64(&mut self, v: f64) { self.wr.write_str(f64::to_str_digits(v, 6u)) } + fn emit_f64(&mut self, v: f64) { + write!(self.wr, "{}", f64::to_str_digits(v, 6u)) + } fn emit_f32(&mut self, v: f32) { self.emit_f64(v as f64); } fn emit_char(&mut self, v: char) { self.emit_str(str::from_char(v)) } - fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)) } + fn emit_str(&mut self, v: &str) { + write!(self.wr, "{}", escape_str(v)) + } fn emit_enum(&mut self, _name: &str, f: &fn(&mut Encoder)) { f(self) } @@ -137,23 +141,19 @@ impl serialize::Encoder for Encoder { // Bunny => "Bunny" // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]} if cnt == 0 { - self.wr.write_str(escape_str(name)); + write!(self.wr, "{}", escape_str(name)); } else { - self.wr.write_char('{'); - self.wr.write_str("\"variant\""); - self.wr.write_char(':'); - self.wr.write_str(escape_str(name)); - self.wr.write_char(','); - self.wr.write_str("\"fields\""); - self.wr.write_str(":["); + write!(self.wr, "\\{\"variant\":"); + write!(self.wr, "{}", escape_str(name)); + write!(self.wr, ",\"fields\":["); f(self); - self.wr.write_str("]}"); + write!(self.wr, "]\\}"); } } fn emit_enum_variant_arg(&mut self, idx: uint, f: &fn(&mut Encoder)) { if idx != 0 { - self.wr.write_char(','); + write!(self.wr, ","); } f(self); } @@ -174,18 +174,17 @@ impl serialize::Encoder for Encoder { } fn emit_struct(&mut self, _: &str, _: uint, f: &fn(&mut Encoder)) { - self.wr.write_char('{'); + write!(self.wr, r"\{"); f(self); - self.wr.write_char('}'); + write!(self.wr, r"\}"); } fn emit_struct_field(&mut self, name: &str, idx: uint, f: &fn(&mut Encoder)) { - if idx != 0 { self.wr.write_char(','); } - self.wr.write_str(escape_str(name)); - self.wr.write_char(':'); + if idx != 0 { write!(self.wr, ",") } + write!(self.wr, "{}:", escape_str(name)); f(self); } @@ -211,31 +210,31 @@ impl serialize::Encoder for Encoder { fn emit_option_some(&mut self, f: &fn(&mut Encoder)) { f(self); } fn emit_seq(&mut self, _len: uint, f: &fn(&mut Encoder)) { - self.wr.write_char('['); + write!(self.wr, "["); f(self); - self.wr.write_char(']'); + write!(self.wr, "]"); } fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut Encoder)) { if idx != 0 { - self.wr.write_char(','); + write!(self.wr, ","); } f(self) } fn emit_map(&mut self, _len: uint, f: &fn(&mut Encoder)) { - self.wr.write_char('{'); + write!(self.wr, r"\{"); f(self); - self.wr.write_char('}'); + write!(self.wr, r"\}"); } fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut Encoder)) { - if idx != 0 { self.wr.write_char(','); } + if idx != 0 { write!(self.wr, ",") } f(self) } fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut Encoder)) { - self.wr.write_char(':'); + write!(self.wr, ":"); f(self) } } @@ -243,12 +242,12 @@ impl serialize::Encoder for Encoder { /// Another encoder for JSON, but prints out human-readable JSON instead of /// compact data pub struct PrettyEncoder { - priv wr: @io::Writer, + priv wr: @mut io::Writer, priv indent: uint, } /// Creates a new encoder whose output will be written to the specified writer -pub fn PrettyEncoder(wr: @io::Writer) -> PrettyEncoder { +pub fn PrettyEncoder(wr: @mut io::Writer) -> PrettyEncoder { PrettyEncoder { wr: wr, indent: 0, @@ -256,7 +255,7 @@ pub fn PrettyEncoder(wr: @io::Writer) -> PrettyEncoder { } impl serialize::Encoder for PrettyEncoder { - fn emit_nil(&mut self) { self.wr.write_str("null") } + fn emit_nil(&mut self) { write!(self.wr, "null") } fn emit_uint(&mut self, v: uint) { self.emit_f64(v as f64); } fn emit_u64(&mut self, v: u64) { self.emit_f64(v as f64); } @@ -272,17 +271,19 @@ impl serialize::Encoder for PrettyEncoder { fn emit_bool(&mut self, v: bool) { if v { - self.wr.write_str("true"); + write!(self.wr, "true"); } else { - self.wr.write_str("false"); + write!(self.wr, "false"); } } - fn emit_f64(&mut self, v: f64) { self.wr.write_str(f64::to_str_digits(v, 6u)) } + fn emit_f64(&mut self, v: f64) { + write!(self.wr, "{}", f64::to_str_digits(v, 6u)) + } fn emit_f32(&mut self, v: f32) { self.emit_f64(v as f64); } fn emit_char(&mut self, v: char) { self.emit_str(str::from_char(v)) } - fn emit_str(&mut self, v: &str) { self.wr.write_str(escape_str(v)); } + fn emit_str(&mut self, v: &str) { write!(self.wr, "{}", escape_str(v)); } fn emit_enum(&mut self, _name: &str, f: &fn(&mut PrettyEncoder)) { f(self) @@ -294,19 +295,13 @@ impl serialize::Encoder for PrettyEncoder { cnt: uint, f: &fn(&mut PrettyEncoder)) { if cnt == 0 { - self.wr.write_str(escape_str(name)); + write!(self.wr, "{}", escape_str(name)); } else { - self.wr.write_char('['); self.indent += 2; - self.wr.write_char('\n'); - self.wr.write_str(spaces(self.indent)); - self.wr.write_str(escape_str(name)); - self.wr.write_str(",\n"); + write!(self.wr, "[\n{}{},\n", spaces(self.indent), escape_str(name)); f(self); - self.wr.write_char('\n'); self.indent -= 2; - self.wr.write_str(spaces(self.indent)); - self.wr.write_char(']'); + write!(self.wr, "\n{}]", spaces(self.indent)); } } @@ -314,9 +309,9 @@ impl serialize::Encoder for PrettyEncoder { idx: uint, f: &fn(&mut PrettyEncoder)) { if idx != 0 { - self.wr.write_str(",\n"); + write!(self.wr, ",\n"); } - self.wr.write_str(spaces(self.indent)); + write!(self.wr, "{}", spaces(self.indent)); f(self) } @@ -341,15 +336,13 @@ impl serialize::Encoder for PrettyEncoder { len: uint, f: &fn(&mut PrettyEncoder)) { if len == 0 { - self.wr.write_str("{}"); + write!(self.wr, "\\{\\}"); } else { - self.wr.write_char('{'); + write!(self.wr, "\\{"); self.indent += 2; f(self); - self.wr.write_char('\n'); self.indent -= 2; - self.wr.write_str(spaces(self.indent)); - self.wr.write_char('}'); + write!(self.wr, "\n{}\\}", spaces(self.indent)); } } @@ -358,13 +351,11 @@ impl serialize::Encoder for PrettyEncoder { idx: uint, f: &fn(&mut PrettyEncoder)) { if idx == 0 { - self.wr.write_char('\n'); + write!(self.wr, "\n"); } else { - self.wr.write_str(",\n"); + write!(self.wr, ",\n"); } - self.wr.write_str(spaces(self.indent)); - self.wr.write_str(escape_str(name)); - self.wr.write_str(": "); + write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)); f(self); } @@ -393,54 +384,50 @@ impl serialize::Encoder for PrettyEncoder { fn emit_seq(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) { if len == 0 { - self.wr.write_str("[]"); + write!(self.wr, "[]"); } else { - self.wr.write_char('['); + write!(self.wr, "["); self.indent += 2; f(self); - self.wr.write_char('\n'); self.indent -= 2; - self.wr.write_str(spaces(self.indent)); - self.wr.write_char(']'); + write!(self.wr, "\n{}]", spaces(self.indent)); } } fn emit_seq_elt(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) { if idx == 0 { - self.wr.write_char('\n'); + write!(self.wr, "\n"); } else { - self.wr.write_str(",\n"); + write!(self.wr, ",\n"); } - self.wr.write_str(spaces(self.indent)); + write!(self.wr, "{}", spaces(self.indent)); f(self) } fn emit_map(&mut self, len: uint, f: &fn(&mut PrettyEncoder)) { if len == 0 { - self.wr.write_str("{}"); + write!(self.wr, "\\{\\}"); } else { - self.wr.write_char('{'); + write!(self.wr, "\\{"); self.indent += 2; f(self); - self.wr.write_char('\n'); self.indent -= 2; - self.wr.write_str(spaces(self.indent)); - self.wr.write_char('}'); + write!(self.wr, "\n{}\\}", spaces(self.indent)); } } fn emit_map_elt_key(&mut self, idx: uint, f: &fn(&mut PrettyEncoder)) { if idx == 0 { - self.wr.write_char('\n'); + write!(self.wr, "\n"); } else { - self.wr.write_str(",\n"); + write!(self.wr, ",\n"); } - self.wr.write_str(spaces(self.indent)); + write!(self.wr, "{}", spaces(self.indent)); f(self); } fn emit_map_elt_val(&mut self, _idx: uint, f: &fn(&mut PrettyEncoder)) { - self.wr.write_str(": "); + write!(self.wr, ": "); f(self); } } @@ -460,21 +447,23 @@ impl serialize::Encodable for Json { impl Json{ /// Encodes a json value into a io::writer. Uses a single line. - pub fn to_writer(&self, wr: @io::Writer) { + pub fn to_writer(&self, wr: @mut io::Writer) { let mut encoder = Encoder(wr); self.encode(&mut encoder) } /// Encodes a json value into a io::writer. /// Pretty-prints in a more readable format. - pub fn to_pretty_writer(&self, wr: @io::Writer) { + pub fn to_pretty_writer(&self, wr: @mut io::Writer) { let mut encoder = PrettyEncoder(wr); self.encode(&mut encoder) } /// Encodes a json value into a string pub fn to_pretty_str(&self) -> ~str { - io::with_str_writer(|wr| self.to_pretty_writer(wr)) + let s = @mut MemWriter::new(); + self.to_pretty_writer(s as @mut io::Writer); + str::from_utf8(s.inner_ref().as_slice()) } } @@ -853,9 +842,9 @@ impl> Parser { } } -/// Decodes a json value from an @io::Reader -pub fn from_reader(rdr: @io::Reader) -> Result { - let s = str::from_utf8(rdr.read_whole_stream()); +/// Decodes a json value from an `&mut io::Reader` +pub fn from_reader(mut rdr: &mut io::Reader) -> Result { + let s = str::from_utf8(rdr.read_to_end()); let mut parser = Parser(~s.iter()); parser.parse() } @@ -1306,7 +1295,9 @@ impl ToJson for Option { impl to_str::ToStr for Json { /// Encodes a json value into a string fn to_str(&self) -> ~str { - io::with_str_writer(|wr| self.to_writer(wr)) + let s = @mut MemWriter::new(); + self.to_writer(s as @mut io::Writer); + str::from_utf8(s.inner_ref().as_slice()) } } @@ -1321,8 +1312,7 @@ mod tests { use super::*; - use std::io; - + use std::rt::io; use serialize::Decodable; use treemap::TreeMap; @@ -1493,18 +1483,28 @@ mod tests { assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap()); } + fn with_str_writer(f: &fn(@mut io::Writer)) -> ~str { + use std::rt::io::mem::MemWriter; + use std::rt::io::Decorator; + use std::str; + + let m = @mut MemWriter::new(); + f(m as @mut io::Writer); + str::from_utf8(*m.inner_ref()) + } + #[test] fn test_write_enum() { let animal = Dog; assert_eq!( - do io::with_str_writer |wr| { + do with_str_writer |wr| { let mut encoder = Encoder(wr); animal.encode(&mut encoder); }, ~"\"Dog\"" ); assert_eq!( - do io::with_str_writer |wr| { + do with_str_writer |wr| { let mut encoder = PrettyEncoder(wr); animal.encode(&mut encoder); }, @@ -1513,14 +1513,14 @@ mod tests { let animal = Frog(~"Henry", 349); assert_eq!( - do io::with_str_writer |wr| { + do with_str_writer |wr| { let mut encoder = Encoder(wr); animal.encode(&mut encoder); }, ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}" ); assert_eq!( - do io::with_str_writer |wr| { + do with_str_writer |wr| { let mut encoder = PrettyEncoder(wr); animal.encode(&mut encoder); }, @@ -1536,14 +1536,14 @@ mod tests { #[test] fn test_write_some() { let value = Some(~"jodhpurs"); - let s = do io::with_str_writer |wr| { + let s = do with_str_writer |wr| { let mut encoder = Encoder(wr); value.encode(&mut encoder); }; assert_eq!(s, ~"\"jodhpurs\""); let value = Some(~"jodhpurs"); - let s = do io::with_str_writer |wr| { + let s = do with_str_writer |wr| { let mut encoder = PrettyEncoder(wr); value.encode(&mut encoder); }; @@ -1553,13 +1553,13 @@ mod tests { #[test] fn test_write_none() { let value: Option<~str> = None; - let s = do io::with_str_writer |wr| { + let s = do with_str_writer |wr| { let mut encoder = Encoder(wr); value.encode(&mut encoder); }; assert_eq!(s, ~"null"); - let s = do io::with_str_writer |wr| { + let s = do with_str_writer |wr| { let mut encoder = Encoder(wr); value.encode(&mut encoder); }; diff --git a/src/libextra/semver.rs b/src/libextra/semver.rs index 02c35000ce3..0ab38cdb5df 100644 --- a/src/libextra/semver.rs +++ b/src/libextra/semver.rs @@ -30,8 +30,6 @@ use std::char; use std::cmp; -use std::io::{ReaderUtil}; -use std::io; use std::option::{Option, Some, None}; use std::to_str::ToStr; @@ -147,14 +145,19 @@ condition! { bad_parse: () -> (); } -fn take_nonempty_prefix(rdr: @io::Reader, - ch: char, - pred: &fn(char) -> bool) -> (~str, char) { +fn take_nonempty_prefix>(rdr: &mut T, + pred: &fn(char) -> bool) -> (~str, Option) { let mut buf = ~""; - let mut ch = ch; - while pred(ch) { - buf.push_char(ch); - ch = rdr.read_char(); + let mut ch = rdr.next(); + loop { + match ch { + None => break, + Some(c) if !pred(c) => break, + Some(c) => { + buf.push_char(c); + ch = rdr.next(); + } + } } if buf.is_empty() { bad_parse::cond.raise(()) @@ -163,16 +166,16 @@ fn take_nonempty_prefix(rdr: @io::Reader, (buf, ch) } -fn take_num(rdr: @io::Reader, ch: char) -> (uint, char) { - let (s, ch) = take_nonempty_prefix(rdr, ch, char::is_digit); +fn take_num>(rdr: &mut T) -> (uint, Option) { + let (s, ch) = take_nonempty_prefix(rdr, char::is_digit); match from_str::(s) { None => { bad_parse::cond.raise(()); (0, ch) }, Some(i) => (i, ch) } } -fn take_ident(rdr: @io::Reader, ch: char) -> (Identifier, char) { - let (s,ch) = take_nonempty_prefix(rdr, ch, char::is_alphanumeric); +fn take_ident>(rdr: &mut T) -> (Identifier, Option) { + let (s,ch) = take_nonempty_prefix(rdr, char::is_alphanumeric); if s.iter().all(char::is_digit) { match from_str::(s) { None => { bad_parse::cond.raise(()); (Numeric(0), ch) }, @@ -183,38 +186,38 @@ fn take_ident(rdr: @io::Reader, ch: char) -> (Identifier, char) { } } -fn expect(ch: char, c: char) { - if ch != c { +fn expect(ch: Option, c: char) { + if ch != Some(c) { bad_parse::cond.raise(()) } } -fn parse_reader(rdr: @io::Reader) -> Version { - let (major, ch) = take_num(rdr, rdr.read_char()); +fn parse_iter>(rdr: &mut T) -> Version { + let (major, ch) = take_num(rdr); expect(ch, '.'); - let (minor, ch) = take_num(rdr, rdr.read_char()); + let (minor, ch) = take_num(rdr); expect(ch, '.'); - let (patch, ch) = take_num(rdr, rdr.read_char()); + let (patch, ch) = take_num(rdr); let mut pre = ~[]; let mut build = ~[]; let mut ch = ch; - if ch == '-' { + if ch == Some('-') { loop { - let (id, c) = take_ident(rdr, rdr.read_char()); + let (id, c) = take_ident(rdr); pre.push(id); ch = c; - if ch != '.' { break; } + if ch != Some('.') { break; } } } - if ch == '+' { + if ch == Some('+') { loop { - let (id, c) = take_ident(rdr, rdr.read_char()); + let (id, c) = take_ident(rdr); build.push(id); ch = c; - if ch != '.' { break; } + if ch != Some('.') { break; } } } @@ -236,13 +239,11 @@ pub fn parse(s: &str) -> Option { let s = s.trim(); let mut bad = false; do bad_parse::cond.trap(|_| { debug!("bad"); bad = true }).inside { - do io::with_str_reader(s) |rdr| { - let v = parse_reader(rdr); - if bad || v.to_str() != s.to_owned() { - None - } else { - Some(v) - } + let v = parse_iter(&mut s.iter()); + if bad || v.to_str() != s.to_owned() { + None + } else { + Some(v) } } } diff --git a/src/libextra/stats.rs b/src/libextra/stats.rs index 40f99716ca7..497145ca7c9 100644 --- a/src/libextra/stats.rs +++ b/src/libextra/stats.rs @@ -13,7 +13,7 @@ use sort; use std::cmp; use std::hashmap; -use std::io; +use std::rt::io; use std::num; // NB: this can probably be rewritten in terms of num::Num @@ -273,14 +273,14 @@ pub fn winsorize(samples: &mut [f64], pct: f64) { } /// Render writes the min, max and quartiles of the provided `Summary` to the provided `Writer`. -pub fn write_5_number_summary(w: @io::Writer, s: &Summary) { +pub fn write_5_number_summary(w: &mut io::Writer, s: &Summary) { let (q1,q2,q3) = s.quartiles; - w.write_str(format!("(min={}, q1={}, med={}, q3={}, max={})", + write!(w, "(min={}, q1={}, med={}, q3={}, max={})", s.min, q1, q2, q3, - s.max)); + s.max); } /// Render a boxplot to the provided writer. The boxplot shows the min, max and quartiles of the @@ -295,7 +295,7 @@ pub fn write_5_number_summary(w: @io::Writer, s: &Summary) { /// 10 | [--****#******----------] | 40 /// ~~~~ -pub fn write_boxplot(w: @io::Writer, s: &Summary, width_hint: uint) { +pub fn write_boxplot(w: &mut io::Writer, s: &Summary, width_hint: uint) { let (q1,q2,q3) = s.quartiles; @@ -325,52 +325,48 @@ pub fn write_boxplot(w: @io::Writer, s: &Summary, width_hint: uint) { let range_width = width_hint - overhead_width;; let char_step = range / (range_width as f64); - w.write_str(lostr); - w.write_char(' '); - w.write_char('|'); + write!(w, "{} |", lostr); let mut c = 0; let mut v = lo; while c < range_width && v < s.min { - w.write_char(' '); + write!(w, " "); v += char_step; c += 1; } - w.write_char('['); + write!(w, "["); c += 1; while c < range_width && v < q1 { - w.write_char('-'); + write!(w, "-"); v += char_step; c += 1; } while c < range_width && v < q2 { - w.write_char('*'); + write!(w, "*"); v += char_step; c += 1; } - w.write_char('#'); + write!(w, r"\#"); c += 1; while c < range_width && v < q3 { - w.write_char('*'); + write!(w, "*"); v += char_step; c += 1; } while c < range_width && v < s.max { - w.write_char('-'); + write!(w, "-"); v += char_step; c += 1; } - w.write_char(']'); + write!(w, "]"); while c < range_width { - w.write_char(' '); + write!(w, " "); v += char_step; c += 1; } - w.write_char('|'); - w.write_char(' '); - w.write_str(histr); + write!(w, "| {}", histr); } /// Returns a HashMap with the number of occurrences of every element in the @@ -392,18 +388,20 @@ mod tests { use stats::Summary; use stats::write_5_number_summary; use stats::write_boxplot; - use std::io; + use std::rt::io; + use std::str; fn check(samples: &[f64], summ: &Summary) { let summ2 = Summary::new(samples); - let w = io::stdout(); - w.write_char('\n'); + let mut w = io::stdout(); + let w = &mut w as &mut io::Writer; + write!(w, "\n"); write_5_number_summary(w, &summ2); - w.write_char('\n'); + write!(w, "\n"); write_boxplot(w, &summ2, 50); - w.write_char('\n'); + write!(w, "\n"); assert_eq!(summ.sum, summ2.sum); assert_eq!(summ.min, summ2.min); @@ -944,10 +942,11 @@ mod tests { #[test] fn test_boxplot_nonpositive() { fn t(s: &Summary, expected: ~str) { - let out = do io::with_str_writer |w| { - write_boxplot(w, s, 30) - }; - + use std::rt::io::mem::MemWriter; + use std::rt::io::Decorator; + let mut m = MemWriter::new(); + write_boxplot(&mut m as &mut io::Writer, s, 30); + let out = str::from_utf8_owned(m.inner()); assert_eq!(out, expected); } diff --git a/src/libextra/term.rs b/src/libextra/term.rs index 878224890e6..22ce833ea24 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -13,7 +13,7 @@ #[allow(missing_doc)]; -use std::io; +use std::rt::io; #[cfg(not(target_os = "win32"))] use std::os; #[cfg(not(target_os = "win32"))] use terminfo::*; @@ -96,19 +96,19 @@ fn cap_for_attr(attr: attr::Attr) -> &'static str { #[cfg(not(target_os = "win32"))] pub struct Terminal { priv num_colors: u16, - priv out: @io::Writer, + priv out: @mut io::Writer, priv ti: ~TermInfo } #[cfg(target_os = "win32")] pub struct Terminal { priv num_colors: u16, - priv out: @io::Writer, + priv out: @mut io::Writer, } #[cfg(not(target_os = "win32"))] impl Terminal { - pub fn new(out: @io::Writer) -> Result { + pub fn new(out: @mut io::Writer) -> Result { let term = os::getenv("TERM"); if term.is_none() { return Err(~"TERM environment variable undefined"); @@ -243,7 +243,7 @@ impl Terminal { #[cfg(target_os = "win32")] impl Terminal { - pub fn new(out: @io::Writer) -> Result { + pub fn new(out: @mut io::Writer) -> Result { return Ok(Terminal {out: out, num_colors: 0}); } diff --git a/src/libextra/test.rs b/src/libextra/test.rs index f95c7aa22b7..457f7868e23 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -30,8 +30,8 @@ use treemap::TreeMap; use std::clone::Clone; use std::comm::{stream, SharedChan, GenericPort, GenericChan}; -use std::io; -use std::result; +use std::rt::io; +use std::rt::io::file::FileInfo; use std::task; use std::to_str::ToStr; use std::f64; @@ -336,8 +336,8 @@ pub enum TestResult { } struct ConsoleTestState { - out: @io::Writer, - log_out: Option<@io::Writer>, + out: @mut io::Writer, + log_out: Option<@mut io::Writer>, term: Option, use_color: bool, total: uint, @@ -353,17 +353,13 @@ struct ConsoleTestState { impl ConsoleTestState { pub fn new(opts: &TestOpts) -> ConsoleTestState { let log_out = match opts.logfile { - Some(ref path) => match io::file_writer(path, - [io::Create, - io::Truncate]) { - result::Ok(w) => Some(w), - result::Err(ref s) => { - fail!("can't open output file: {}", *s) - } + Some(ref path) => { + let out = path.open_writer(io::CreateOrTruncate); + Some(@mut out as @mut io::Writer) }, None => None }; - let out = io::stdout(); + let out = @mut io::stdio::stdout() as @mut io::Writer; let term = match term::Terminal::new(out) { Err(_) => None, Ok(t) => Some(t) @@ -424,12 +420,12 @@ impl ConsoleTestState { word: &str, color: term::color::Color) { match self.term { - None => self.out.write_str(word), + None => self.out.write(word.as_bytes()), Some(ref t) => { if self.use_color { t.fg(color); } - self.out.write_str(word); + self.out.write(word.as_bytes()); if self.use_color { t.reset(); } @@ -440,12 +436,12 @@ impl ConsoleTestState { pub fn write_run_start(&mut self, len: uint) { self.total = len; let noun = if len != 1 { &"tests" } else { &"test" }; - self.out.write_line(format!("\nrunning {} {}", len, noun)); + write!(self.out, "\nrunning {} {}\n", len, noun); } pub fn write_test_start(&self, test: &TestDesc, align: NamePadding) { let name = test.padded_name(self.max_name_len, align); - self.out.write_str(format!("test {} ... ", name)); + write!(self.out, "test {} ... ", name); } pub fn write_result(&self, result: &TestResult) { @@ -455,41 +451,40 @@ impl ConsoleTestState { TrIgnored => self.write_ignored(), TrMetrics(ref mm) => { self.write_metric(); - self.out.write_str(": " + fmt_metrics(mm)); + write!(self.out, ": {}", fmt_metrics(mm)); } TrBench(ref bs) => { self.write_bench(); - self.out.write_str(": " + fmt_bench_samples(bs)) + write!(self.out, ": {}", fmt_bench_samples(bs)); } } - self.out.write_str(&"\n"); + write!(self.out, "\n"); } pub fn write_log(&self, test: &TestDesc, result: &TestResult) { match self.log_out { None => (), Some(out) => { - out.write_line(format!("{} {}", - match *result { + write!(out, "{} {}",match *result { TrOk => ~"ok", TrFailed => ~"failed", TrIgnored => ~"ignored", TrMetrics(ref mm) => fmt_metrics(mm), TrBench(ref bs) => fmt_bench_samples(bs) - }, test.name.to_str())); + }, test.name.to_str()); } } } pub fn write_failures(&self) { - self.out.write_line("\nfailures:"); + write!(self.out, "\nfailures:\n"); let mut failures = ~[]; for f in self.failures.iter() { failures.push(f.name.to_str()); } sort::tim_sort(failures); for name in failures.iter() { - self.out.write_line(format!(" {}", name.to_str())); + writeln!(self.out, " {}", name.to_str()); } } @@ -506,36 +501,34 @@ impl ConsoleTestState { MetricAdded => { added += 1; self.write_added(); - self.out.write_line(format!(": {}", *k)); + writeln!(self.out, ": {}", *k); } MetricRemoved => { removed += 1; self.write_removed(); - self.out.write_line(format!(": {}", *k)); + writeln!(self.out, ": {}", *k); } Improvement(pct) => { improved += 1; - self.out.write_str(*k); - self.out.write_str(": "); + write!(self.out, "{}: ", *k); self.write_improved(); - self.out.write_line(format!(" by {:.2f}%", pct as f64)) + writeln!(self.out, " by {:.2f}%", pct as f64); } Regression(pct) => { regressed += 1; - self.out.write_str(*k); - self.out.write_str(": "); + write!(self.out, "{}: ", *k); self.write_regressed(); - self.out.write_line(format!(" by {:.2f}%", pct as f64)) + writeln!(self.out, " by {:.2f}%", pct as f64); } } } - self.out.write_line(format!("result of ratchet: {} matrics added, {} removed, \ - {} improved, {} regressed, {} noise", - added, removed, improved, regressed, noise)); + writeln!(self.out, "result of ratchet: {} matrics added, {} removed, \ + {} improved, {} regressed, {} noise", + added, removed, improved, regressed, noise); if regressed == 0 { - self.out.write_line("updated ratchet file") + writeln!(self.out, "updated ratchet file"); } else { - self.out.write_line("left ratchet file untouched") + writeln!(self.out, "left ratchet file untouched"); } } @@ -547,12 +540,12 @@ impl ConsoleTestState { let ratchet_success = match *ratchet_metrics { None => true, Some(ref pth) => { - self.out.write_str(format!("\nusing metrics ratchet: {}\n", pth.display())); + write!(self.out, "\nusing metrics ratcher: {}\n", pth.display()); match ratchet_pct { None => (), Some(pct) => - self.out.write_str(format!("with noise-tolerance forced to: {}%%\n", - pct as f64)) + writeln!(self.out, "with noise-tolerance forced to: {}%", + pct) } let (diff, ok) = self.metrics.ratchet(pth, ratchet_pct); self.write_metric_diff(&diff); @@ -567,15 +560,15 @@ impl ConsoleTestState { let success = ratchet_success && test_success; - self.out.write_str("\ntest result: "); + write!(self.out, "\ntest result: "); if success { // There's no parallelism at this point so it's safe to use color self.write_ok(); } else { self.write_failed(); } - self.out.write_str(format!(". {} passed; {} failed; {} ignored; {} measured\n\n", - self.passed, self.failed, self.ignored, self.measured)); + write!(self.out, ". {} passed; {} failed; {} ignored; {} measured\n\n", + self.passed, self.failed, self.ignored, self.measured); return success; } } @@ -659,7 +652,7 @@ pub fn run_tests_console(opts: &TestOpts, None => (), Some(ref pth) => { st.metrics.save(pth); - st.out.write_str(format!("\nmetrics saved to: {}", pth.display())); + write!(st.out, "\nmetrics saved to: {}", pth.display()); } } return st.write_run_finish(&opts.ratchet_metrics, opts.ratchet_noise_percent); @@ -667,39 +660,43 @@ pub fn run_tests_console(opts: &TestOpts, #[test] fn should_sort_failures_before_printing_them() { + use std::rt::io; + use std::rt::io::Decorator; + use std::rt::io::mem::MemWriter; + use std::str; fn dummy() {} - let s = do io::with_str_writer |wr| { - let test_a = TestDesc { - name: StaticTestName("a"), - ignore: false, - should_fail: false - }; - - let test_b = TestDesc { - name: StaticTestName("b"), - ignore: false, - should_fail: false - }; - - let st = @ConsoleTestState { - out: wr, - log_out: None, - term: None, - use_color: false, - total: 0u, - passed: 0u, - failed: 0u, - ignored: 0u, - measured: 0u, - metrics: MetricMap::new(), - failures: ~[test_b, test_a], - max_name_len: 0u, - }; - - st.write_failures(); + let m = @mut MemWriter::new(); + let test_a = TestDesc { + name: StaticTestName("a"), + ignore: false, + should_fail: false }; + let test_b = TestDesc { + name: StaticTestName("b"), + ignore: false, + should_fail: false + }; + + let st = @ConsoleTestState { + out: m as @mut io::Writer, + log_out: None, + term: None, + use_color: false, + total: 0u, + passed: 0u, + failed: 0u, + ignored: 0u, + measured: 0u, + max_name_len: 10u, + metrics: MetricMap::new(), + failures: ~[test_b, test_a] + }; + + st.write_failures(); + let s = str::from_utf8(*m.inner_ref()); + let apos = s.find_str("a").unwrap(); let bpos = s.find_str("b").unwrap(); assert!(apos < bpos); @@ -939,15 +936,15 @@ impl MetricMap { /// Load MetricDiff from a file. pub fn load(p: &Path) -> MetricMap { assert!(os::path_exists(p)); - let f = io::file_reader(p).unwrap(); + let f = @mut p.open_reader(io::Open) as @mut io::Reader; let mut decoder = json::Decoder(json::from_reader(f).unwrap()); MetricMap(Decodable::decode(&mut decoder)) } /// Write MetricDiff to a file. pub fn save(&self, p: &Path) { - let f = io::file_writer(p, [io::Create, io::Truncate]).unwrap(); - self.to_json().to_pretty_writer(f); + let f = @mut p.open_writer(io::CreateOrTruncate); + self.to_json().to_pretty_writer(f as @mut io::Writer); } /// Compare against another MetricMap. Optionally compare all diff --git a/src/libextra/time.rs b/src/libextra/time.rs index f675c6f2392..2950f02ad19 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -10,7 +10,8 @@ #[allow(missing_doc)]; -use std::io; +use std::rt::io::Reader; +use std::rt::io::mem::BufReader; use std::num; use std::str; @@ -666,61 +667,69 @@ pub fn strptime(s: &str, format: &str) -> Result { } } - do io::with_str_reader(format) |rdr| { - let mut tm = Tm { - tm_sec: 0_i32, - tm_min: 0_i32, - tm_hour: 0_i32, - tm_mday: 0_i32, - tm_mon: 0_i32, - tm_year: 0_i32, - tm_wday: 0_i32, - tm_yday: 0_i32, - tm_isdst: 0_i32, - tm_gmtoff: 0_i32, - tm_zone: ~"", - tm_nsec: 0_i32, + let mut rdr = BufReader::new(format.as_bytes()); + let mut tm = Tm { + tm_sec: 0_i32, + tm_min: 0_i32, + tm_hour: 0_i32, + tm_mday: 0_i32, + tm_mon: 0_i32, + tm_year: 0_i32, + tm_wday: 0_i32, + tm_yday: 0_i32, + tm_isdst: 0_i32, + tm_gmtoff: 0_i32, + tm_zone: ~"", + tm_nsec: 0_i32, + }; + let mut pos = 0u; + let len = s.len(); + let mut result = Err(~"Invalid time"); + + while pos < len { + let range = s.char_range_at(pos); + let ch = range.ch; + let next = range.next; + + let mut buf = [0]; + let c = match rdr.read(buf) { + Some(*) => buf[0] as u8 as char, + None => break }; - let mut pos = 0u; - let len = s.len(); - let mut result = Err(~"Invalid time"); - - while !rdr.eof() && pos < len { - let range = s.char_range_at(pos); - let ch = range.ch; - let next = range.next; - - match rdr.read_char() { - '%' => { - match parse_type(s, pos, rdr.read_char(), &mut tm) { - Ok(next) => pos = next, - Err(e) => { result = Err(e); break; } - } - }, - c => { - if c != ch { break } - pos = next; + match c { + '%' => { + let ch = match rdr.read(buf) { + Some(*) => buf[0] as u8 as char, + None => break + }; + match parse_type(s, pos, ch, &mut tm) { + Ok(next) => pos = next, + Err(e) => { result = Err(e); break; } } + }, + c => { + if c != ch { break } + pos = next; } } - - if pos == len && rdr.eof() { - Ok(Tm { - tm_sec: tm.tm_sec, - tm_min: tm.tm_min, - tm_hour: tm.tm_hour, - tm_mday: tm.tm_mday, - tm_mon: tm.tm_mon, - tm_year: tm.tm_year, - tm_wday: tm.tm_wday, - tm_yday: tm.tm_yday, - tm_isdst: tm.tm_isdst, - tm_gmtoff: tm.tm_gmtoff, - tm_zone: tm.tm_zone.clone(), - tm_nsec: tm.tm_nsec, - }) - } else { result } } + + if pos == len && rdr.eof() { + Ok(Tm { + tm_sec: tm.tm_sec, + tm_min: tm.tm_min, + tm_hour: tm.tm_hour, + tm_mday: tm.tm_mday, + tm_mon: tm.tm_mon, + tm_year: tm.tm_year, + tm_wday: tm.tm_wday, + tm_yday: tm.tm_yday, + tm_isdst: tm.tm_isdst, + tm_gmtoff: tm.tm_gmtoff, + tm_zone: tm.tm_zone.clone(), + tm_nsec: tm.tm_nsec, + }) + } else { result } } /// Formats the time according to the format string. @@ -929,18 +938,26 @@ pub fn strftime(format: &str, tm: &Tm) -> ~str { } } - let mut buf = ~""; + let mut buf = ~[]; - do io::with_str_reader(format) |rdr| { - while !rdr.eof() { - match rdr.read_char() { - '%' => buf.push_str(parse_type(rdr.read_char(), tm)), - ch => buf.push_char(ch) + let mut rdr = BufReader::new(format.as_bytes()); + loop { + let mut b = [0]; + let ch = match rdr.read(b) { + Some(*) => b[0], + None => break, + }; + match ch as char { + '%' => { + rdr.read(b); + let s = parse_type(b[0] as char, tm); + buf.push_all(s.as_bytes()); } + ch => buf.push(ch as u8) } } - buf + str::from_utf8_owned(buf) } #[cfg(test)] diff --git a/src/libextra/url.rs b/src/libextra/url.rs index e836d3b5270..bfa3934700a 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -12,10 +12,9 @@ #[allow(missing_doc)]; - +use std::rt::io::{Reader, Seek}; +use std::rt::io::mem::BufReader; use std::cmp::Eq; -use std::io::{Reader, ReaderUtil}; -use std::io; use std::hashmap::HashMap; use std::to_bytes; use std::uint; @@ -68,42 +67,46 @@ impl UserInfo { } fn encode_inner(s: &str, full_url: bool) -> ~str { - do io::with_str_reader(s) |rdr| { - let mut out = ~""; + let mut rdr = BufReader::new(s.as_bytes()); + let mut out = ~""; - while !rdr.eof() { - let ch = rdr.read_byte() as u8 as char; - match ch { - // unreserved: - 'A' .. 'Z' | - 'a' .. 'z' | - '0' .. '9' | - '-' | '.' | '_' | '~' => { - out.push_char(ch); - } - _ => { - if full_url { - match ch { - // gen-delims: - ':' | '/' | '?' | '#' | '[' | ']' | '@' | + loop { + let mut buf = [0]; + let ch = match rdr.read(buf) { + None => break, + Some(*) => buf[0] as char, + }; - // sub-delims: - '!' | '$' | '&' | '"' | '(' | ')' | '*' | - '+' | ',' | ';' | '=' => { - out.push_char(ch); - } + match ch { + // unreserved: + 'A' .. 'Z' | + 'a' .. 'z' | + '0' .. '9' | + '-' | '.' | '_' | '~' => { + out.push_char(ch); + } + _ => { + if full_url { + match ch { + // gen-delims: + ':' | '/' | '?' | '#' | '[' | ']' | '@' | - _ => out.push_str(format!("%{:X}", ch as uint)) - } - } else { - out.push_str(format!("%{:X}", ch as uint)); + // sub-delims: + '!' | '$' | '&' | '"' | '(' | ')' | '*' | + '+' | ',' | ';' | '=' => { + out.push_char(ch); + } + + _ => out.push_str(format!("%{:X}", ch as uint)) } - } + } else { + out.push_str(format!("%{:X}", ch as uint)); } + } } - - out } + + out } /** @@ -128,41 +131,49 @@ pub fn encode_component(s: &str) -> ~str { } fn decode_inner(s: &str, full_url: bool) -> ~str { - do io::with_str_reader(s) |rdr| { - let mut out = ~""; + let mut rdr = BufReader::new(s.as_bytes()); + let mut out = ~""; - while !rdr.eof() { - match rdr.read_char() { - '%' => { - let bytes = rdr.read_bytes(2u); - let ch = uint::parse_bytes(bytes, 16u).unwrap() as u8 as char; - - if full_url { - // Only decode some characters: - match ch { - // gen-delims: - ':' | '/' | '?' | '#' | '[' | ']' | '@' | - - // sub-delims: - '!' | '$' | '&' | '"' | '(' | ')' | '*' | - '+' | ',' | ';' | '=' => { - out.push_char('%'); - out.push_char(bytes[0u] as char); - out.push_char(bytes[1u] as char); - } - - ch => out.push_char(ch) - } - } else { - out.push_char(ch); - } - } - ch => out.push_char(ch) + loop { + let mut buf = [0]; + let ch = match rdr.read(buf) { + None => break, + Some(*) => buf[0] as char + }; + match ch { + '%' => { + let mut bytes = [0, 0]; + match rdr.read(bytes) { + Some(2) => {} + _ => fail2!() // XXX: malformed url? } - } + let ch = uint::parse_bytes(bytes, 16u).unwrap() as u8 as char; - out + if full_url { + // Only decode some characters: + match ch { + // gen-delims: + ':' | '/' | '?' | '#' | '[' | ']' | '@' | + + // sub-delims: + '!' | '$' | '&' | '"' | '(' | ')' | '*' | + '+' | ',' | ';' | '=' => { + out.push_char('%'); + out.push_char(bytes[0u] as char); + out.push_char(bytes[1u] as char); + } + + ch => out.push_char(ch) + } + } else { + out.push_char(ch); + } + } + ch => out.push_char(ch) + } } + + out } /** @@ -182,22 +193,25 @@ pub fn decode_component(s: &str) -> ~str { } fn encode_plus(s: &str) -> ~str { - do io::with_str_reader(s) |rdr| { - let mut out = ~""; + let mut rdr = BufReader::new(s.as_bytes()); + let mut out = ~""; - while !rdr.eof() { - let ch = rdr.read_byte() as u8 as char; - match ch { - 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '.' | '-' => { - out.push_char(ch); - } - ' ' => out.push_char('+'), - _ => out.push_str(format!("%{:X}", ch as uint)) - } + loop { + let mut buf = [0]; + let ch = match rdr.read(buf) { + Some(*) => buf[0] as char, + None => break, + }; + match ch { + 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '.' | '-' => { + out.push_char(ch); + } + ' ' => out.push_char('+'), + _ => out.push_str(format!("%{:X}", ch as uint)) } - - out } + + out } /** @@ -230,61 +244,69 @@ pub fn encode_form_urlencoded(m: &HashMap<~str, ~[~str]>) -> ~str { * type into a hashmap. */ pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<~str, ~[~str]> { - do io::with_bytes_reader(s) |rdr| { - let mut m = HashMap::new(); - let mut key = ~""; - let mut value = ~""; - let mut parsing_key = true; + let mut rdr = BufReader::new(s); + let mut m = HashMap::new(); + let mut key = ~""; + let mut value = ~""; + let mut parsing_key = true; - while !rdr.eof() { - match rdr.read_char() { - '&' | ';' => { - if key != ~"" && value != ~"" { - let mut values = match m.pop(&key) { - Some(values) => values, - None => ~[], - }; - - values.push(value); - m.insert(key, values); - } - - parsing_key = true; - key = ~""; - value = ~""; - } - '=' => parsing_key = false, - ch => { - let ch = match ch { - '%' => { - let bytes = rdr.read_bytes(2u); - uint::parse_bytes(bytes, 16u).unwrap() as u8 as char - } - '+' => ' ', - ch => ch + loop { + let mut buf = [0]; + let ch = match rdr.read(buf) { + Some(*) => buf[0] as char, + None => break, + }; + match ch { + '&' | ';' => { + if key != ~"" && value != ~"" { + let mut values = match m.pop(&key) { + Some(values) => values, + None => ~[], }; - if parsing_key { - key.push_char(ch) - } else { - value.push_char(ch) + values.push(value); + m.insert(key, values); + } + + parsing_key = true; + key = ~""; + value = ~""; + } + '=' => parsing_key = false, + ch => { + let ch = match ch { + '%' => { + let mut bytes = [0, 0]; + match rdr.read(bytes) { + Some(2) => {} + _ => fail2!() // XXX: malformed? + } + uint::parse_bytes(bytes, 16u).unwrap() as u8 as char } + '+' => ' ', + ch => ch + }; + + if parsing_key { + key.push_char(ch) + } else { + value.push_char(ch) } } } - - if key != ~"" && value != ~"" { - let mut values = match m.pop(&key) { - Some(values) => values, - None => ~[], - }; - - values.push(value); - m.insert(key, values); - } - - m } + + if key != ~"" && value != ~"" { + let mut values = match m.pop(&key) { + Some(values) => values, + None => ~[], + }; + + values.push(value); + m.insert(key, values); + } + + m } @@ -292,16 +314,18 @@ fn split_char_first(s: &str, c: char) -> (~str, ~str) { let len = s.len(); let mut index = len; let mut mat = 0; - do io::with_str_reader(s) |rdr| { - let mut ch; - while !rdr.eof() { - ch = rdr.read_byte() as u8 as char; - if ch == c { - // found a match, adjust markers - index = rdr.tell()-1; - mat = 1; - break; - } + let mut rdr = BufReader::new(s.as_bytes()); + loop { + let mut buf = [0]; + let ch = match rdr.read(buf) { + Some(*) => buf[0] as char, + None => break, + }; + if ch == c { + // found a match, adjust markers + index = (rdr.tell() as uint) - 1; + mat = 1; + break; } } if index+mat == len { diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index 4d79b2059db..30efecde37f 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -19,7 +19,13 @@ use arc::{Arc,RWArc}; use treemap::TreeMap; use std::cell::Cell; use std::comm::{PortOne, oneshot}; -use std::{io, os, task}; +use std::{os, str, task}; +use std::rt::io; +use std::rt::io::Writer; +use std::rt::io::Decorator; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::mem::MemWriter; +use std::rt::io::file::FileInfo; /** * @@ -174,19 +180,19 @@ impl Database { // FIXME #4330: This should have &mut self and should set self.db_dirty to false. fn save(&self) { - let f = io::file_writer(&self.db_filename, [io::Create, io::Truncate]).unwrap(); - self.db_cache.to_json().to_pretty_writer(f); + let f = @mut self.db_filename.open_writer(io::CreateOrTruncate); + self.db_cache.to_json().to_pretty_writer(f as @mut io::Writer); } fn load(&mut self) { assert!(!self.db_dirty); assert!(os::path_exists(&self.db_filename)); - let f = io::file_reader(&self.db_filename); + let f = self.db_filename.open_reader(io::Open); match f { - Err(e) => fail!("Couldn't load workcache database {}: {}", - self.db_filename.display(), e.to_str()), - Ok(r) => - match json::from_reader(r) { + None => fail!("Couldn't load workcache database {}", + self.db_filename.display()), + Some(r) => + match json::from_reader(@mut r as @mut io::Reader) { Err(e) => fail!("Couldn't parse workcache database (from file {}): {}", self.db_filename.display(), e.to_str()), Ok(r) => { @@ -256,20 +262,18 @@ enum Work<'self, T> { } fn json_encode>(t: &T) -> ~str { - do io::with_str_writer |wr| { - let mut encoder = json::Encoder(wr); - t.encode(&mut encoder); - } + let writer = @mut MemWriter::new(); + let mut encoder = json::Encoder(writer as @mut io::Writer); + t.encode(&mut encoder); + str::from_utf8(writer.inner_ref().as_slice()) } // FIXME(#5121) fn json_decode>(s: &str) -> T { debug!("json decoding: {}", s); - do io::with_str_reader(s) |rdr| { - let j = json::from_reader(rdr).unwrap(); - let mut decoder = json::Decoder(j); - Decodable::decode(&mut decoder) - } + let j = json::from_str(s).unwrap(); + let mut decoder = json::Decoder(j); + Decodable::decode(&mut decoder) } fn digest>(t: &T) -> ~str { @@ -280,8 +284,8 @@ fn digest>(t: &T) -> ~str { fn digest_file(path: &Path) -> ~str { let mut sha = ~Sha1::new(); - let s = io::read_whole_file_str(path); - (*sha).input_str(s.unwrap()); + let s = path.open_reader(io::Open).read_to_end(); + (*sha).input(s); (*sha).result_str() } @@ -492,7 +496,6 @@ impl<'self, T:Send + #[test] fn test() { - use std::io::WriterUtil; use std::{os, run}; // Create a path to a new file 'filename' in the directory in which @@ -507,8 +510,7 @@ fn test() { let pth = make_path(~"foo.c"); { - let r = io::file_writer(&pth, [io::Create]); - r.unwrap().write_str("int main() { return 0; }"); + pth.open_writer(io::Create).write(bytes!("int main() { return 0; }")); } let db_path = make_path(~"db.json"); @@ -539,5 +541,5 @@ fn test() { } }; - io::println(s); + println(s); } diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 2438d22881f..1b9cb10f1dc 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -26,7 +26,6 @@ use std::c_str::ToCStr; use std::char; use std::hash::Streaming; use std::hash; -use std::io; use std::os::consts::{macos, freebsd, linux, android, win32}; use std::os; use std::ptr; @@ -930,7 +929,7 @@ pub fn link_binary(sess: Session, let cc_args = link_args(sess, obj_filename, out_filename, lm); debug!("{} link args: {}", cc_prog, cc_args.connect(" ")); if (sess.opts.debugging_opts & session::print_link_args) != 0 { - io::println(format!("{} link args: {}", cc_prog, cc_args.connect(" "))); + println!("{} link args: {}", cc_prog, cc_args.connect(" ")); } // We run 'cc' here diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 67a59f24e29..d2b0dad80f6 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -26,7 +26,8 @@ use util::common::time; use util::ppaux; use std::hashmap::{HashMap,HashSet}; -use std::io; +use std::rt::io; +use std::rt::io::mem::MemReader; use std::os; use std::vec; use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt}; @@ -552,17 +553,16 @@ pub fn pretty_print_input(sess: Session, }; let src = sess.codemap.get_filemap(source_name(input)).src; - do io::with_str_reader(src) |rdr| { - pprust::print_crate(sess.codemap, - token::get_ident_interner(), - sess.span_diagnostic, - &crate, - source_name(input), - rdr, - io::stdout(), - annotation, - is_expanded); - } + let rdr = @mut MemReader::new(src.as_bytes().to_owned()); + pprust::print_crate(sess.codemap, + token::get_ident_interner(), + sess.span_diagnostic, + &crate, + source_name(input), + rdr as @mut io::Reader, + @mut io::stdout() as @mut io::Writer, + annotation, + is_expanded); } pub fn get_os(triple: &str) -> Option { @@ -1048,7 +1048,7 @@ pub fn early_error(emitter: @diagnostic::Emitter, msg: &str) -> ! { fail!(); } -pub fn list_metadata(sess: Session, path: &Path, out: @io::Writer) { +pub fn list_metadata(sess: Session, path: &Path, out: @mut io::Writer) { metadata::loader::list_file_metadata( token::get_ident_interner(), session::sess_os_to_meta_os(sess.targ_cfg.os), path, out); diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 10232730329..be118792f49 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -27,8 +27,7 @@ use middle::astencode::vtable_decoder_helpers; use std::u64; -use std::io::WriterUtil; -use std::io; +use std::rt::io; use std::option; use std::str; use std::vec; @@ -56,14 +55,14 @@ fn lookup_hash(d: ebml::Doc, eq_fn: &fn(x:&[u8]) -> bool, hash: u64) -> let index = reader::get_doc(d, tag_index); let table = reader::get_doc(index, tag_index_table); let hash_pos = table.start + (hash % 256 * 4) as uint; - let pos = io::u64_from_be_bytes(*d.data, hash_pos, 4) as uint; + let pos = ::std::io::u64_from_be_bytes(*d.data, hash_pos, 4) as uint; let tagged_doc = reader::doc_at(d.data, pos); let belt = tag_index_buckets_bucket_elt; let mut ret = None; do reader::tagged_docs(tagged_doc.doc, belt) |elt| { - let pos = io::u64_from_be_bytes(*elt.data, elt.start, 4) as uint; + let pos = ::std::io::u64_from_be_bytes(*elt.data, elt.start, 4) as uint; if eq_fn(elt.data.slice(elt.start + 4, elt.end)) { ret = Some(reader::doc_at(d.data, pos).doc); false @@ -78,7 +77,7 @@ pub type GetCrateDataCb<'self> = &'self fn(ast::CrateNum) -> Cmd; pub fn maybe_find_item(item_id: int, items: ebml::Doc) -> Option { fn eq_item(bytes: &[u8], item_id: int) -> bool { - return io::u64_from_be_bytes( + return ::std::io::u64_from_be_bytes( bytes.slice(0u, 4u), 0u, 4u) as int == item_id; } @@ -1254,7 +1253,7 @@ fn family_names_type(fam: Family) -> bool { fn read_path(d: ebml::Doc) -> (~str, uint) { do reader::with_doc_data(d) |desc| { - let pos = io::u64_from_be_bytes(desc, 0u, 4u) as uint; + let pos = ::std::io::u64_from_be_bytes(desc, 0u, 4u) as uint; let pathbytes = desc.slice(4u, desc.len()); let path = str::from_utf8(pathbytes); @@ -1353,23 +1352,23 @@ fn get_attributes(md: ebml::Doc) -> ~[ast::Attribute] { fn list_meta_items(intr: @ident_interner, meta_items: ebml::Doc, - out: @io::Writer) { + out: @mut io::Writer) { let r = get_meta_items(meta_items); for mi in r.iter() { - out.write_str(format!("{}\n", pprust::meta_item_to_str(*mi, intr))); + write!(out, "{}\n", pprust::meta_item_to_str(*mi, intr)); } } fn list_crate_attributes(intr: @ident_interner, md: ebml::Doc, hash: &str, - out: @io::Writer) { - out.write_str(format!("=Crate Attributes ({})=\n", hash)); + out: @mut io::Writer) { + write!(out, "=Crate Attributes ({})=\n", hash); let r = get_attributes(md); for attr in r.iter() { - out.write_str(format!("{}\n", pprust::attribute_to_str(attr, intr))); + write!(out, "{}\n", pprust::attribute_to_str(attr, intr)); } - out.write_str("\n\n"); + write!(out, "\n\n"); } pub fn get_crate_attributes(data: @~[u8]) -> ~[ast::Attribute] { @@ -1404,17 +1403,16 @@ pub fn get_crate_deps(data: @~[u8]) -> ~[CrateDep] { return deps; } -fn list_crate_deps(data: @~[u8], out: @io::Writer) { - out.write_str("=External Dependencies=\n"); +fn list_crate_deps(data: @~[u8], out: @mut io::Writer) { + write!(out, "=External Dependencies=\n"); let r = get_crate_deps(data); for dep in r.iter() { - out.write_str( - format!("{} {}-{}-{}\n", - dep.cnum, token::ident_to_str(&dep.name), dep.hash, dep.vers)); + write!(out, "{} {}-{}-{}\n", + dep.cnum, token::ident_to_str(&dep.name), dep.hash, dep.vers); } - out.write_str("\n"); + write!(out, "\n"); } pub fn get_crate_hash(data: @~[u8]) -> @str { @@ -1434,7 +1432,7 @@ pub fn get_crate_vers(data: @~[u8]) -> @str { } pub fn list_crate_metadata(intr: @ident_interner, bytes: @~[u8], - out: @io::Writer) { + out: @mut io::Writer) { let hash = get_crate_hash(bytes); let md = reader::Doc(bytes); list_crate_attributes(intr, md, hash, out); diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index bae0dcc2a52..e6d6b282572 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1819,7 +1819,7 @@ pub fn encode_metadata(parms: EncodeParams, crate: &Crate) -> ~[u8] { } } - io::println("metadata stats:"); + println("metadata stats:"); println!(" inline bytes: {}", ecx.stats.inline_bytes); println!(" attribute bytes: {}", ecx.stats.attr_bytes); println!(" dep bytes: {}", ecx.stats.dep_bytes); diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index e682ff299a9..34eb387a3f5 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -25,7 +25,7 @@ use syntax::attr::AttrMetaMethods; use std::c_str::ToCStr; use std::cast; -use std::io; +use std::rt::io; use std::num; use std::option; use std::os::consts::{macos, freebsd, linux, android, win32}; @@ -271,11 +271,11 @@ pub fn read_meta_section_name(os: Os) -> &'static str { pub fn list_file_metadata(intr: @ident_interner, os: Os, path: &Path, - out: @io::Writer) { + out: @mut io::Writer) { match get_metadata_section(os, path) { option::Some(bytes) => decoder::list_crate_metadata(intr, bytes, out), option::None => { - out.write_str(format!("could not find metadata in {}.\n", path.display())) + write!(out, "could not find metadata in {}.\n", path.display()) } } } diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 2722fff12a8..55daff90e62 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -21,7 +21,6 @@ use util::common::stmt_set; use util::ppaux::{note_and_explain_region, Repr, UserString}; use std::hashmap::{HashSet, HashMap}; -use std::io; use std::ops::{BitOr, BitAnd}; use std::result::{Result}; use syntax::ast; @@ -99,7 +98,7 @@ pub fn check_crate( visit::walk_crate(bccx, crate, ()); if tcx.sess.borrowck_stats() { - io::println("--- borrowck stats ---"); + println("--- borrowck stats ---"); println!("paths requiring guarantees: {}", bccx.stats.guaranteed_paths); println!("paths requiring loans : {}", diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 22fd1d393e9..7ad55936b9e 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -18,7 +18,7 @@ use std::cast; -use std::io; +use std::rt::io; use std::uint; use std::vec; use std::hashmap::HashMap; @@ -349,12 +349,12 @@ impl DataFlowContext { debug!("Dataflow result:"); debug!("{}", { let this = @(*self).clone(); - this.pretty_print_to(io::stderr(), blk); + this.pretty_print_to(@mut io::stderr() as @mut io::Writer, blk); "" }); } - fn pretty_print_to(@self, wr: @io::Writer, blk: &ast::Block) { + fn pretty_print_to(@self, wr: @mut io::Writer, blk: &ast::Block) { let ps = pprust::rust_printer_annotated(wr, self.tcx.sess.intr(), self as @pprust::pp_ann); diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 71934c9f2a7..695f4a6fd13 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,7 +111,8 @@ use middle::moves; use std::cast::transmute; use std::hashmap::HashMap; -use std::io; +use std::rt::io; +use std::str; use std::to_str; use std::uint; use std::vec; @@ -739,15 +740,14 @@ impl Liveness { } pub fn write_vars(&self, - wr: @io::Writer, + wr: &mut io::Writer, ln: LiveNode, test: &fn(uint) -> LiveNode) { let node_base_idx = self.idx(ln, Variable(0)); for var_idx in range(0u, self.ir.num_vars) { let idx = node_base_idx + var_idx; if test(idx).is_valid() { - wr.write_str(" "); - wr.write_str(Variable(var_idx).to_str()); + write!(wr, " {}", Variable(var_idx).to_str()); } } } @@ -784,20 +784,14 @@ impl Liveness { } pub fn ln_str(&self, ln: LiveNode) -> ~str { - do io::with_str_writer |wr| { - wr.write_str("[ln("); - wr.write_uint(*ln); - wr.write_str(") of kind "); - wr.write_str(format!("{:?}", self.ir.lnks[*ln])); - wr.write_str(" reads"); + str::from_utf8_owned(do io::mem::with_mem_writer |wr| { + let wr = wr as &mut io::Writer; + write!(wr, "[ln({}) of kind {:?} reads", *ln, self.ir.lnks[*ln]); self.write_vars(wr, ln, |idx| self.users[idx].reader ); - wr.write_str(" writes"); + write!(wr, " writes"); self.write_vars(wr, ln, |idx| self.users[idx].writer ); - wr.write_str(" "); - wr.write_str(" precedes "); - wr.write_str((self.successors[*ln]).to_str()); - wr.write_str("]"); - } + write!(wr, " precedes {}]", self.successors[*ln].to_str()); + }) } pub fn init_empty(&self, ln: LiveNode, succ_ln: LiveNode) { diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index df7b09f9db7..8b5167b7e8f 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -70,7 +70,6 @@ use middle::trans::type_::Type; use std::c_str::ToCStr; use std::hash; use std::hashmap::HashMap; -use std::io; use std::libc::c_uint; use std::vec; use std::local_data; @@ -3163,7 +3162,7 @@ pub fn trans_crate(sess: session::Session, // Translate the metadata. write_metadata(ccx, &crate); if ccx.sess.trans_stats() { - io::println("--- trans stats ---"); + println("--- trans stats ---"); println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs); println!("n_glues_created: {}", ccx.stats.n_glues_created); println!("n_null_glues: {}", ccx.stats.n_null_glues); @@ -3173,7 +3172,7 @@ pub fn trans_crate(sess: session::Session, println!("n_monos: {}", ccx.stats.n_monos); println!("n_inlines: {}", ccx.stats.n_inlines); println!("n_closures: {}", ccx.stats.n_closures); - io::println("fn stats:"); + println("fn stats:"); do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| { insns_a > insns_b } diff --git a/src/librustc/rustc.rs b/src/librustc/rustc.rs index ecf45d5c424..ce50397d003 100644 --- a/src/librustc/rustc.rs +++ b/src/librustc/rustc.rs @@ -36,7 +36,8 @@ use driver::session; use middle::lint; use std::comm; -use std::io; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; use std::num; use std::os; use std::result; @@ -181,7 +182,7 @@ Available lint options: lint::level_to_str(spec.default), spec.desc); } - io::println(""); + println(""); } pub fn describe_debug_flags() { @@ -247,7 +248,7 @@ pub fn run_compiler(args: &[~str], demitter: @diagnostic::Emitter) { 1u => { let ifile = matches.free[0].as_slice(); if "-" == ifile { - let src = str::from_utf8(io::stdin().read_whole_stream()); + let src = str::from_utf8(io::stdin().read_to_end()); str_input(src.to_managed()) } else { file_input(Path::new(ifile)) @@ -275,7 +276,7 @@ pub fn run_compiler(args: &[~str], demitter: @diagnostic::Emitter) { if ls { match input { file_input(ref ifile) => { - list_metadata(sess, &(*ifile), io::stdout()); + list_metadata(sess, &(*ifile), @mut io::stdout() as @mut io::Writer); } str_input(_) => { early_error(demitter, "can not list metadata for stdin"); diff --git a/src/librustdoc/rustdoc.rs b/src/librustdoc/rustdoc.rs index 4c53fe48fe1..c0fab1ad98f 100644 --- a/src/librustdoc/rustdoc.rs +++ b/src/librustdoc/rustdoc.rs @@ -28,6 +28,9 @@ use std::local_data; use std::rt::io::Writer; use std::rt::io::file::FileInfo; use std::rt::io; +use std::rt::io::mem::MemWriter; +use std::rt::io::Decorator; +use std::str; use extra::getopts; use extra::getopts::groups; use extra::json; @@ -257,11 +260,11 @@ fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output { /// This input format purely deserializes the json output file. No passes are /// run over the deserialized output. fn json_input(input: &str) -> Result { - let input = match ::std::io::file_reader(&Path::new(input)) { - Ok(i) => i, - Err(s) => return Err(s), + let input = match Path::new(input).open_reader(io::Open) { + Some(f) => f, + None => return Err(format!("couldn't open {} for reading", input)), }; - match json::from_reader(input) { + match json::from_reader(@mut input as @mut io::Reader) { Err(s) => Err(s.to_str()), Ok(json::Object(obj)) => { let mut obj = obj; @@ -306,8 +309,10 @@ fn json_output(crate: clean::Crate, res: ~[plugins::PluginJson], dst: Path) { // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode // straight to the Rust JSON representation. - let crate_json_str = do std::io::with_str_writer |w| { - crate.encode(&mut json::Encoder(w)); + let crate_json_str = { + let w = @mut MemWriter::new(); + crate.encode(&mut json::Encoder(w as @mut io::Writer)); + str::from_utf8(*w.inner_ref()) }; let crate_json = match json::from_str(crate_json_str) { Ok(j) => j, diff --git a/src/librustpkg/context.rs b/src/librustpkg/context.rs index 72197219fc5..bee21d70b2d 100644 --- a/src/librustpkg/context.rs +++ b/src/librustpkg/context.rs @@ -10,7 +10,7 @@ // Context data structure used by rustpkg -use std::{io, os}; +use std::os; use extra::workcache; use rustc::driver::session::{OptLevel, No}; @@ -243,43 +243,43 @@ pub fn flags_forbidden_for_cmd(flags: &RustcFlags, }; if flags.linker.is_some() && cmd != "build" && cmd != "install" { - io::println("The --linker option can only be used with the build or install commands."); + println("The --linker option can only be used with the build or install commands."); return true; } if flags.link_args.is_some() && cmd != "build" && cmd != "install" { - io::println("The --link-args option can only be used with the build or install commands."); + println("The --link-args option can only be used with the build or install commands."); return true; } if !cfgs.is_empty() && cmd != "build" && cmd != "install" { - io::println("The --cfg option can only be used with the build or install commands."); + println("The --cfg option can only be used with the build or install commands."); return true; } if user_supplied_opt_level && cmd != "build" && cmd != "install" { - io::println("The -O and --opt-level options can only be used with the build \ + println("The -O and --opt-level options can only be used with the build \ or install commands."); return true; } if flags.save_temps && cmd != "build" && cmd != "install" { - io::println("The --save-temps option can only be used with the build \ + println("The --save-temps option can only be used with the build \ or install commands."); return true; } if flags.target.is_some() && cmd != "build" && cmd != "install" { - io::println("The --target option can only be used with the build \ + println("The --target option can only be used with the build \ or install commands."); return true; } if flags.target_cpu.is_some() && cmd != "build" && cmd != "install" { - io::println("The --target-cpu option can only be used with the build \ + println("The --target-cpu option can only be used with the build \ or install commands."); return true; } if flags.experimental_features.is_some() && cmd != "build" && cmd != "install" { - io::println("The -Z option can only be used with the build or install commands."); + println("The -Z option can only be used with the build or install commands."); return true; } diff --git a/src/librustpkg/messages.rs b/src/librustpkg/messages.rs index 96c99a7a0f1..79c8ff794ab 100644 --- a/src/librustpkg/messages.rs +++ b/src/librustpkg/messages.rs @@ -9,31 +9,38 @@ // except according to those terms. use extra::term; -use std::io; +use std::rt::io; pub fn note(msg: &str) { - pretty_message(msg, "note: ", term::color::GREEN, io::stdout()) + pretty_message(msg, "note: ", term::color::GREEN, + @mut io::stdout() as @mut io::Writer) } pub fn warn(msg: &str) { - pretty_message(msg, "warning: ", term::color::YELLOW, io::stdout()) + pretty_message(msg, "warning: ", term::color::YELLOW, + @mut io::stdout() as @mut io::Writer) } pub fn error(msg: &str) { - pretty_message(msg, "error: ", term::color::RED, io::stdout()) + pretty_message(msg, "error: ", term::color::RED, + @mut io::stdout() as @mut io::Writer) } -fn pretty_message<'a>(msg: &'a str, prefix: &'a str, color: term::color::Color, out: @io::Writer) { +fn pretty_message<'a>(msg: &'a str, + prefix: &'a str, + color: term::color::Color, + out: @mut io::Writer) { let term = term::Terminal::new(out); match term { Ok(ref t) => { t.fg(color); - out.write_str(prefix); + out.write(prefix.as_bytes()); t.reset(); }, _ => { - out.write_str(prefix); + out.write(prefix.as_bytes()); } } - out.write_line(msg); + out.write(msg.as_bytes()); + out.write(['\n' as u8]); } diff --git a/src/librustpkg/rustpkg.rs b/src/librustpkg/rustpkg.rs index 2c1fdccd13c..bd3a1b2f672 100644 --- a/src/librustpkg/rustpkg.rs +++ b/src/librustpkg/rustpkg.rs @@ -24,7 +24,7 @@ extern mod extra; extern mod rustc; extern mod syntax; -use std::{io, os, result, run, str, task}; +use std::{os, result, run, str, task}; pub use std::path::Path; use extra::workcache; @@ -346,7 +346,7 @@ impl CtxMethods for BuildContext { } } "list" => { - io::println("Installed packages:"); + println("Installed packages:"); do installed_packages::list_installed_packages |pkg_id| { do pkg_id.path.display().with_str |s| { println(s); @@ -726,7 +726,7 @@ impl CtxMethods for BuildContext { } pub fn main() { - io::println("WARNING: The Rust package manager is experimental and may be unstable"); + println("WARNING: The Rust package manager is experimental and may be unstable"); os::set_exit_status(main_args(os::args())); } diff --git a/src/librustpkg/source_control.rs b/src/librustpkg/source_control.rs index 9a571e07570..c3e4205dfc9 100644 --- a/src/librustpkg/source_control.rs +++ b/src/librustpkg/source_control.rs @@ -10,7 +10,7 @@ // Utils for working with version control repositories. Just git right now. -use std::{io, os, run, str}; +use std::{os, run, str}; use std::run::{ProcessOutput, ProcessOptions, Process}; use extra::tempfile::TempDir; use version::*; @@ -36,8 +36,8 @@ pub fn safe_git_clone(source: &Path, v: &Version, target: &Path) -> CloneResult source.as_str().unwrap().to_owned(), target.as_str().unwrap().to_owned()]); if outp.status != 0 { - io::println(str::from_utf8_owned(outp.output.clone())); - io::println(str::from_utf8_owned(outp.error)); + println(str::from_utf8_owned(outp.output.clone())); + println(str::from_utf8_owned(outp.error)); return DirToUse(target.clone()); } else { @@ -52,8 +52,8 @@ pub fn safe_git_clone(source: &Path, v: &Version, target: &Path) -> CloneResult format!("--git-dir={}", git_dir.as_str().unwrap().to_owned()), ~"checkout", format!("{}", *s)]); if outp.status != 0 { - io::println(str::from_utf8_owned(outp.output.clone())); - io::println(str::from_utf8_owned(outp.error)); + println(str::from_utf8_owned(outp.output.clone())); + println(str::from_utf8_owned(outp.error)); return DirToUse(target.clone()); } } diff --git a/src/librustpkg/testsuite/fail/src/no-inferred-crates/src/zzyzx.rs b/src/librustpkg/testsuite/fail/src/no-inferred-crates/src/zzyzx.rs index 0fd68ca3a20..6c9a63fe7bd 100644 --- a/src/librustpkg/testsuite/fail/src/no-inferred-crates/src/zzyzx.rs +++ b/src/librustpkg/testsuite/fail/src/no-inferred-crates/src/zzyzx.rs @@ -15,8 +15,6 @@ The test runner should check that, after `rustpkg build hello-world`: * testsuite/hello-world/build/ does not contain a library */ -use std::io; - fn main() { - io::println(~"Hello world!"); + println(~"Hello world!"); } diff --git a/src/librustpkg/testsuite/pass/src/hello-world/main.rs b/src/librustpkg/testsuite/pass/src/hello-world/main.rs index c8b2ce97c0c..d4c65954fe6 100644 --- a/src/librustpkg/testsuite/pass/src/hello-world/main.rs +++ b/src/librustpkg/testsuite/pass/src/hello-world/main.rs @@ -18,8 +18,6 @@ The test runner should check that, after `rustpkg build hello-world`: * testsuite/pass/hello-world/build is empty */ -use std::io; - fn main() { - io::println(~"Hello world!"); + println(~"Hello world!"); } diff --git a/src/librustpkg/usage.rs b/src/librustpkg/usage.rs index 4b10451c813..ef6ac485b72 100644 --- a/src/librustpkg/usage.rs +++ b/src/librustpkg/usage.rs @@ -8,10 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; - pub fn general() { - io::println("Usage: rustpkg [options] [args..] + println("Usage: rustpkg [options] [args..] Where is one of: build, clean, do, info, install, list, prefer, test, uninstall, unprefer @@ -24,7 +22,7 @@ Options: } pub fn build() { - io::println("rustpkg build [options..] [package-ID] + println("rustpkg build [options..] [package-ID] Build the given package ID if specified. With no package ID argument, build the package in the current directory. In that case, the current @@ -50,21 +48,21 @@ Options: } pub fn clean() { - io::println("rustpkg clean + println("rustpkg clean Remove all build files in the work cache for the package in the current directory."); } pub fn do_cmd() { - io::println("rustpkg do + println("rustpkg do Runs a command in the package script. You can listen to a command by tagging a function with the attribute `#[pkg_do(cmd)]`."); } pub fn info() { - io::println("rustpkg [options..] info + println("rustpkg [options..] info Probe the package script in the current directory for information. @@ -73,13 +71,13 @@ Options: } pub fn list() { - io::println("rustpkg list + println("rustpkg list List all installed packages."); } pub fn install() { - io::println("rustpkg install [options..] [package-ID] + println("rustpkg install [options..] [package-ID] Install the given package ID if specified. With no package ID argument, install the package in the current directory. @@ -105,14 +103,14 @@ Options: } pub fn uninstall() { - io::println("rustpkg uninstall [@version] + println("rustpkg uninstall [@version] Remove a package by id or name and optionally version. If the package(s) is/are depended on by another package then they cannot be removed."); } pub fn prefer() { - io::println("rustpkg [options..] prefer [@version] + println("rustpkg [options..] prefer [@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to @@ -130,7 +128,7 @@ Example: } pub fn unprefer() { - io::println("rustpkg [options..] unprefer [@version] + println("rustpkg [options..] unprefer [@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version @@ -139,7 +137,7 @@ information."); } pub fn test() { - io::println("rustpkg [options..] test + println("rustpkg [options..] test Build all test crates in the current directory with the test flag. Then, run all the resulting test executables, redirecting the output @@ -150,7 +148,7 @@ Options: } pub fn init() { - io::println("rustpkg init + println("rustpkg init This will turn the current working directory into a workspace. The first command you run when starting off a new project. diff --git a/src/librustpkg/workcache_support.rs b/src/librustpkg/workcache_support.rs index d49a581e070..b68e42d8ebe 100644 --- a/src/librustpkg/workcache_support.rs +++ b/src/librustpkg/workcache_support.rs @@ -8,21 +8,27 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; + use extra::sha1::Sha1; use extra::digest::Digest; use extra::workcache; -use std::io; /// Hashes the file contents along with the last-modified time pub fn digest_file_with_date(path: &Path) -> ~str { use conditions::bad_path::cond; use cond1 = conditions::bad_stat::cond; - let s = io::read_whole_file_str(path); - match s { - Ok(s) => { + let mut err = None; + let bytes = do io::io_error::cond.trap(|e| err = Some(e)).inside { + path.open_reader(io::Open).read_to_end() + }; + match err { + None => { let mut sha = Sha1::new(); - sha.input_str(s); + sha.input(bytes); let st = match path.stat() { Some(st) => st, None => cond1.raise((path.clone(), format!("Couldn't get file access time"))) @@ -30,11 +36,9 @@ pub fn digest_file_with_date(path: &Path) -> ~str { sha.input_str(st.modified.to_str()); sha.result_str() } - Err(e) => { - let path = cond.raise((path.clone(), format!("Couldn't read file: {}", e))); - // FIXME (#9639): This needs to handle non-utf8 paths - // XXX: I'm pretty sure this is the wrong return value - path.as_str().unwrap().to_owned() + Some(e) => { + cond.raise((path.clone(), format!("Couldn't read file: {}", e.desc))); + ~"" } } } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 4e55c5fe60e..2ffe654d3bd 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -65,15 +65,17 @@ use ptr; use result::{Result, Ok, Err}; use str::{StrSlice, OwnedStr}; use str; -use to_str::ToStr; use uint; use vec::{MutableVector, ImmutableVector, OwnedVector, OwnedCopyableVector, CopyableVector}; use vec; -#[allow(non_camel_case_types)] // not sure what to do about this -pub type fd_t = c_int; +#[cfg(stage0)] +pub use rt::io::stdio::{print, println}; -pub mod rustrt { +#[allow(non_camel_case_types)] // not sure what to do about this +type fd_t = c_int; + +mod rustrt { use libc; #[link_name = "rustrt"] @@ -1013,7 +1015,7 @@ pub struct FILERes { } impl FILERes { - pub fn new(f: *libc::FILE) -> FILERes { + fn new(f: *libc::FILE) -> FILERes { FILERes { f: f } } } @@ -1028,37 +1030,6 @@ impl Drop for FILERes { } } -pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> @Reader { - if cleanup { - @Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader - } else { - @f as @Reader - } -} - -// FIXME (#2004): this should either be an trait-less impl, a set of -// top-level functions that take a reader, or a set of default methods on -// reader (which can then be called reader) - -/** -* Gives a `Reader` that allows you to read values from standard input. -* -* # Example -* -* ```rust -* let stdin = std::io::stdin(); -* let line = stdin.read_line(); -* std::io::print(line); -* ``` -*/ -pub fn stdin() -> @Reader { - #[fixed_stack_segment]; #[inline(never)]; - - unsafe { - @rustrt::rust_get_stdin() as @Reader - } -} - pub fn file_reader(path: &Path) -> Result<@Reader, ~str> { #[fixed_stack_segment]; #[inline(never)]; @@ -1073,71 +1044,10 @@ pub fn file_reader(path: &Path) -> Result<@Reader, ~str> { Err(~"error opening " + p) } } else { - Ok(FILE_reader(f, true)) + Ok(@Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader) } } - -// Byte readers -pub struct BytesReader { - // FIXME(#5723) see other FIXME below - // FIXME(#7268) this should also be parameterized over <'self> - bytes: &'static [u8], - pos: @mut uint -} - -impl Reader for BytesReader { - fn read(&self, bytes: &mut [u8], len: uint) -> uint { - let count = num::min(len, self.bytes.len() - *self.pos); - - let view = self.bytes.slice(*self.pos, self.bytes.len()); - vec::bytes::copy_memory(bytes, view, count); - - *self.pos += count; - - count - } - - fn read_byte(&self) -> int { - if *self.pos == self.bytes.len() { - return -1; - } - - let b = self.bytes[*self.pos]; - *self.pos += 1u; - b as int - } - - fn eof(&self) -> bool { - *self.pos == self.bytes.len() - } - - fn seek(&self, offset: int, whence: SeekStyle) { - let pos = *self.pos; - *self.pos = seek_in_buf(offset, pos, self.bytes.len(), whence); - } - - fn tell(&self) -> uint { - *self.pos - } -} - -pub fn with_bytes_reader(bytes: &[u8], f: &fn(@Reader) -> T) -> T { - // XXX XXX XXX this is glaringly unsound - // FIXME(#5723) Use a &Reader for the callback's argument. Should be: - // fn with_bytes_reader<'r, T>(bytes: &'r [u8], f: &fn(&'r Reader) -> T) -> T - let bytes: &'static [u8] = unsafe { cast::transmute(bytes) }; - f(@BytesReader { - bytes: bytes, - pos: @mut 0 - } as @Reader) -} - -pub fn with_str_reader(s: &str, f: &fn(@Reader) -> T) -> T { - // FIXME(#5723): As above. - with_bytes_reader(s.as_bytes(), f) -} - // Writing pub enum FileFlag { Append, Create, Truncate, NoFlag, } @@ -1286,7 +1196,7 @@ pub struct FdRes { } impl FdRes { - pub fn new(fd: fd_t) -> FdRes { + fn new(fd: fd_t) -> FdRes { FdRes { fd: fd } } } @@ -1301,15 +1211,6 @@ impl Drop for FdRes { } } -pub fn fd_writer(fd: fd_t, cleanup: bool) -> @Writer { - if cleanup { - @Wrapper { base: fd, cleanup: FdRes::new(fd) } as @Writer - } else { - @fd as @Writer - } -} - - pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> { #[fixed_stack_segment]; #[inline(never)]; @@ -1339,7 +1240,7 @@ pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) if fd < (0 as c_int) { Err(format!("error opening {}: {}", path.display(), os::last_os_error())) } else { - Ok(fd_writer(fd, true)) + Ok(@Wrapper { base: fd, cleanup: FdRes::new(fd) } as @Writer) } } @@ -1615,64 +1516,6 @@ pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> { // FIXME (#2004) why are these different from the way stdin() is // implemented? - -/** -* Gives a `Writer` which allows you to write to the standard output. -* -* # Example -* -* ```rust -* let stdout = std::io::stdout(); -* stdout.write_str("hello\n"); -* ``` -*/ -pub fn stdout() -> @Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) } - -/** -* Gives a `Writer` which allows you to write to standard error. -* -* # Example -* -* ```rust -* let stderr = std::io::stderr(); -* stderr.write_str("hello\n"); -* ``` -*/ -pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) } - -/** -* Prints a string to standard output. -* -* This string will not have an implicit newline at the end. If you want -* an implicit newline, please see `println`. -* -* # Example -* -* ```rust -* // print is imported into the prelude, and so is always available. -* print("hello"); -* ``` -*/ -pub fn print(s: &str) { - stdout().write_str(s); -} - -/** -* Prints a string to standard output, followed by a newline. -* -* If you do not want an implicit newline, please see `print`. -* -* # Example -* -* ```rust -* // println is imported into the prelude, and so is always available. -* println("hello"); -* ``` -*/ -pub fn println(s: &str) { - stdout().write_line(s); -} - pub struct BytesWriter { bytes: @mut ~[u8], pos: @mut uint, @@ -1736,7 +1579,7 @@ pub fn with_str_writer(f: &fn(@Writer)) -> ~str { } // Utility functions -pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) -> +fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) -> uint { let mut bpos = pos as int; let blen = len as int; @@ -1749,137 +1592,6 @@ pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) -> return bpos as uint; } -pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> { - do read_whole_file(file).and_then |bytes| { - if str::is_utf8(bytes) { - Ok(str::from_utf8(bytes)) - } else { - Err(file.display().to_str() + " is not UTF-8") - } - } -} - -// FIXME (#2004): implement this in a low-level way. Going through the -// abstractions is pointless. -pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> { - do file_reader(file).and_then |rdr| { - Ok(rdr.read_whole_stream()) - } -} - -// fsync related - -pub mod fsync { - use io::{FILERes, FdRes, fd_t}; - use libc; - use ops::Drop; - use option::{None, Option, Some}; - use os; - - pub enum Level { - // whatever fsync does on that platform - FSync, - - // fdatasync on linux, similiar or more on other platforms - FDataSync, - - // full fsync - // - // You must additionally sync the parent directory as well! - FullFSync, - } - - - // Artifacts that need to fsync on destruction - pub struct Res { - priv arg: Arg, - } - - impl Res { - pub fn new(arg: Arg) -> Res { - Res { arg: arg } - } - } - - #[unsafe_destructor] - impl Drop for Res { - fn drop(&mut self) { - match self.arg.opt_level { - None => (), - Some(level) => { - // fail hard if not succesful - assert!(((self.arg.fsync_fn)(&self.arg.val, level) != -1)); - } - } - } - } - - pub struct Arg { - priv val: t, - priv opt_level: Option, - priv fsync_fn: extern "Rust" fn(f: &t, Level) -> int, - } - - // fsync file after executing blk - // FIXME (#2004) find better way to create resources within lifetime of - // outer res - pub fn FILE_res_sync(file: &FILERes, - opt_level: Option, - blk: &fn(v: Res<*libc::FILE>)) { - blk(Res::new(Arg { - val: file.f, - opt_level: opt_level, - fsync_fn: fsync_FILE, - })); - - fn fileno(stream: *libc::FILE) -> libc::c_int { - #[fixed_stack_segment]; #[inline(never)]; - unsafe { libc::fileno(stream) } - } - - fn fsync_FILE(stream: &*libc::FILE, level: Level) -> int { - fsync_fd(fileno(*stream), level) - } - } - - // fsync fd after executing blk - pub fn fd_res_sync(fd: &FdRes, opt_level: Option, - blk: &fn(v: Res)) { - blk(Res::new(Arg { - val: fd.fd, - opt_level: opt_level, - fsync_fn: fsync_fd_helper, - })); - } - - fn fsync_fd(fd: libc::c_int, level: Level) -> int { - #[fixed_stack_segment]; #[inline(never)]; - - os::fsync_fd(fd, level) as int - } - - fn fsync_fd_helper(fd_ptr: &libc::c_int, level: Level) -> int { - fsync_fd(*fd_ptr, level) - } - - // Type of objects that may want to fsync - pub trait FSyncable { fn fsync(&self, l: Level) -> int; } - - // Call o.fsync after executing blk - pub fn obj_sync(o: @FSyncable, opt_level: Option, - blk: &fn(v: Res<@FSyncable>)) { - blk(Res::new(Arg { - val: o, - opt_level: opt_level, - fsync_fn: obj_fsync_fn, - })); - } - - fn obj_fsync_fn(o: &@FSyncable, level: Level) -> int { - (*o).fsync(level) - } -} - #[cfg(test)] mod tests { use prelude::*; @@ -1934,82 +1646,6 @@ mod tests { } } - #[test] - fn test_readchars_empty() { - do io::with_str_reader("") |inp| { - let res : ~[char] = inp.read_chars(128); - assert_eq!(res.len(), 0); - } - } - - #[test] - fn test_read_line_utf8() { - do io::with_str_reader("生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| { - let line = inp.read_line(); - assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤"); - } - } - - #[test] - fn test_read_lines() { - do io::with_str_reader("a\nb\nc\n") |inp| { - assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); - } - - do io::with_str_reader("a\nb\nc") |inp| { - assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); - } - - do io::with_str_reader("") |inp| { - assert!(inp.read_lines().is_empty()); - } - } - - #[test] - fn test_readchars_wide() { - let wide_test = ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤"; - let ivals : ~[int] = ~[ - 29983, 38152, 30340, 27748, - 21273, 20999, 32905, 27748, - 104, 101, 108, 108, 111, - 29983, 38152, 30340, 27748, - 21273, 20999, 32905, 27748]; - fn check_read_ln(len : uint, s: &str, ivals: &[int]) { - do io::with_str_reader(s) |inp| { - let res : ~[char] = inp.read_chars(len); - if len <= ivals.len() { - assert_eq!(res.len(), len); - } - for (iv, c) in ivals.iter().zip(res.iter()) { - assert!(*iv == *c as int) - } - } - } - let mut i = 0; - while i < 8 { - check_read_ln(i, wide_test, ivals); - i += 1; - } - // check a long read for good measure - check_read_ln(128, wide_test, ivals); - } - - #[test] - fn test_readchar() { - do io::with_str_reader("生") |inp| { - let res = inp.read_char(); - assert_eq!(res as int, 29983); - } - } - - #[test] - fn test_readchar_empty() { - do io::with_str_reader("") |inp| { - let res = inp.read_char(); - assert_eq!(res, unsafe { transmute(-1u32) }); // FIXME: #8971: unsound - } - } - #[test] fn file_reader_not_exist() { match io::file_reader(&Path::new("not a file")) { diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 65190c5d8d6..99930b39a65 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -32,7 +32,6 @@ use c_str::CString; use clone::Clone; use container::Container; -use io; use iter::range; use libc; use libc::{c_char, c_void, c_int, size_t}; @@ -356,64 +355,6 @@ pub fn fdopen(fd: c_int) -> *FILE { } } - -// fsync related - -#[cfg(windows)] -pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int { - #[fixed_stack_segment]; #[inline(never)]; - unsafe { - use libc::funcs::extra::msvcrt::*; - return commit(fd); - } -} - -#[cfg(target_os = "linux")] -#[cfg(target_os = "android")] -pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int { - #[fixed_stack_segment]; #[inline(never)]; - unsafe { - use libc::funcs::posix01::unistd::*; - match level { - io::fsync::FSync - | io::fsync::FullFSync => return fsync(fd), - io::fsync::FDataSync => return fdatasync(fd) - } - } -} - -#[cfg(target_os = "macos")] -pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int { - #[fixed_stack_segment]; #[inline(never)]; - - unsafe { - use libc::consts::os::extra::*; - use libc::funcs::posix88::fcntl::*; - use libc::funcs::posix01::unistd::*; - match level { - io::fsync::FSync => return fsync(fd), - _ => { - // According to man fnctl, the ok retval is only specified to be - // !=-1 - if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int) - { return -1 as c_int; } - else - { return 0 as c_int; } - } - } - } -} - -#[cfg(target_os = "freebsd")] -pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int { - #[fixed_stack_segment]; #[inline(never)]; - - unsafe { - use libc::funcs::posix01::unistd::*; - return fsync(fd); - } -} - pub struct Pipe { input: c_int, out: c_int diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 1d9d5512ff4..456d344b838 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -962,7 +962,6 @@ pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> boo mod test { use ast::*; use super::*; - use std::io; use opt_vec; use std::hashmap::HashMap; @@ -1137,7 +1136,7 @@ mod test { // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: - io::println("about to run bad test"); + println("about to run bad test"); { let sc = unfold_test_sc(~[R(id(a,EMPTY_CTXT),50), R(id(a,EMPTY_CTXT),51)], EMPTY_CTXT,&mut t); diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index bbbaf2a2f60..736f92910af 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -11,7 +11,7 @@ use codemap::{Pos, Span}; use codemap; -use std::io; +use std::rt::io; use std::local_data; use extra::term; @@ -199,9 +199,14 @@ fn diagnosticcolor(lvl: level) -> term::color::Color { fn print_maybe_styled(msg: &str, color: term::attr::Attr) { local_data_key!(tls_terminal: @Option) - let stderr = io::stderr(); + let stderr = @mut io::stderr() as @mut io::Writer; + fn is_stderr_screen() -> bool { + #[fixed_stack_segment]; + use std::libc; + unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } + } - if stderr.get_type() == io::Screen { + if is_stderr_screen() { let t = match local_data::get(tls_terminal, |v| v.map(|k| *k)) { None => { let t = term::Terminal::new(stderr); @@ -218,21 +223,21 @@ fn print_maybe_styled(msg: &str, color: term::attr::Attr) { match t { &Some(ref term) => { term.attr(color); - stderr.write_str(msg); + write!(stderr, "{}", msg); term.reset(); }, - _ => stderr.write_str(msg) + _ => write!(stderr, "{}", msg) } } else { - stderr.write_str(msg); + write!(stderr, "{}", msg); } } fn print_diagnostic(topic: &str, lvl: level, msg: &str) { - let stderr = io::stderr(); + let mut stderr = io::stderr(); if !topic.is_empty() { - stderr.write_str(format!("{} ", topic)); + write!(&mut stderr as &mut io::Writer, "{} ", topic); } print_maybe_styled(format!("{}: ", diagnosticstr(lvl)), @@ -266,6 +271,8 @@ fn highlight_lines(cm: @codemap::CodeMap, lvl: level, lines: @codemap::FileLines) { let fm = lines.file; + let mut err = io::stderr(); + let err = &mut err as &mut io::Writer; // arbitrarily only print up to six lines of the error let max_lines = 6u; @@ -277,21 +284,12 @@ fn highlight_lines(cm: @codemap::CodeMap, } // Print the offending lines for line in display_lines.iter() { - io::stderr().write_str(format!("{}:{} ", fm.name, *line + 1u)); - let s = fm.get_line(*line as int) + "\n"; - io::stderr().write_str(s); + write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int)); } if elided { let last_line = display_lines[display_lines.len() - 1u]; let s = format!("{}:{} ", fm.name, last_line + 1u); - let mut indent = s.len(); - let mut out = ~""; - while indent > 0u { - out.push_char(' '); - indent -= 1u; - } - out.push_str("...\n"); - io::stderr().write_str(out); + write!(err, "{0:1$}...\n", "", s.len()); } // FIXME (#3260) @@ -325,7 +323,7 @@ fn highlight_lines(cm: @codemap::CodeMap, _ => s.push_char(' '), }; } - io::stderr().write_str(s); + write!(err, "{}", s); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 1018e79aabc..99bcb36eedb 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1524,7 +1524,8 @@ mod test { } fn fake_print_crate(crate: &ast::Crate) { - let s = pprust::rust_printer(std::io::stderr(),get_ident_interner()); + let out = @mut std::rt::io::stderr() as @mut std::rt::io::Writer; + let s = pprust::rust_printer(out, get_ident_interner()); pprust::print_crate_(s, crate); } @@ -1536,7 +1537,7 @@ mod test { //fn expand_and_resolve(crate_str: @str) -> ast::crate { //let expanded_ast = expand_crate_str(crate_str); - // std::io::println(format!("expanded: {:?}\n",expanded_ast)); + // println(format!("expanded: {:?}\n",expanded_ast)); //mtwt_resolve_crate(expanded_ast) //} //fn expand_and_resolve_and_pretty_print (crate_str : @str) -> ~str { @@ -1645,9 +1646,9 @@ mod test { let varref_marks = mtwt_marksof(varref.segments[0].identifier.ctxt, invalid_name); if (!(varref_name==binding_name)){ - std::io::println("uh oh, should match but doesn't:"); - std::io::println(format!("varref: {:?}",varref)); - std::io::println(format!("binding: {:?}", bindings[binding_idx])); + println("uh oh, should match but doesn't:"); + println!("varref: {:?}",varref); + println!("binding: {:?}", bindings[binding_idx]); ast_util::display_sctable(get_sctable()); } assert_eq!(varref_name,binding_name); @@ -1665,12 +1666,12 @@ mod test { println!("text of test case: \"{}\"", teststr); println!(""); println!("uh oh, matches but shouldn't:"); - std::io::println(format!("varref: {:?}",varref)); + println!("varref: {:?}",varref); // good lord, you can't make a path with 0 segments, can you? println!("varref's first segment's uint: {}, and string: \"{}\"", varref.segments[0].identifier.name, ident_to_str(&varref.segments[0].identifier)); - std::io::println(format!("binding: {:?}", bindings[binding_idx])); + println!("binding: {:?}", bindings[binding_idx]); ast_util::display_sctable(get_sctable()); } assert!(!fail); @@ -1703,17 +1704,17 @@ foo_module!() && (@"xx" == (ident_to_str(&p.segments[0].identifier))) }).enumerate() { if (mtwt_resolve(v.segments[0].identifier) != resolved_binding) { - std::io::println("uh oh, xx binding didn't match xx varref:"); - std::io::println(format!("this is xx varref \\# {:?}",idx)); - std::io::println(format!("binding: {:?}",cxbind)); - std::io::println(format!("resolves to: {:?}",resolved_binding)); - std::io::println(format!("varref: {:?}",v.segments[0].identifier)); - std::io::println(format!("resolves to: {:?}", - mtwt_resolve(v.segments[0].identifier))); + println("uh oh, xx binding didn't match xx varref:"); + println!("this is xx varref \\# {:?}",idx); + println!("binding: {:?}",cxbind); + println!("resolves to: {:?}",resolved_binding); + println!("varref: {:?}",v.segments[0].identifier); + println!("resolves to: {:?}", + mtwt_resolve(v.segments[0].identifier)); let table = get_sctable(); - std::io::println("SC table:"); + println("SC table:"); for (idx,val) in table.table.iter().enumerate() { - std::io::println(format!("{:4u} : {:?}",idx,val)); + println!("{:4u} : {:?}",idx,val); } } assert_eq!(mtwt_resolve(v.segments[0].identifier),resolved_binding); diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index 52807009073..3e07b16221e 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -15,15 +15,13 @@ use ext::base; use print; use parse::token::{get_ident_interner}; -use std::io; - pub fn expand_syntax_ext(cx: @ExtCtxt, sp: codemap::Span, tt: &[ast::token_tree]) -> base::MacResult { cx.print_backtrace(); - io::stdout().write_line( + println( print::pprust::tt_to_str( &ast::tt_delim(@mut tt.to_owned()), get_ident_interner())); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index dcfeb99365a..df177cf75dc 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -19,8 +19,10 @@ use parse; use parse::token::{get_ident_interner}; use print::pprust; -use std::io; -use std::result; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; +use std::str; // These macros all relate to the file system; they either return // the column/row/filename of the expression, or they include @@ -89,14 +91,23 @@ pub fn expand_include(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) pub fn expand_include_str(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) -> base::MacResult { let file = get_single_str_from_tts(cx, sp, tts, "include_str!"); - let res = io::read_whole_file_str(&res_rel_file(cx, sp, &Path::new(file))); - match res { - result::Ok(res) => { - base::MRExpr(cx.expr_str(sp, res.to_managed())) - } - result::Err(e) => { - cx.span_fatal(sp, e); - } + let file = res_rel_file(cx, sp, &Path::new(file)); + let mut error = None; + let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { + file.open_reader(io::Open).read_to_end() + }; + match error { + Some(e) => { + cx.span_fatal(sp, format!("couldn't read {}: {}", + file.display(), e.desc)); + } + None => {} + } + match str::from_utf8_owned_opt(bytes) { + Some(s) => base::MRExpr(cx.expr_str(sp, s.to_managed())), + None => { + cx.span_fatal(sp, format!("{} wasn't a utf-8 file", file.display())); + } } } @@ -106,13 +117,21 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: Span, tts: &[ast::token_tree]) use std::at_vec; let file = get_single_str_from_tts(cx, sp, tts, "include_bin!"); - match io::read_whole_file(&res_rel_file(cx, sp, &Path::new(file))) { - result::Ok(src) => { - let v = at_vec::to_managed_move(src); - base::MRExpr(cx.expr_lit(sp, ast::lit_binary(v))) + let file = res_rel_file(cx, sp, &Path::new(file)); + + let mut error = None; + let bytes = do io::read_error::cond.trap(|e| error = Some(e)).inside { + do io::io_error::cond.trap(|e| error = Some(e)).inside { + file.open_reader(io::Open).read_to_end() } - result::Err(ref e) => { - cx.parse_sess().span_diagnostic.handler().fatal((*e)) + }; + match error { + Some(e) => { + cx.span_fatal(sp, format!("couldn't read {}: {}", + file.display(), e.desc)); + } + None => { + base::MRExpr(cx.expr_lit(sp, ast::lit_binary(bytes))) } } } diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index 38921648a2b..e9e6eb872c8 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -18,7 +18,8 @@ use parse::lexer; use parse::token; use parse::token::{get_ident_interner}; -use std::io; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; use std::str; use std::uint; @@ -346,9 +347,9 @@ pub struct lit { pub fn gather_comments_and_literals(span_diagnostic: @mut diagnostic::span_handler, path: @str, - srdr: @io::Reader) + mut srdr: &mut io::Reader) -> (~[cmnt], ~[lit]) { - let src = str::from_utf8(srdr.read_whole_stream()).to_managed(); + let src = str::from_utf8(srdr.read_to_end()).to_managed(); let cm = CodeMap::new(); let filemap = cm.new_filemap(path, src); let rdr = lexer::new_low_level_string_reader(span_diagnostic, filemap); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index c9405d72464..93e5d3dd772 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -19,8 +19,11 @@ use parse::attr::parser_attr; use parse::lexer::reader; use parse::parser::Parser; -use std::io; use std::path::Path; +use std::rt::io; +use std::rt::io::extensions::ReaderUtil; +use std::rt::io::file::FileInfo; +use std::str; pub mod lexer; pub mod parser; @@ -260,16 +263,34 @@ pub fn new_parser_from_tts(sess: @mut ParseSess, /// add the path to the session's codemap and return the new filemap. pub fn file_to_filemap(sess: @mut ParseSess, path: &Path, spanopt: Option) -> @FileMap { - match io::read_whole_file_str(path) { - // FIXME (#9639): This needs to handle non-utf8 paths - Ok(src) => string_to_filemap(sess, src.to_managed(), path.as_str().unwrap().to_managed()), - Err(e) => { - match spanopt { - Some(span) => sess.span_diagnostic.span_fatal(span, e), - None => sess.span_diagnostic.handler().fatal(e) - } + let err = |msg: &str| { + match spanopt { + Some(sp) => sess.span_diagnostic.span_fatal(sp, msg), + None => sess.span_diagnostic.handler().fatal(msg), + } + }; + let mut error = None; + let bytes = do io::io_error::cond.trap(|e| error = Some(e)).inside { + do io::read_error::cond.trap(|e| error = Some(e)).inside { + path.open_reader(io::Open).read_to_end() + } + }; + match error { + Some(e) => { + err(format!("couldn't read {}: {}", path.display(), e.desc)); + } + None => {} + } + match str::from_utf8_owned_opt(bytes) { + Some(s) => { + return string_to_filemap(sess, s.to_managed(), + path.as_str().unwrap().to_managed()); + } + None => { + err(format!("{} is not UTF-8 encoded", path.display())) } } + unreachable!() } // given a session and a string, add the string to @@ -318,7 +339,10 @@ mod test { use super::*; use extra::serialize::Encodable; use extra; - use std::io; + use std::rt::io; + use std::rt::io::Decorator; + use std::rt::io::mem::MemWriter; + use std::str; use codemap::{Span, BytePos, Spanned}; use opt_vec; use ast; @@ -330,10 +354,10 @@ mod test { use util::parser_testing::string_to_stmt; #[cfg(test)] fn to_json_str>(val: @E) -> ~str { - do io::with_str_writer |writer| { - let mut encoder = extra::json::Encoder(writer); - val.encode(&mut encoder); - } + let writer = @mut MemWriter::new(); + let mut encoder = extra::json::Encoder(writer as @mut io::Writer); + val.encode(&mut encoder); + str::from_utf8(*writer.inner_ref()) } // produce a codemap::span diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 871584003b5..4801fa21fc4 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -61,7 +61,7 @@ * avoid combining it with other lines and making matters even worse. */ -use std::io; +use std::rt::io; use std::vec; #[deriving(Clone, Eq)] @@ -148,7 +148,7 @@ pub struct print_stack_elt { pub static size_infinity: int = 0xffff; -pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { +pub fn mk_printer(out: @mut io::Writer, linewidth: uint) -> @mut Printer { // Yes 3, it makes the ring buffers big enough to never // fall behind. let n: uint = 3 * linewidth; @@ -157,7 +157,7 @@ pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { let size: ~[int] = vec::from_elem(n, 0); let scan_stack: ~[uint] = vec::from_elem(n, 0u); @mut Printer { - out: @out, + out: out, buf_len: n, margin: linewidth as int, space: linewidth as int, @@ -255,7 +255,7 @@ pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer { * called 'print'. */ pub struct Printer { - out: @@io::Writer, + out: @mut io::Writer, buf_len: uint, margin: int, // width of lines we're constrained to space: int, // number of spaces left on line @@ -452,7 +452,7 @@ impl Printer { } pub fn print_newline(&mut self, amount: int) { debug!("NEWLINE {}", amount); - (*self.out).write_str("\n"); + write!(self.out, "\n"); self.pending_indentation = 0; self.indent(amount); } @@ -474,10 +474,10 @@ impl Printer { } pub fn print_str(&mut self, s: &str) { while self.pending_indentation > 0 { - (*self.out).write_str(" "); + write!(self.out, " "); self.pending_indentation -= 1; } - (*self.out).write_str(s); + write!(self.out, "{}", s); } pub fn print(&mut self, x: token, L: int) { debug!("print {} {} (remaining line space={})", tok_str(x), L, diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 0e330da31e6..400ff804485 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -28,7 +28,10 @@ use print::pp; use print::pprust; use std::char; -use std::io; +use std::str; +use std::rt::io; +use std::rt::io::Decorator; +use std::rt::io::mem::MemWriter; // The @ps is stored here to prevent recursive type. pub enum ann_node<'self> { @@ -83,11 +86,11 @@ pub fn end(s: @ps) { pp::end(s.s); } -pub fn rust_printer(writer: @io::Writer, intr: @ident_interner) -> @ps { +pub fn rust_printer(writer: @mut io::Writer, intr: @ident_interner) -> @ps { return rust_printer_annotated(writer, intr, @no_ann::new() as @pp_ann); } -pub fn rust_printer_annotated(writer: @io::Writer, +pub fn rust_printer_annotated(writer: @mut io::Writer, intr: @ident_interner, ann: @pp_ann) -> @ps { @@ -118,8 +121,8 @@ pub fn print_crate(cm: @CodeMap, span_diagnostic: @mut diagnostic::span_handler, crate: &ast::Crate, filename: @str, - input: @io::Reader, - out: @io::Writer, + input: @mut io::Reader, + out: @mut io::Writer, ann: @pp_ann, is_expanded: bool) { let (cmnts, lits) = comments::gather_comments_and_literals( @@ -200,26 +203,26 @@ pub fn path_to_str(p: &ast::Path, intr: @ident_interner) -> ~str { pub fn fun_to_str(decl: &ast::fn_decl, purity: ast::purity, name: ast::Ident, opt_explicit_self: Option, generics: &ast::Generics, intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - print_fn(s, decl, Some(purity), AbiSet::Rust(), - name, generics, opt_explicit_self, ast::inherited); - end(s); // Close the head box - end(s); // Close the outer box - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + print_fn(s, decl, Some(purity), AbiSet::Rust(), + name, generics, opt_explicit_self, ast::inherited); + end(s); // Close the head box + end(s); // Close the outer box + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn block_to_str(blk: &ast::Block, intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - // containing cbox, will be closed by print-block at } - cbox(s, indent_unit); - // head-ibox, will be closed by print-block after { - ibox(s, 0u); - print_block(s, blk); - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + // containing cbox, will be closed by print-block at } + cbox(s, indent_unit); + // head-ibox, will be closed by print-block after { + ibox(s, 0u); + print_block(s, blk); + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @ident_interner) -> ~str { @@ -2196,11 +2199,11 @@ pub fn print_string(s: @ps, st: &str, style: ast::StrStyle) { } pub fn to_str(t: &T, f: &fn(@ps, &T), intr: @ident_interner) -> ~str { - do io::with_str_writer |wr| { - let s = rust_printer(wr, intr); - f(s, t); - eof(s.s); - } + let wr = @mut MemWriter::new(); + let s = rust_printer(wr as @mut io::Writer, intr); + f(s, t); + eof(s.s); + str::from_utf8(*wr.inner_ref()) } pub fn next_comment(s: @ps) -> Option { diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index 2d209e40e42..f91327b6a65 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -13,7 +13,6 @@ extern mod extra; use extra::time; use extra::treemap::TreeMap; use std::hashmap::{HashMap, HashSet}; -use std::io; use std::os; use std::rand::{Rng, IsaacRng, SeedableRng}; use std::trie::TrieMap; @@ -28,7 +27,7 @@ fn timed(label: &str, f: &fn()) { } fn ascending>(map: &mut M, n_keys: uint) { - io::println(" Ascending integers:"); + println(" Ascending integers:"); do timed("insert") { for i in range(0u, n_keys) { @@ -50,7 +49,7 @@ fn ascending>(map: &mut M, n_keys: uint) { } fn descending>(map: &mut M, n_keys: uint) { - io::println(" Descending integers:"); + println(" Descending integers:"); do timed("insert") { for i in range(0, n_keys).invert() { @@ -118,7 +117,7 @@ fn main() { println!("{} keys", n_keys); - io::println("\nTreeMap:"); + println("\nTreeMap:"); { let mut map: TreeMap = TreeMap::new(); @@ -131,12 +130,12 @@ fn main() { } { - io::println(" Random integers:"); + println(" Random integers:"); let mut map: TreeMap = TreeMap::new(); vector(&mut map, n_keys, rand); } - io::println("\nHashMap:"); + println("\nHashMap:"); { let mut map: HashMap = HashMap::new(); @@ -149,12 +148,12 @@ fn main() { } { - io::println(" Random integers:"); + println(" Random integers:"); let mut map: HashMap = HashMap::new(); vector(&mut map, n_keys, rand); } - io::println("\nTrieMap:"); + println("\nTrieMap:"); { let mut map: TrieMap = TrieMap::new(); @@ -167,7 +166,7 @@ fn main() { } { - io::println(" Random integers:"); + println(" Random integers:"); let mut map: TrieMap = TrieMap::new(); vector(&mut map, n_keys, rand); } diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index b9a8e74668f..9f65dc1e555 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -13,7 +13,6 @@ extern mod extra; use extra::bitv::BitvSet; use extra::treemap::TreeSet; use std::hashmap::HashSet; -use std::io; use std::os; use std::rand; use std::uint; @@ -123,12 +122,11 @@ impl Results { } fn write_header(header: &str) { - io::stdout().write_str(header); - io::stdout().write_str("\n"); + println(header); } fn write_row(label: &str, value: f64) { - io::stdout().write_str(format!("{:30s} {} s\n", label, value)); + println!("{:30s} {} s\n", label, value); } fn write_results(label: &str, results: &Results) { diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 97479fc133a..2a5971be216 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -22,7 +22,6 @@ extern mod extra; use std::comm::{Port, Chan, SharedChan}; use std::comm; -use std::io; use std::os; use std::task; use std::uint; @@ -90,10 +89,10 @@ fn run(args: &[~str]) { let result = from_child.recv(); let end = extra::time::precise_time_s(); let elapsed = end - start; - io::stdout().write_str(format!("Count is {:?}\n", result)); - io::stdout().write_str(format!("Test took {:?} seconds\n", elapsed)); + print!("Count is {:?}\n", result); + print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); - io::stdout().write_str(format!("Throughput={} per sec\n", thruput)); + print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index 584a8b8befc..1ff531324b3 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -17,7 +17,6 @@ extern mod extra; use std::comm::{SharedChan, Chan, stream}; -use std::io; use std::os; use std::task; use std::uint; @@ -84,10 +83,10 @@ fn run(args: &[~str]) { let result = from_child.recv(); let end = extra::time::precise_time_s(); let elapsed = end - start; - io::stdout().write_str(format!("Count is {:?}\n", result)); - io::stdout().write_str(format!("Test took {:?} seconds\n", elapsed)); + print!("Count is {:?}\n", result); + print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); - io::stdout().write_str(format!("Throughput={} per sec\n", thruput)); + print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 96e87788b70..6bfb731badd 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -14,7 +14,6 @@ extern mod extra; use std::cell::Cell; use std::comm::{stream, SharedChan}; -use std::io; use std::option; use std::os; use std::task; @@ -191,15 +190,15 @@ fn rendezvous(nn: uint, set: ~[color]) { } // print each color in the set - io::println(show_color_list(set)); + println(show_color_list(set)); // print each creature's stats for rep in report.iter() { - io::println(*rep); + println(*rep); } // print the total number of creatures met - io::println(show_number(creatures_met)); + println(show_number(creatures_met)); } fn main() { @@ -215,10 +214,10 @@ fn main() { let nn = from_str::(args[1]).unwrap(); print_complements(); - io::println(""); + println(""); rendezvous(nn, ~[Blue, Red, Yellow]); - io::println(""); + println(""); rendezvous(nn, ~[Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue]); diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index ef1061c780e..3d1362b2f29 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -18,7 +18,7 @@ extern mod extra; use std::int; -use std::io; +use std::rt::io; use std::os; use std::rand::Rng; use std::rand; @@ -68,12 +68,12 @@ fn select_random(r: u32, genelist: ~[AminoAcids]) -> char { bisect(genelist.clone(), 0, genelist.len() - 1, r) } -fn make_random_fasta(wr: @io::Writer, +fn make_random_fasta(wr: @mut io::Writer, id: ~str, desc: ~str, genelist: ~[AminoAcids], n: int) { - wr.write_line(~">" + id + " " + desc); + writeln!(wr, ">{} {}", id, desc); let mut rng = rand::rng(); let rng = @mut MyRandom { last: rng.gen() @@ -83,26 +83,26 @@ fn make_random_fasta(wr: @io::Writer, op.push_char(select_random(myrandom_next(rng, 100u32), genelist.clone())); if op.len() >= LINE_LENGTH { - wr.write_line(op); + writeln!(wr, "{}", op); op = ~""; } } - if op.len() > 0u { wr.write_line(op); } + if op.len() > 0u { writeln!(wr, "{}", op); } } -fn make_repeat_fasta(wr: @io::Writer, id: ~str, desc: ~str, s: ~str, n: int) { - wr.write_line(~">" + id + " " + desc); +fn make_repeat_fasta(wr: @mut io::Writer, id: ~str, desc: ~str, s: ~str, n: int) { + writeln!(wr, ">{} {}", id, desc); let mut op = str::with_capacity( LINE_LENGTH ); let sl = s.len(); for i in range(0u, n as uint) { if (op.len() >= LINE_LENGTH) { - wr.write_line( op ); + writeln!(wr, "{}", op); op = str::with_capacity( LINE_LENGTH ); } op.push_char( s[i % sl] as char ); } if op.len() > 0 { - wr.write_line(op) + writeln!(wr, "{}", op); } } @@ -122,10 +122,10 @@ fn main() { }; let writer = if os::getenv("RUST_BENCH").is_some() { - io::file_writer(&Path::new("./shootout-fasta.data"), - [io::Truncate, io::Create]).unwrap() + let file = "./shootout-fasta.data".open_writer(io::CreateOrTruncate); + @mut file as @mut io::Writer } else { - io::stdout() + @mut io::stdout() as @mut io::Writer }; let n = from_str::(args[1]).unwrap(); diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 59dd0846b59..83a0fbd42ce 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -18,8 +18,6 @@ use std::cmp::Ord; use std::comm::{stream, Port, Chan}; use std::comm; use std::hashmap::HashMap; -use std::io::ReaderUtil; -use std::io; use std::option; use std::os; use std::str; @@ -237,6 +235,6 @@ fn main() { // now fetch and print result messages for (ii, _sz) in sizes.iter().enumerate() { - io::println(from_child[ii].recv()); + println(from_child[ii].recv()); } } diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 88b3cfdff42..b3c3fa4db6f 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -23,8 +23,6 @@ extern mod extra; use extra::{time, getopts}; use std::comm::{stream, SharedChan}; -use std::io::WriterUtil; -use std::io; use std::os; use std::result::{Ok, Err}; use std::task; @@ -113,8 +111,6 @@ fn main() { let num_trials = 10; - let out = io::stdout(); - for n in range(1, max + 1) { for _ in range(0, num_trials) { let start = time::precise_time_ns(); @@ -123,8 +119,7 @@ fn main() { let elapsed = stop - start; - out.write_line(format!("{}\t{}\t{}", n, fibn, - elapsed.to_str())); + println!("{}\t{}\t{}", n, fibn, elapsed.to_str()); } } } diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index be2bd051cad..e1b1f59298e 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -13,8 +13,6 @@ extern mod extra; use extra::smallintmap::SmallIntMap; -use std::io::WriterUtil; -use std::io; use std::os; use std::uint; @@ -59,8 +57,8 @@ fn main() { let maxf = max as f64; - io::stdout().write_str(format!("insert(): {:?} seconds\n", checkf)); - io::stdout().write_str(format!(" : {} op/sec\n", maxf/checkf)); - io::stdout().write_str(format!("get() : {:?} seconds\n", appendf)); - io::stdout().write_str(format!(" : {} op/sec\n", maxf/appendf)); + println!("insert(): {:?} seconds\n", checkf); + println!(" : {} op/sec\n", maxf/checkf); + println!("get() : {:?} seconds\n", appendf); + println!(" : {} op/sec\n", maxf/appendf); } diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 189b3ef740e..21d492d85fc 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -14,8 +14,7 @@ extern mod extra; -use std::io::{ReaderUtil, WriterUtil}; -use std::io; +use std::rt::io; use std::os; use std::uint; use std::unstable::intrinsics::cttz16; @@ -67,7 +66,7 @@ impl Sudoku { return true; } - pub fn read(reader: @io::Reader) -> Sudoku { + pub fn read(reader: @mut io::Reader) -> Sudoku { assert!(reader.read_line() == ~"9,9"); /* assert first line is exactly "9,9" */ let mut g = vec::from_fn(10u, { |_i| ~[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8] }); @@ -87,7 +86,7 @@ impl Sudoku { return Sudoku::new(g) } - pub fn write(&self, writer: @io::Writer) { + pub fn write(&self, writer: @mut io::Writer) { for row in range(0u8, 9u8) { writer.write_str(format!("{}", self.grid[row][0] as uint)); for col in range(1u8, 9u8) { @@ -278,8 +277,8 @@ fn main() { let mut sudoku = if use_default { Sudoku::from_vec(&DEFAULT_SUDOKU) } else { - Sudoku::read(io::stdin()) + Sudoku::read(@mut io::stdin() as @mut io::Reader) }; sudoku.solve(); - sudoku.write(io::stdout()); + sudoku.write(@mut io::stdout() as @mut io::Writer); } diff --git a/src/test/compile-fail/issue-5060-fail.rs b/src/test/compile-fail/issue-5060-fail.rs index c5039854444..ef5ad2766ca 100644 --- a/src/test/compile-fail/issue-5060-fail.rs +++ b/src/test/compile-fail/issue-5060-fail.rs @@ -10,17 +10,15 @@ #[feature(macro_rules)]; -use std::io; - macro_rules! print_hd_tl ( ($field_hd:ident, $($field_tl:ident),+) => ({ - io::print(stringify!($field)); //~ ERROR unknown macro variable - io::print("::["); + print(stringify!($field)); //~ ERROR unknown macro variable + print("::["); $( - io::print(stringify!($field_tl)); - io::print(", "); + print(stringify!($field_tl)); + print(", "); )+ - io::print("]\n"); + print("]\n"); }) ) diff --git a/src/test/compile-fail/issue-5883.rs b/src/test/compile-fail/issue-5883.rs index a8b9000c6d9..621510cea99 100644 --- a/src/test/compile-fail/issue-5883.rs +++ b/src/test/compile-fail/issue-5883.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +trait A {} struct Struct { - r: io::Reader //~ ERROR reference to trait `io::Reader` where a type is expected + r: A //~ ERROR reference to trait `A` where a type is expected } -fn new_struct(r: io::Reader) -> Struct { //~ ERROR reference to trait `io::Reader` where a type is expected +fn new_struct(r: A) -> Struct { //~ ERROR reference to trait `A` where a type is expected Struct { r: r } } diff --git a/src/test/compile-fail/issue-7573.rs b/src/test/compile-fail/issue-7573.rs index 2be763ee768..9dc29e59f90 100644 --- a/src/test/compile-fail/issue-7573.rs +++ b/src/test/compile-fail/issue-7573.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; - pub struct PkgId { local_path: ~str, junk: ~str @@ -32,7 +30,7 @@ pub fn remove_package_from_database() { list_database(push_id); for l in lines_to_use.iter() { - io::stdout().write_line(l.local_path); + println!("{}", l.local_path); } } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index 22cf54428a7..2818214c994 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -13,8 +13,6 @@ use cal = bar::c::cc; -use std::io; - use std::either::Right; //~ ERROR unused import use std::util::*; // shouldn't get errors for not using @@ -24,15 +22,23 @@ use std::util::*; // shouldn't get errors for not using use std::option::{Some, None}; //~ ERROR unused import //~^ ERROR unused import -use std::io::ReaderUtil; //~ ERROR unused import +use test::A; //~ ERROR unused import // Be sure that if we just bring some methods into scope that they're also // counted as being used. -use std::io::WriterUtil; +use test::B; // Make sure this import is warned about when at least one of its imported names // is unused use std::vec::{from_fn, from_elem}; //~ ERROR unused import +mod test { + pub trait A { fn a(&self) {} } + pub trait B { fn b(&self) {} } + pub struct C; + impl A for C {} + impl B for C {} +} + mod foo { pub struct Point{x: int, y: int} pub struct Square{p: Point, h: uint, w: uint} @@ -58,6 +64,6 @@ fn main() { cal(foo::Point{x:3, y:9}); let a = 3; ignore(a); - io::stdout().write_str("a"); + test::C.b(); let _a = from_elem(0, 0); } diff --git a/src/test/run-fail/issue-2156.rs b/src/test/run-fail/issue-2156.rs deleted file mode 100644 index 863663334f8..00000000000 --- a/src/test/run-fail/issue-2156.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[allow(unnecessary_allocation)]; - -// error-pattern:explicit failure -// Don't double free the string -extern mod extra; - -use std::io::ReaderUtil; -use std::io; - -fn main() { - do io::with_str_reader(~"") |rdr| { - match rdr.read_char() { '=' => { } _ => { fail!() } } - } -} diff --git a/src/test/run-pass/auto-ref-bounded-ty-param.rs b/src/test/run-pass/auto-ref-bounded-ty-param.rs index bb01c27fa0d..5211e76d3d7 100644 --- a/src/test/run-pass/auto-ref-bounded-ty-param.rs +++ b/src/test/run-pass/auto-ref-bounded-ty-param.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; - trait Foo { fn f(&self); } @@ -30,7 +28,7 @@ impl Foo for T { impl Baz for Bar { fn g(&self) { - io::println(self.x.to_str()); + println(self.x.to_str()); } } diff --git a/src/test/run-pass/expr-repeat-vstore.rs b/src/test/run-pass/expr-repeat-vstore.rs index 8a498563359..2831740deaf 100644 --- a/src/test/run-pass/expr-repeat-vstore.rs +++ b/src/test/run-pass/expr-repeat-vstore.rs @@ -1,7 +1,5 @@ #[feature(managed_boxes)]; -use std::io::println; - pub fn main() { let v: ~[int] = ~[ 1, ..5 ]; println(v[0].to_str()); diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 0ef9e7108ae..5a3b177aadc 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -16,8 +16,7 @@ extern mod extra; -use std::io::ReaderUtil; -use std::io; +use std::rt::io; use std::to_str; enum square { @@ -64,16 +63,15 @@ fn square_from_char(c: char) -> square { } fn read_board_grid(input: rdr) -> ~[~[square]] { - let input = @input as @io::Reader; + let input = @mut input as @mut io::Reader; let mut grid = ~[]; - do input.each_line |line| { - let mut row = ~[]; - for c in line.iter() { - row.push(square_from_char(c)) - } - grid.push(row); - true - }; + let mut line = [0, ..10]; + input.read(line); + let mut row = ~[]; + for c in line.iter() { + row.push(square_from_char(*c as char)) + } + grid.push(row); let width = grid[0].len(); for row in grid.iter() { assert!(row.len() == width) } grid diff --git a/src/test/run-pass/issue-3556.rs b/src/test/run-pass/issue-3556.rs index 2d4e128f623..e092d45ce68 100644 --- a/src/test/run-pass/issue-3556.rs +++ b/src/test/run-pass/issue-3556.rs @@ -12,9 +12,6 @@ extern mod extra; -use std::io::WriterUtil; -use std::io; - enum Token { Text(@~str), ETag(@~[~str], @~str), @@ -28,8 +25,7 @@ fn check_strs(actual: &str, expected: &str) -> bool { if actual != expected { - io::stderr().write_line(format!("Found {}, but expected {}", actual, - expected)); + println!("Found {}, but expected {}", actual, expected); return false; } return true; diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index 9665da11b93..ba92434ba69 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -13,13 +13,11 @@ // rustc --test map_to_str.rs && ./map_to_str extern mod extra; -use std::io::{WriterUtil}; - fn check_strs(actual: &str, expected: &str) -> bool { if actual != expected { - io::stderr().write_line(fmt!("Found %s, but expected %s", actual, expected)); + println!("Found %s, but expected %s", actual, expected); return false; } return true; diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 55273f7029b..50d6a3ae6b8 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -20,8 +20,6 @@ extern mod extra; // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. -use std::io::WriterUtil; -use std::io; use std::str; use std::vec; @@ -150,7 +148,7 @@ impl Canvas for AsciiArt { // this little helper. pub fn check_strs(actual: &str, expected: &str) -> bool { if actual != expected { - io::stderr().write_line(format!("Found:\n{}\nbut expected\n{}", actual, expected)); + println!("Found:\n{}\nbut expected\n{}", actual, expected); return false; } return true; diff --git a/src/test/run-pass/issue-4333.rs b/src/test/run-pass/issue-4333.rs index ebf29be6d5e..86cef39abc8 100644 --- a/src/test/run-pass/issue-4333.rs +++ b/src/test/run-pass/issue-4333.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; +use std::rt::io; pub fn main() { - let stdout = &io::stdout() as &io::WriterUtil; - stdout.write_line("Hello!"); + let stdout = &mut io::stdout() as &mut io::Writer; + stdout.write(bytes!("Hello!")); } diff --git a/src/test/run-pass/issue-4541.rs b/src/test/run-pass/issue-4541.rs index 7b80974313e..32e13f5ac7f 100644 --- a/src/test/run-pass/issue-4541.rs +++ b/src/test/run-pass/issue-4541.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io; - fn parse_args() -> ~str { let args = ::std::os::args(); let mut n = 0; @@ -28,5 +26,5 @@ fn parse_args() -> ~str { } pub fn main() { - io::println(parse_args()); + println(parse_args()); } diff --git a/src/test/run-pass/issue-5060.rs b/src/test/run-pass/issue-5060.rs index e7d0cc01240..7b96d5a48b9 100644 --- a/src/test/run-pass/issue-5060.rs +++ b/src/test/run-pass/issue-5060.rs @@ -10,17 +10,15 @@ #[feature(macro_rules)]; -use std::io; - macro_rules! print_hd_tl ( ($field_hd:ident, $($field_tl:ident),+) => ({ - io::print(stringify!($field_hd)); - io::print("::["); + print(stringify!($field_hd)); + print("::["); $( - io::print(stringify!($field_tl)); - io::print(", "); + print(stringify!($field_tl)); + print(", "); )+ - io::print("]\n"); + print("]\n"); }) ) diff --git a/src/test/run-pass/issue-5741.rs b/src/test/run-pass/issue-5741.rs index 46ec68675e7..4282e7acf19 100644 --- a/src/test/run-pass/issue-5741.rs +++ b/src/test/run-pass/issue-5741.rs @@ -10,9 +10,7 @@ #[allow(unreachable_code)]; -use std::io; - pub fn main() { return; - while io::stdin().read_line() != ~"quit" { }; + while true {}; } diff --git a/src/test/run-pass/issue-8498.rs b/src/test/run-pass/issue-8498.rs index 40f98355f34..247b74e4643 100644 --- a/src/test/run-pass/issue-8498.rs +++ b/src/test/run-pass/issue-8498.rs @@ -9,14 +9,13 @@ // except according to those terms. // xfail-test -use std::io; fn main() { // This is ok match &[(~5,~7)] { ps => { let (ref y, _) = ps[0]; - io::println(fmt!("1. y = %d", **y)); + println(fmt!("1. y = %d", **y)); assert!(**y == 5); } } @@ -25,8 +24,8 @@ fn main() { match Some(&[(~5,)]) { Some(ps) => { let (ref y,) = ps[0]; - io::println(fmt!("2. y = %d", **y)); - if **y != 5 { io::println("sadness"); } + println(fmt!("2. y = %d", **y)); + if **y != 5 { println("sadness"); } } None => () } @@ -35,7 +34,7 @@ fn main() { match Some(&[(~5,~7)]) { Some(ps) => { let (ref y, ref z) = ps[0]; - io::println(fmt!("3. y = %d z = %d", **y, **z)); + println(fmt!("3. y = %d z = %d", **y, **z)); assert!(**y == 5); } None => () diff --git a/src/test/run-pass/match-drop-strs-issue-4541.rs b/src/test/run-pass/match-drop-strs-issue-4541.rs index e90d6b28626..0580bc938d7 100644 --- a/src/test/run-pass/match-drop-strs-issue-4541.rs +++ b/src/test/run-pass/match-drop-strs-issue-4541.rs @@ -2,7 +2,6 @@ // copying, and moving to ensure that we don't segfault // or double-free, as we were wont to do in the past. -use std::io; use std::os; fn parse_args() -> ~str { @@ -23,5 +22,5 @@ fn parse_args() -> ~str { } pub fn main() { - io::println(parse_args()); + println(parse_args()); } diff --git a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs index 0259c3955d8..5e03b47d1b1 100644 --- a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs +++ b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs @@ -12,8 +12,6 @@ extern mod extra; -use std::io; - trait Serializer { } @@ -33,15 +31,13 @@ impl Serializable for F { } } -impl Serializer for @io::Writer { +impl Serializer for int { } pub fn main() { - do io::with_str_writer |wr| { - let foo = F { a: 1 }; - foo.serialize(wr); + let foo = F { a: 1 }; + foo.serialize(1i); - let bar = F { a: F {a: 1 } }; - bar.serialize(wr); - }; + let bar = F { a: F {a: 1 } }; + bar.serialize(2i); } diff --git a/src/test/run-pass/new-import-syntax.rs b/src/test/run-pass/new-import-syntax.rs index c7497bf3de5..ef59606afe3 100644 --- a/src/test/run-pass/new-import-syntax.rs +++ b/src/test/run-pass/new-import-syntax.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::println; - pub fn main() { println("Hello world!"); } diff --git a/src/test/run-pass/new-style-constants.rs b/src/test/run-pass/new-style-constants.rs index e2402080bc3..fa681c81398 100644 --- a/src/test/run-pass/new-style-constants.rs +++ b/src/test/run-pass/new-style-constants.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::io::println; - static FOO: int = 3; pub fn main() { diff --git a/src/test/run-pass/stat.rs b/src/test/run-pass/stat.rs index 7501c46079d..85cf265c2d0 100644 --- a/src/test/run-pass/stat.rs +++ b/src/test/run-pass/stat.rs @@ -13,8 +13,9 @@ extern mod extra; use extra::tempfile; -use std::io::WriterUtil; -use std::io; +use std::rt::io; +use std::rt::io::Writer; +use std::rt::io::file::FileInfo; use std::os; pub fn main() { @@ -22,11 +23,12 @@ pub fn main() { let path = dir.path().join("file"); { - match io::file_writer(&path, [io::Create, io::Truncate]) { - Err(ref e) => fail!("{}", e.clone()), - Ok(f) => { + match path.open_writer(io::CreateOrTruncate) { + None => unreachable!(), + Some(f) => { + let mut f = f; for _ in range(0u, 1000) { - f.write_u8(0); + f.write([0]); } } } diff --git a/src/test/run-pass/trait-static-method-overwriting.rs b/src/test/run-pass/trait-static-method-overwriting.rs index 5ac26e65d88..c8f2afe8c61 100644 --- a/src/test/run-pass/trait-static-method-overwriting.rs +++ b/src/test/run-pass/trait-static-method-overwriting.rs @@ -11,8 +11,6 @@ // except according to those terms. mod base { - use std::io; - pub trait HasNew { fn new() -> Self; } @@ -34,7 +32,7 @@ mod base { impl ::base::HasNew for Bar { fn new() -> Bar { - io::println("Bar"); + println("Bar"); Bar { dummy: () } } }