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};
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());
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 {
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() }
};
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\
------------------------------------------\n\
\n",
expected, actual);
- io::stdout().write_str(msg);
fail!();
}
}
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 {
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\
------------------------------------------\n\
\n",
err, ProcRes.cmdline, ProcRes.stdout, ProcRes.stderr);
- io::stdout().write_str(msg);
fail!();
}
~[(~"",~"")], 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));
~[(~"",~"")], 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);
}
}
}
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()
}
use common::config;
-use std::io;
use std::os::getenv;
/// Conversion table from triple OS name to Rust SYSNAME
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
- if config.verbose { io::println(s); }
+ if config.verbose { println(s); }
}
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")
// Utility modules
pub mod c_vec;
-pub mod io_util;
// Concurrency
pub mod complex;
pub mod stats;
pub mod semver;
-pub mod fileinput;
pub mod flate;
pub mod hex;
pub mod uuid;
+++ /dev/null
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-/*!
-A 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<Path>,
- 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<Path>],
- /**
- 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<Path>]) -> 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<Path>])
- -> 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<Path>] {
- 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<Path>], 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<Path>],
- 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::<uint>(nums[0]).unwrap();
- let line_num = from_str::<uint>(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
- };
- }
-}
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[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<A>(&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() )
- }
-}
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;
/// 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); }
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) }
// 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);
}
}
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);
}
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)
}
}
/// 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,
}
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); }
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)
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));
}
}
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)
}
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));
}
}
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);
}
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);
}
}
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())
}
}
}
}
-/// Decodes a json value from an @io::Reader
-pub fn from_reader(rdr: @io::Reader) -> Result<Json, Error> {
- 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<Json, Error> {
+ let s = str::from_utf8(rdr.read_to_end());
let mut parser = Parser(~s.iter());
parser.parse()
}
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())
}
}
use super::*;
- use std::io;
-
+ use std::rt::io;
use serialize::Decodable;
use treemap::TreeMap;
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);
},
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);
},
#[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);
};
#[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);
};
use std::char;
use std::cmp;
-use std::io::{ReaderUtil};
-use std::io;
use std::option::{Option, Some, None};
use std::to_str::ToStr;
bad_parse: () -> ();
}
-fn take_nonempty_prefix(rdr: @io::Reader,
- ch: char,
- pred: &fn(char) -> bool) -> (~str, char) {
+fn take_nonempty_prefix<T: Iterator<char>>(rdr: &mut T,
+ pred: &fn(char) -> bool) -> (~str, Option<char>) {
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(())
(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<T: Iterator<char>>(rdr: &mut T) -> (uint, Option<char>) {
+ let (s, ch) = take_nonempty_prefix(rdr, char::is_digit);
match from_str::<uint>(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<T: Iterator<char>>(rdr: &mut T) -> (Identifier, Option<char>) {
+ let (s,ch) = take_nonempty_prefix(rdr, char::is_alphanumeric);
if s.iter().all(char::is_digit) {
match from_str::<uint>(s) {
None => { bad_parse::cond.raise(()); (Numeric(0), ch) },
}
}
-fn expect(ch: char, c: char) {
- if ch != c {
+fn expect(ch: Option<char>, 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<T: Iterator<char>>(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; }
}
}
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)
}
}
}
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
}
/// 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
/// 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;
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
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);
#[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);
}
#[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::*;
#[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<Terminal, ~str> {
+ pub fn new(out: @mut io::Writer) -> Result<Terminal, ~str> {
let term = os::getenv("TERM");
if term.is_none() {
return Err(~"TERM environment variable undefined");
#[cfg(target_os = "win32")]
impl Terminal {
- pub fn new(out: @io::Writer) -> Result<Terminal, ~str> {
+ pub fn new(out: @mut io::Writer) -> Result<Terminal, ~str> {
return Ok(Terminal {out: out, num_colors: 0});
}
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;
}
struct ConsoleTestState {
- out: @io::Writer,
- log_out: Option<@io::Writer>,
+ out: @mut io::Writer,
+ log_out: Option<@mut io::Writer>,
term: Option<term::Terminal>,
use_color: bool,
total: uint,
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)
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();
}
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) {
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());
}
}
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");
}
}
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);
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;
}
}
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);
#[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 m = @mut MemWriter::new();
+ let test_a = TestDesc {
+ name: StaticTestName("a"),
+ 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,
- };
+ let test_b = TestDesc {
+ name: StaticTestName("b"),
+ ignore: false,
+ should_fail: false
+ };
- st.write_failures();
+ 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);
/// 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
#[allow(missing_doc)];
-use std::io;
+use std::rt::io::Reader;
+use std::rt::io::mem::BufReader;
use std::num;
use std::str;
}
}
- 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 pos = 0u;
- let len = s.len();
- let mut result = Err(~"Invalid time");
+ 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 !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;
+ 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
+ };
+ 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.
}
}
- 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)]
#[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;
}
fn encode_inner(s: &str, full_url: bool) -> ~str {
- do io::with_str_reader(s) |rdr| {
- 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:
- ':' | '/' | '?' | '#' | '[' | ']' | '@' |
-
- // sub-delims:
- '!' | '$' | '&' | '"' | '(' | ')' | '*' |
- '+' | ',' | ';' | '=' => {
- out.push_char(ch);
- }
-
- _ => out.push_str(format!("%{:X}", ch as uint))
- }
- } else {
- out.push_str(format!("%{:X}", ch as uint));
+ let mut rdr = BufReader::new(s.as_bytes());
+ let mut out = ~"";
+
+ loop {
+ let mut buf = [0];
+ let ch = match rdr.read(buf) {
+ None => break,
+ Some(*) => buf[0] as char,
+ };
+
+ match ch {
+ // unreserved:
+ 'A' .. 'Z' |
+ 'a' .. 'z' |
+ '0' .. '9' |
+ '-' | '.' | '_' | '~' => {
+ out.push_char(ch);
+ }
+ _ => {
+ if full_url {
+ match ch {
+ // gen-delims:
+ ':' | '/' | '?' | '#' | '[' | ']' | '@' |
+
+ // 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
}
/**
}
fn decode_inner(s: &str, full_url: bool) -> ~str {
- do io::with_str_reader(s) |rdr| {
- 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);
+ let mut rdr = BufReader::new(s.as_bytes());
+ let mut out = ~"";
+
+ 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;
+
+ 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)
}
- }
- ch => out.push_char(ch)
+ } else {
+ out.push_char(ch);
}
+ }
+ ch => out.push_char(ch)
}
-
- out
}
+
+ out
}
/**
}
fn encode_plus(s: &str) -> ~str {
- do io::with_str_reader(s) |rdr| {
- 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))
- }
- }
+ let mut rdr = BufReader::new(s.as_bytes());
+ let mut out = ~"";
- out
+ 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
}
/**
* 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;
-
- 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);
- }
+ let mut rdr = BufReader::new(s);
+ let mut m = HashMap::new();
+ let mut key = ~"";
+ let mut value = ~"";
+ let mut parsing_key = true;
+
+ 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 => ~[],
+ };
- parsing_key = true;
- key = ~"";
- value = ~"";
+ values.push(value);
+ m.insert(key, values);
}
- '=' => 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
- };
- if parsing_key {
- key.push_char(ch)
- } else {
- value.push_char(ch)
+ 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);
- }
+ if key != ~"" && value != ~"" {
+ let mut values = match m.pop(&key) {
+ Some(values) => values,
+ None => ~[],
+ };
- m
+ values.push(value);
+ m.insert(key, values);
}
+
+ m
}
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 {
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;
/**
*
// 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) => {
}
fn json_encode<T:Encodable<json::Encoder>>(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<T:Decodable<json::Decoder>>(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:Encodable<json::Encoder>>(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()
}
#[test]
fn test() {
- use std::io::WriterUtil;
use std::{os, run};
// Create a path to a new file 'filename' in the directory in which
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");
}
};
- io::println(s);
+ println(s);
}
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;
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
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};
};
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<session::Os> {
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);
use std::u64;
-use std::io::WriterUtil;
-use std::io;
+use std::rt::io;
use std::option;
use std::str;
use std::vec;
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
pub fn maybe_find_item(item_id: int, items: ebml::Doc) -> Option<ebml::Doc> {
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;
}
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);
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] {
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 {
}
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);
}
}
- 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);
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};
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())
}
}
}
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;
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 : {}",
use std::cast;
-use std::io;
+use std::rt::io;
use std::uint;
use std::vec;
use std::hashmap::HashMap;
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);
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;
}
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());
}
}
}
}
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) {
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;
// 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);
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
}
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;
lint::level_to_str(spec.default),
spec.desc);
}
- io::println("");
+ println("");
}
pub fn describe_debug_flags() {
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))
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");
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;
/// This input format purely deserializes the json output file. No passes are
/// run over the deserialized output.
fn json_input(input: &str) -> Result<Output, ~str> {
- 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;
// 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,
// Context data structure used by rustpkg
-use std::{io, os};
+use std::os;
use extra::workcache;
use rustc::driver::session::{OptLevel, No};
};
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;
}
// 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]);
}
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;
}
}
"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);
}
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()));
}
// 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::*;
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 {
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());
}
}
* testsuite/hello-world/build/ does not contain a library
*/
-use std::io;
-
fn main() {
- io::println(~"Hello world!");
+ println(~"Hello world!");
}
* testsuite/pass/hello-world/build is empty
*/
-use std::io;
-
fn main() {
- io::println(~"Hello world!");
+ println(~"Hello world!");
}
// 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] <cmd> [args..]
+ println("Usage: rustpkg [options] <cmd> [args..]
Where <cmd> is one of:
build, clean, do, info, install, list, prefer, test, uninstall, unprefer
}
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
}
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 <cmd>
+ println("rustpkg do <cmd>
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.
}
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.
}
pub fn uninstall() {
- io::println("rustpkg uninstall <id|name>[@version]
+ println("rustpkg uninstall <id|name>[@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 <id|name>[@version]
+ println("rustpkg [options..] prefer <id|name>[@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
}
pub fn unprefer() {
- io::println("rustpkg [options..] unprefer <id|name>[@version]
+ println("rustpkg [options..] unprefer <id|name>[@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
}
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
}
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.
// 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")))
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)));
+ ~""
}
}
}
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;
+#[cfg(stage0)]
+pub use rt::io::stdio::{print, println};
+
#[allow(non_camel_case_types)] // not sure what to do about this
-pub type fd_t = c_int;
+type fd_t = c_int;
-pub mod rustrt {
+mod rustrt {
use libc;
#[link_name = "rustrt"]
}
impl FILERes {
- pub fn new(f: *libc::FILE) -> FILERes {
+ fn new(f: *libc::FILE) -> FILERes {
FILERes { f: f }
}
}
}
}
-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)];
Err(~"error opening " + p)
}
} else {
- Ok(FILE_reader(f, true))
- }
-}
-
-
-// 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
+ Ok(@Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader)
}
}
-pub fn with_bytes_reader<T>(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<T>(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, }
}
impl FdRes {
- pub fn new(fd: fd_t) -> FdRes {
+ fn new(fd: fd_t) -> FdRes {
FdRes { fd: fd }
}
}
}
}
-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)];
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)
}
}
// 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,
}
// 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;
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<t> {
- priv arg: Arg<t>,
- }
-
- impl <t> Res<t> {
- pub fn new(arg: Arg<t>) -> Res<t> {
- Res { arg: arg }
- }
- }
-
- #[unsafe_destructor]
- impl<T> Drop for Res<T> {
- 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<t> {
- priv val: t,
- priv opt_level: Option<Level>,
- 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<Level>,
- 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<Level>,
- blk: &fn(v: Res<fd_t>)) {
- 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<Level>,
- 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::*;
}
}
- #[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")) {
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};
}
}
-
-// 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
mod test {
use ast::*;
use super::*;
- use std::io;
use opt_vec;
use std::hashmap::HashMap;
// - 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);
use codemap::{Pos, Span};
use codemap;
-use std::io;
+use std::rt::io;
use std::local_data;
use extra::term;
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: @Option<term::Terminal>)
- 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);
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)),
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;
}
// 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)
_ => 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 {
}
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);
}
//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 {
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);
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);
&& (@"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);
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()));
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
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()));
+ }
}
}
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()
+ }
+ };
+ match error {
+ Some(e) => {
+ cx.span_fatal(sp, format!("couldn't read {}: {}",
+ file.display(), e.desc));
}
- result::Err(ref e) => {
- cx.parse_sess().span_diagnostic.handler().fatal((*e))
+ None => {
+ base::MRExpr(cx.expr_lit(sp, ast::lit_binary(bytes)))
}
}
}
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;
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);
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;
/// 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<Span>)
-> @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
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;
use util::parser_testing::string_to_stmt;
#[cfg(test)] fn to_json_str<E : Encodable<extra::json::Encoder>>(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
* avoid combining it with other lines and making matters even worse.
*/
-use std::io;
+use std::rt::io;
use std::vec;
#[deriving(Clone, Eq)]
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;
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,
* 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
}
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);
}
}
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,
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> {
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 {
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(
pub fn fun_to_str(decl: &ast::fn_decl, purity: ast::purity, name: ast::Ident,
opt_explicit_self: Option<ast::explicit_self_>,
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 {
}
pub fn to_str<T>(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<comments::cmnt> {
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;
}
fn ascending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
- io::println(" Ascending integers:");
+ println(" Ascending integers:");
do timed("insert") {
for i in range(0u, n_keys) {
}
fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
- io::println(" Descending integers:");
+ println(" Descending integers:");
do timed("insert") {
for i in range(0, n_keys).invert() {
println!("{} keys", n_keys);
- io::println("\nTreeMap:");
+ println("\nTreeMap:");
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
}
{
- io::println(" Random integers:");
+ println(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand);
}
- io::println("\nHashMap:");
+ println("\nHashMap:");
{
let mut map: HashMap<uint,uint> = HashMap::new();
}
{
- io::println(" Random integers:");
+ println(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand);
}
- io::println("\nTrieMap:");
+ println("\nTrieMap:");
{
let mut map: TrieMap<uint> = TrieMap::new();
}
{
- io::println(" Random integers:");
+ println(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand);
}
use extra::bitv::BitvSet;
use extra::treemap::TreeSet;
use std::hashmap::HashSet;
-use std::io;
use std::os;
use std::rand;
use std::uint;
}
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) {
use std::comm::{Port, Chan, SharedChan};
use std::comm;
-use std::io;
use std::os;
use std::task;
use std::uint;
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);
}
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
-use std::io;
use std::os;
use std::task;
use std::uint;
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);
}
use std::cell::Cell;
use std::comm::{stream, SharedChan};
-use std::io;
use std::option;
use std::os;
use std::task;
}
// 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() {
let nn = from_str::<uint>(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]);
extern mod extra;
use std::int;
-use std::io;
+use std::rt::io;
use std::os;
use std::rand::Rng;
use std::rand;
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()
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);
}
}
};
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::<int>(args[1]).unwrap();
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;
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
- io::println(from_child[ii].recv());
+ println(from_child[ii].recv());
}
}
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;
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();
let elapsed = stop - start;
- out.write_line(format!("{}\t{}\t{}", n, fibn,
- elapsed.to_str()));
+ println!("{}\t{}\t{}", n, fibn, elapsed.to_str());
}
}
}
extern mod extra;
use extra::smallintmap::SmallIntMap;
-use std::io::WriterUtil;
-use std::io;
use std::os;
use std::uint;
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);
}
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;
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] });
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) {
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);
}
#[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");
})
)
// 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 }
}
// 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
list_database(push_id);
for l in lines_to_use.iter() {
- io::stdout().write_line(l.local_path);
+ println!("{}", l.local_path);
}
}
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
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}
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);
}
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[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!() } }
- }
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::io;
-
trait Foo {
fn f(&self);
}
impl Baz for Bar {
fn g(&self) {
- io::println(self.x.to_str());
+ println(self.x.to_str());
}
}
#[feature(managed_boxes)];
-use std::io::println;
-
pub fn main() {
let v: ~[int] = ~[ 1, ..5 ];
println(v[0].to_str());
extern mod extra;
-use std::io::ReaderUtil;
-use std::io;
+use std::rt::io;
use std::to_str;
enum square {
}
fn read_board_grid<rdr:'static + io::Reader>(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
extern mod extra;
-use std::io::WriterUtil;
-use std::io;
-
enum Token {
Text(@~str),
ETag(@~[~str], @~str),
{
if actual != expected
{
- io::stderr().write_line(format!("Found {}, but expected {}", actual,
- expected));
+ println!("Found {}, but expected {}", actual, expected);
return false;
}
return true;
// 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;
// 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;
// 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;
// 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!"));
}
// 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;
}
pub fn main() {
- io::println(parse_args());
+ println(parse_args());
}
#[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");
})
)
#[allow(unreachable_code)];
-use std::io;
-
pub fn main() {
return;
- while io::stdin().read_line() != ~"quit" { };
+ while true {};
}
// 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);
}
}
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 => ()
}
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 => ()
// 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 {
}
pub fn main() {
- io::println(parse_args());
+ println(parse_args());
}
extern mod extra;
-use std::io;
-
trait Serializer {
}
}
}
-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);
}
// 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!");
}
// 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() {
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() {
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]);
}
}
}
// except according to those terms.
mod base {
- use std::io;
-
pub trait HasNew<T> {
fn new() -> Self;
}
impl ::base::HasNew<Bar> for Bar {
fn new() -> Bar {
- io::println("Bar");
+ println("Bar");
Bar { dummy: () }
}
}