use io::prelude::*;
use cmp;
-use error::Error as StdError;
-use error::FromError;
+use error::{self, FromError};
use fmt;
use io::{self, Cursor, DEFAULT_BUF_SIZE, Error, ErrorKind};
use ptr;
/// For example, every call to `read` on `TcpStream` results in a system call.
/// A `BufReader` performs large, infrequent reads on the underlying `Read`
/// and maintains an in-memory buffer of the results.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct BufReader<R> {
inner: R,
buf: Cursor<Vec<u8>>,
impl<R: Read> BufReader<R> {
/// Creates a new `BufReader` with a default buffer capacity
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn new(inner: R) -> BufReader<R> {
BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
}
/// Creates a new `BufReader` with the specified buffer capacity
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(cap: usize, inner: R) -> BufReader<R> {
BufReader {
inner: inner,
}
/// Gets a reference to the underlying reader.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_ref(&self) -> &R { &self.inner }
/// Gets a mutable reference to the underlying reader.
/// # Warning
///
/// It is inadvisable to directly read from the underlying reader.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
/// Unwraps this `BufReader`, returning the underlying reader.
///
/// Note that any leftover data in the internal buffer is lost.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> R { self.inner }
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
// If we don't have any buffered data and we're doing a massive read
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<R: Read> BufRead for BufReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
// If we've reached the end of our internal buffer then we need to fetch
/// underlying `Write` in large, infrequent batches.
///
/// This writer will be flushed when it is dropped.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct BufWriter<W> {
inner: Option<W>,
buf: Vec<u8>,
/// An error returned by `into_inner` which indicates whether a flush error
/// happened or not.
#[derive(Debug)]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoInnerError<W>(W, Error);
impl<W: Write> BufWriter<W> {
/// Creates a new `BufWriter` with a default buffer capacity
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn new(inner: W) -> BufWriter<W> {
BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
}
/// Creates a new `BufWriter` with the specified buffer capacity
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(cap: usize, inner: W) -> BufWriter<W> {
BufWriter {
inner: Some(inner),
}
/// Gets a reference to the underlying writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() }
/// Gets a mutable reference to the underlying write.
/// # Warning
///
/// It is inadvisable to directly read from the underlying writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() }
/// Unwraps this `BufWriter`, returning the underlying writer.
///
/// The buffer is flushed before returning the writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
match self.flush_buf() {
Err(e) => Err(IntoInnerError(self, e)),
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write> Write for BufWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.buf.len() + buf.len() > self.buf.capacity() {
/// Returns the error which caused the call to `into_inner` to fail.
///
/// This error was returned when attempting to flush the internal buffer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn error(&self) -> &Error { &self.1 }
/// Returns the underlying `BufWriter` instance which generated the error.
///
/// The returned object can be used to retry a flush or re-inspect the
/// buffer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> W { self.0 }
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<W> FromError<IntoInnerError<W>> for Error {
fn from_error(iie: IntoInnerError<W>) -> Error { iie.1 }
}
-impl<W> StdError for IntoInnerError<W> {
- fn description(&self) -> &str { self.error().description() }
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<W> error::Error for IntoInnerError<W> {
+ fn description(&self) -> &str {
+ error::Error::description(self.error())
+ }
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<W> fmt::Display for IntoInnerError<W> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.error().fmt(f)
/// (`0x0a`, `'\n'`) is detected.
///
/// This writer will be flushed when it is dropped.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct LineWriter<W> {
inner: BufWriter<W>,
}
impl<W: Write> LineWriter<W> {
/// Creates a new `LineWriter`
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn new(inner: W) -> LineWriter<W> {
// Lines typically aren't that long, don't use a giant buffer
- LineWriter { inner: BufWriter::with_capacity(1024, inner) }
+ LineWriter::with_capacity(1024, inner)
+ }
+
+ /// Creates a new `LineWriter` with a specified capacity for the internal
+ /// buffer.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn with_capacity(cap: usize, inner: W) -> LineWriter<W> {
+ LineWriter { inner: BufWriter::with_capacity(cap, inner) }
}
/// Gets a reference to the underlying writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn get_ref(&self) -> &W { self.inner.get_ref() }
+
+ /// Gets a mutable reference to the underlying writer.
///
- /// This type does not expose the ability to get a mutable reference to the
- /// underlying reader because that could possibly corrupt the buffer.
- pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.get_ref() }
+ /// Caution must be taken when calling methods on the mutable reference
+ /// returned as extra writes could corrupt the output stream.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() }
/// Unwraps this `LineWriter`, returning the underlying writer.
///
/// The internal buffer is flushed before returning the writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
IntoInnerError(LineWriter { inner: buf }, e)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write> Write for LineWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match buf.rposition_elem(&b'\n') {
/// Wraps a Stream and buffers input and output to and from it.
///
-/// It can be excessively inefficient to work directly with a `Stream`. For
+/// It can be excessively inefficient to work directly with a `Read+Write`. For
/// example, every call to `read` or `write` on `TcpStream` results in a system
/// call. A `BufStream` keeps in memory buffers of data, making large,
-/// infrequent calls to `read` and `write` on the underlying `Stream`.
+/// infrequent calls to `read` and `write` on the underlying `Read+Write`.
///
/// The output half will be flushed when this stream is dropped.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct BufStream<S> {
inner: BufReader<InternalBufWriter<S>>
}
impl<S: Read + Write> BufStream<S> {
/// Creates a new buffered stream with explicitly listed capacities for the
/// reader/writer buffer.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacities(reader_cap: usize, writer_cap: usize, inner: S)
-> BufStream<S> {
let writer = BufWriter::with_capacity(writer_cap, inner);
/// Creates a new buffered stream with the default reader/writer buffer
/// capacities.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn new(inner: S) -> BufStream<S> {
BufStream::with_capacities(DEFAULT_BUF_SIZE, DEFAULT_BUF_SIZE, inner)
}
/// Gets a reference to the underlying stream.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_ref(&self) -> &S {
let InternalBufWriter(ref w) = self.inner.inner;
w.get_ref()
///
/// It is inadvisable to read directly from or write directly to the
/// underlying stream.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut(&mut self) -> &mut S {
let InternalBufWriter(ref mut w) = self.inner.inner;
w.get_mut()
///
/// The internal buffer is flushed before returning the stream. Any leftover
/// data in the read buffer is lost.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> Result<S, IntoInnerError<BufStream<S>>> {
let BufReader { inner: InternalBufWriter(w), buf } = self.inner;
w.into_inner().map_err(|IntoInnerError(w, e)| {
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Read + Write> BufRead for BufStream<S> {
fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Read + Write> Read for BufStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Read + Write> Write for BufStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.inner.get_mut().write(buf)
use boxed::Box;
use clone::Clone;
-use error::Error as StdError;
+use error;
use fmt;
use option::Option::{self, Some, None};
use result;
///
/// This typedef is generally used to avoid writing out `io::Error` directly and
/// is otherwise a direct mapping to `std::result::Result`.
+#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = result::Result<T, Error>;
/// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
/// `Error` can be created with crafted error messages and a particular value of
/// `ErrorKind`.
#[derive(PartialEq, Eq, Clone, Debug)]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct Error {
repr: Repr,
}
/// A list specifying general categories of I/O error.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
+#[unstable(feature = "io",
+ reason = "the interaction between OS error codes and how they map to \
+ these names (as well as the names themselves) has not \
+ been thoroughly thought out")]
pub enum ErrorKind {
/// The file was not found.
FileNotFound,
impl Error {
/// Creates a new custom error from a specified kind/description/detail.
+ #[unstable(feature = "io", reason = "the exact makeup of an Error may
+ change to include `Box<Error>` for \
+ example")]
pub fn new(kind: ErrorKind,
description: &'static str,
detail: Option<String>) -> Error {
/// This function reads the value of `errno` for the target platform (e.g.
/// `GetLastError` on Windows) and will return a corresponding instance of
/// `Error` for the error code.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn last_os_error() -> Error {
Error::from_os_error(sys::os::errno() as i32)
}
/// Creates a new instance of an `Error` from a particular OS error code.
+ #[unstable(feature = "io",
+ reason = "unclear whether this function is necessary")]
pub fn from_os_error(code: i32) -> Error {
Error { repr: Repr::Os(code) }
}
/// Return the corresponding `ErrorKind` for this error.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn kind(&self) -> ErrorKind {
match self.repr {
Repr::Os(code) => sys::decode_error_kind(code),
}
/// Returns a short description for this error message
+ #[unstable(feature = "io")]
+ #[deprecated(since = "1.0.0", reason = "use the Error trait's description \
+ method instead")]
pub fn description(&self) -> &str {
match self.repr {
Repr::Os(..) => "os error",
}
/// Returns a detailed error message for this error (if one is available)
+ #[unstable(feature = "io")]
+ #[deprecated(since = "1.0.0", reason = "use the to_string() method instead")]
pub fn detail(&self) -> Option<String> {
match self.repr {
Repr::Os(code) => Some(sys::os::error_string(code)),
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.repr {
}
}
-impl StdError for Error {
+#[stable(feature = "rust1", since = "1.0.0")]
+impl error::Error for Error {
fn description(&self) -> &str {
match self.repr {
Repr::Os(..) => "os error",
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
- fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
+ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_to_end(buf)
}
- fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
+ fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_to_string(buf)
}
}
impl<'a, B: BufRead + ?Sized> BufRead for &'a mut B {
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
- fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<()> {
+ fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_until(byte, buf)
}
- fn read_line(&mut self, buf: &mut String) -> io::Result<()> {
+ fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_line(buf)
}
}
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
- fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
+ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_to_end(buf)
}
- fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
+ fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_to_string(buf)
}
}
impl<B: BufRead + ?Sized> BufRead for Box<B> {
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
- fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<()> {
+ fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_until(byte, buf)
}
- fn read_line(&mut self, buf: &mut String) -> io::Result<()> {
+ fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_line(buf)
}
}
//! > development. At this time it is still recommended to use the `old_io`
//! > module while the details of this module shake out.
-#![unstable(feature = "io",
- reason = "this new I/O module is still under active development and \
- APIs are subject to tweaks fairly regularly")]
+#![stable(feature = "rust1", since = "1.0.0")]
use cmp;
use unicode::str as core_str;
-use error::Error as StdError;
+use error as std_error;
use fmt;
use iter::Iterator;
use marker::Sized;
// 2. We're passing a raw buffer to the function `f`, and it is expected that
// the function only *appends* bytes to the buffer. We'll get undefined
// behavior if existing bytes are overwritten to have non-UTF-8 data.
-fn append_to_string<F>(buf: &mut String, f: F) -> Result<()>
- where F: FnOnce(&mut Vec<u8>) -> Result<()>
+fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
+ where F: FnOnce(&mut Vec<u8>) -> Result<usize>
{
struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
#[unsafe_destructor]
let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
let ret = f(g.s);
if str::from_utf8(&g.s[g.len..]).is_err() {
- ret.and_then(|()| {
+ ret.and_then(|_| {
Err(Error::new(ErrorKind::InvalidInput,
"stream did not contain valid UTF-8", None))
})
}
}
-fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<()> {
+fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
+ let mut read = 0;
loop {
if buf.capacity() == buf.len() {
buf.reserve(DEFAULT_BUF_SIZE);
}
match with_end_to_cap(buf, |b| r.read(b)) {
- Ok(0) => return Ok(()),
- Ok(_) => {}
+ Ok(0) => return Ok(read),
+ Ok(n) => read += n,
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
/// Readers are intended to be composable with one another. Many objects
/// throughout the I/O and related libraries take and provide types which
/// implement the `Read` trait.
+#[stable(feature = "rust1", since = "1.0.0")]
pub trait Read {
/// Pull some bytes from this source into the specified buffer, returning
/// how many bytes were read.
/// If this function encounters any form of I/O or other error, an error
/// variant will be returned. If an error is returned then it must be
/// guaranteed that no bytes were read.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
/// Read all bytes until EOF in this source, placing them into `buf`.
/// 2. Returns an error which is not of the kind `ErrorKind::Interrupted`.
///
/// Until one of these conditions is met the function will continuously
- /// invoke `read` to append more data to `buf`.
+ /// invoke `read` to append more data to `buf`. If successful, this function
+ /// will return the total number of bytes read.
///
/// # Errors
///
/// If any other read error is encountered then this function immediately
/// returns. Any bytes which have already been read will be appended to
/// `buf`.
- fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<()> {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
read_to_end(self, buf)
}
/// Read all bytes until EOF in this source, placing them into `buf`.
///
+ /// If successful, this function returns the number of bytes which were read
+ /// and appended to `buf`.
+ ///
/// # Errors
///
/// If the data in this stream is *not* valid UTF-8 then an error is
/// returned and `buf` is unchanged.
///
/// See `read_to_end` for other error semantics.
- fn read_to_string(&mut self, buf: &mut String) -> Result<()> {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
// Note that we do *not* call `.read_to_end()` here. We are passing
// `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
// method to fill it up. An arbitrary implementation could overwrite the
// know is guaranteed to only read data into the end of the buffer.
append_to_string(buf, |b| read_to_end(self, b))
}
-}
-/// Extension methods for all instances of `Read`, typically imported through
-/// `std::io::prelude::*`.
-#[unstable(feature = "io", reason = "may merge into the Read trait")]
-pub trait ReadExt: Read + Sized {
/// Create a "by reference" adaptor for this instance of `Read`.
///
/// The returned adaptor also implements `Read` and will simply borrow this
/// current reader.
#[stable(feature = "rust1", since = "1.0.0")]
- fn by_ref(&mut self) -> &mut Self { self }
+ fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
/// Transform this `Read` instance to an `Iterator` over its bytes.
///
/// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
/// this iterator.
#[stable(feature = "rust1", since = "1.0.0")]
- fn bytes(self) -> Bytes<Self> {
+ fn bytes(self) -> Bytes<Self> where Self: Sized {
Bytes { inner: self }
}
#[unstable(feature = "io", reason = "the semantics of a partial read/write \
of where errors happen is currently \
unclear and may change")]
- fn chars(self) -> Chars<Self> {
+ fn chars(self) -> Chars<Self> where Self: Sized {
Chars { inner: self }
}
/// until EOF is encountered. Afterwards the output is equivalent to the
/// output of `next`.
#[stable(feature = "rust1", since = "1.0.0")]
- fn chain<R: Read>(self, next: R) -> Chain<Self, R> {
+ fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
Chain { first: self, second: next, done_first: false }
}
/// read errors will not count towards the number of bytes read and future
/// calls to `read` may succeed.
#[stable(feature = "rust1", since = "1.0.0")]
- fn take(self, limit: u64) -> Take<Self> {
+ fn take(self, limit: u64) -> Take<Self> where Self: Sized {
Take { inner: self, limit: limit }
}
#[unstable(feature = "io", reason = "the semantics of a partial read/write \
of where errors happen is currently \
unclear and may change")]
- fn tee<W: Write>(self, out: W) -> Tee<Self, W> {
+ fn tee<W: Write>(self, out: W) -> Tee<Self, W> where Self: Sized {
Tee { reader: self, writer: out }
}
}
-impl<T: Read> ReadExt for T {}
-
/// A trait for objects which are byte-oriented sinks.
///
/// The `write` method will attempt to write some data into the object,
/// Writers are intended to be composable with one another. Many objects
/// throughout the I/O and related libraries take and provide types which
/// implement the `Write` trait.
+#[stable(feature = "rust1", since = "1.0.0")]
pub trait Write {
/// Write a buffer into this object, returning how many bytes were written.
///
///
/// It is **not** considered an error if the entire buffer could not be
/// written to this writer.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn write(&mut self, buf: &[u8]) -> Result<usize>;
/// Flush this output stream, ensuring that all intermediately buffered
///
/// It is considered an error if not all bytes could be written due to
/// I/O errors or EOF being reached.
+ #[unstable(feature = "io", reason = "waiting for RFC 950")]
fn flush(&mut self) -> Result<()>;
/// Attempts to write an entire buffer into this write.
/// # Errors
///
/// This function will return the first error that `write` returns.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
while buf.len() > 0 {
match self.write(buf) {
/// # Errors
///
/// This function will return any I/O error reported while formatting.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
// Create a shim which translates a Write to a fmt::Write and saves
// off I/O errors. instead of discarding them
Err(..) => output.error
}
}
-}
-/// Extension methods for all instances of `Write`, typically imported through
-/// `std::io::prelude::*`.
-#[unstable(feature = "io", reason = "may merge into the Read trait")]
-pub trait WriteExt: Write + Sized {
/// Create a "by reference" adaptor for this instance of `Write`.
///
/// The returned adaptor also implements `Write` and will simply borrow this
/// current writer.
#[stable(feature = "rust1", since = "1.0.0")]
- fn by_ref(&mut self) -> &mut Self { self }
+ fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
/// Creates a new writer which will write all data to both this writer and
/// another writer.
#[unstable(feature = "io", reason = "the semantics of a partial read/write \
of where errors happen is currently \
unclear and may change")]
- fn broadcast<W: Write>(self, other: W) -> Broadcast<Self, W> {
+ fn broadcast<W: Write>(self, other: W) -> Broadcast<Self, W>
+ where Self: Sized
+ {
Broadcast { first: self, second: other }
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: Write> WriteExt for T {}
-
/// An object implementing `Seek` internally has some form of cursor which can
/// be moved within a stream of bytes.
///
/// The stream typically has a fixed size, allowing seeking relative to either
/// end or the current offset.
+#[unstable(feature = "io", reason = "the central `seek` method may be split \
+ into multiple methods instead of taking \
+ an enum as an argument")]
pub trait Seek {
/// Seek to an offset, in bytes, in a stream
///
/// Enumeration of possible methods to seek within an I/O object.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
+#[unstable(feature = "io", reason = "awaiting the stability of Seek")]
pub enum SeekFrom {
/// Set the offset to the provided number of bytes.
Start(u64),
}
fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
- -> Result<()> {
+ -> Result<usize> {
+ let mut read = 0;
loop {
let (done, used) = {
let available = match r.fill_buf() {
}
};
r.consume(used);
+ read += used;
if done || used == 0 {
- return Ok(());
+ return Ok(read);
}
}
}
///
/// This type extends the `Read` trait with a few methods that are not
/// possible to reasonably implement with purely a read interface.
+#[stable(feature = "rust1", since = "1.0.0")]
pub trait BufRead: Read {
/// Fills the internal buffer of this object, returning the buffer contents.
///
///
/// This function will return an I/O error if the underlying reader was
/// read, but returned an error.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn fill_buf(&mut self) -> Result<&[u8]>;
/// Tells this buffer that `amt` bytes have been consumed from the buffer,
/// so they should no longer be returned in calls to `read`.
+ ///
+ /// This function does not perform any I/O, it simply informs this object
+ /// that some amount of its buffer, returned from `fill_buf`, has been
+ /// consumed and should no longer be returned.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn consume(&mut self, amt: usize);
/// Read all bytes until the delimiter `byte` is reached.
/// `buf`.
///
/// If this buffered reader is currently at EOF, then this function will not
- /// place any more bytes into `buf` and will return `Ok(())`.
+ /// place any more bytes into `buf` and will return `Ok(n)` where `n` is the
+ /// number of bytes which were read.
///
/// # Errors
///
///
/// If an I/O error is encountered then all bytes read so far will be
/// present in `buf` and its length will have been adjusted appropriately.
- fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<()> {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
read_until(self, byte, buf)
}
/// found) will be appended to `buf`.
///
/// If this reader is currently at EOF then this function will not modify
- /// `buf` and will return `Ok(())`.
+ /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
+ /// were read.
///
/// # Errors
///
/// return an error if the read bytes are not valid UTF-8. If an I/O error
/// is encountered then `buf` may contain some bytes already read in the
/// event that all data read so far was valid UTF-8.
- fn read_line(&mut self, buf: &mut String) -> Result<()> {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn read_line(&mut self, buf: &mut String) -> Result<usize> {
// Note that we are not calling the `.read_until` method here, but
// rather our hardcoded implementation. For more details as to why, see
// the comments in `read_to_end`.
append_to_string(buf, |b| read_until(self, b'\n', b))
}
-}
-/// Extension methods for all instances of `BufRead`, typically imported through
-/// `std::io::prelude::*`.
-pub trait BufReadExt: BufRead + Sized {
/// Returns an iterator over the contents of this reader split on the byte
/// `byte`.
///
/// yielded an error.
#[unstable(feature = "io", reason = "may be renamed to not conflict with \
SliceExt::split")]
- fn split(self, byte: u8) -> Split<Self> {
+ fn split(self, byte: u8) -> Split<Self> where Self: Sized {
Split { buf: self, delim: byte }
}
/// This function will yield errors whenever `read_string` would have also
/// yielded an error.
#[stable(feature = "rust1", since = "1.0.0")]
- fn lines(self) -> Lines<Self> {
+ fn lines(self) -> Lines<Self> where Self: Sized {
Lines { buf: self }
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: BufRead> BufReadExt for T {}
-
/// A `Write` adaptor which will write data to multiple locations.
///
/// For more information, see `WriteExt::broadcast`.
+#[unstable(feature = "io", reason = "awaiting stability of WriteExt::broadcast")]
pub struct Broadcast<T, U> {
first: T,
second: U,
}
+#[unstable(feature = "io", reason = "awaiting stability of WriteExt::broadcast")]
impl<T: Write, U: Write> Write for Broadcast<T, U> {
fn write(&mut self, data: &[u8]) -> Result<usize> {
let n = try!(self.first.write(data));
/// An adaptor which will emit all read data to a specified writer as well.
///
/// For more information see `ReadExt::tee`
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::tee")]
pub struct Tee<R, W> {
reader: R,
writer: W,
}
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::tee")]
impl<R: Read, W: Write> Read for Tee<R, W> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let n = try!(self.reader.read(buf));
/// A bridge from implementations of `Read` to an `Iterator` of `char`.
///
/// See `ReadExt::chars` for more information.
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")]
pub struct Chars<R> {
inner: R,
}
/// An enumeration of possible errors that can be generated from the `Chars`
/// adapter.
#[derive(PartialEq, Clone, Debug)]
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")]
pub enum CharsError {
/// Variant representing that the underlying stream was read successfully
/// but it did not contain valid utf8 data.
Other(Error),
}
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")]
impl<R: Read> Iterator for Chars<R> {
type Item = result::Result<char, CharsError>;
}
}
-impl StdError for CharsError {
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")]
+impl std_error::Error for CharsError {
fn description(&self) -> &str {
match *self {
CharsError::NotUtf8 => "invalid utf8 encoding",
- CharsError::Other(ref e) => e.description(),
+ CharsError::Other(ref e) => std_error::Error::description(e),
}
}
- fn cause(&self) -> Option<&StdError> {
+ fn cause(&self) -> Option<&std_error::Error> {
match *self {
CharsError::NotUtf8 => None,
CharsError::Other(ref e) => e.cause(),
}
}
+#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")]
impl fmt::Display for CharsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
/// particular byte.
///
/// See `BufReadExt::split` for more information.
+#[unstable(feature = "io", reason = "awaiting stability of BufReadExt::split")]
pub struct Split<B> {
buf: B,
delim: u8,
}
+#[unstable(feature = "io", reason = "awaiting stability of BufReadExt::split")]
impl<B: BufRead> Iterator for Split<B> {
type Item = Result<Vec<u8>>;
fn next(&mut self) -> Option<Result<Vec<u8>>> {
let mut buf = Vec::new();
match self.buf.read_until(self.delim, &mut buf) {
- Ok(()) if buf.len() == 0 => None,
- Ok(()) => {
+ Ok(0) => None,
+ Ok(_n) => {
if buf[buf.len() - 1] == self.delim {
buf.pop();
}
fn next(&mut self) -> Option<Result<String>> {
let mut buf = String::new();
match self.buf.read_line(&mut buf) {
- Ok(()) if buf.len() == 0 => None,
- Ok(()) => {
+ Ok(0) => None,
+ Ok(_n) => {
if buf.ends_with("\n") {
buf.pop();
}
//! `Write`, `ReadExt`, and `WriteExt`. Structures and functions are not
//! contained in this module.
-pub use super::{Read, ReadExt, Write, WriteExt, BufRead, BufReadExt};
+#![stable(feature = "rust1", since = "1.0.0")]
+
+pub use super::{Read, Write, BufRead};
pub use fs::PathExt;
// FIXME: pub use as `Seek` when the name isn't in the actual prelude any more
///
/// This handle implements the `Read` trait, but beware that concurrent reads
/// of `Stdin` must be executed with care.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct Stdin {
inner: Arc<Mutex<BufReader<StdinRaw>>>,
}
///
/// This handle implements both the `Read` and `BufRead` traits and is
/// constructed via the `lock` method on `Stdin`.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct StdinLock<'a> {
inner: MutexGuard<'a, BufReader<StdinRaw>>,
}
///
/// To avoid locking and buffering altogether, it is recommended to use the
/// `stdin_raw` constructor.
+#[stable(feature = "rust1", since = "1.0.0")]
pub fn stdin() -> Stdin {
static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
return Stdin {
/// The lock is released when the returned lock goes out of scope. The
/// returned guard also implements the `Read` and `BufRead` traits for
/// accessing the underlying data.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> StdinLock {
StdinLock { inner: self.inner.lock().unwrap() }
}
+
+ /// Locks this handle and reads a line of input into the specified buffer.
+ ///
+ /// For detailed semantics of this method, see the documentation on
+ /// `BufRead::read_line`.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
+ self.lock().read_line(buf)
+ }
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.lock().read(buf)
}
-
- fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
+ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.lock().read_to_end(buf)
}
-
- fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
+ fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
self.lock().read_to_string(buf)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Read for StdinLock<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> BufRead for StdinLock<'a> {
fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
fn consume(&mut self, n: usize) { self.inner.consume(n) }
/// Each handle shares a global buffer of data to be written to the standard
/// output stream. Access is also synchronized via a lock and explicit control
/// over locking is available via the `lock` method.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct Stdout {
// FIXME: this should be LineWriter or BufWriter depending on the state of
// stdout (tty or not). Note that if this is not line buffered it
///
/// This handle implements the `Write` trait and is constructed via the `lock`
/// method on `Stdout`.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct StdoutLock<'a> {
inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
}
///
/// To avoid locking and buffering altogether, it is recommended to use the
/// `stdout_raw` constructor.
+#[stable(feature = "rust1", since = "1.0.0")]
pub fn stdout() -> Stdout {
static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
return Stdout {
///
/// The lock is released when the returned lock goes out of scope. The
/// returned guard also implements the `Write` trait for writing data.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> StdoutLock {
StdoutLock { inner: self.inner.lock().unwrap() }
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Stdout {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.lock().write(buf)
self.lock().write_fmt(fmt)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Write for StdoutLock<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
/// A handle to the standard error stream of a process.
///
/// For more information, see `stderr`
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct Stderr {
inner: Arc<Mutex<StderrRaw>>,
}
///
/// This handle implements the `Write` trait and is constructed via the `lock`
/// method on `Stderr`.
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct StderrLock<'a> {
inner: MutexGuard<'a, StderrRaw>,
}
///
/// To avoid locking altogether, it is recommended to use the `stderr_raw`
/// constructor.
+#[stable(feature = "rust1", since = "1.0.0")]
pub fn stderr() -> Stderr {
static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
return Stderr {
///
/// The lock is released when the returned lock goes out of scope. The
/// returned guard also implements the `Write` trait for writing data.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> StderrLock {
StderrLock { inner: self.inner.lock().unwrap() }
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Stderr {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.lock().write(buf)
self.lock().write_fmt(fmt)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Write for StderrLock<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
#![deny(unused_must_use)]
#![allow(deprecated)] // seriously this is all deprecated
#![allow(unused_imports)]
+#![deprecated(since = "1.0.0",
+ reasons = "APIs have been replaced with new I/O modules such as \
+ std::{io, fs, net, process}")]
pub use self::SeekStyle::*;
pub use self::FileMode::*;
use fmt;
use io;
use marker::PhantomData;
-use old_io::stdio;
use rt::{self, unwind};
use sync::{Mutex, Condvar, Arc};
use thunk::Thunk;
name: Option<String>,
// The size of the stack for the spawned thread
stack_size: Option<usize>,
- // Thread-local stdout
- stdout: Option<Box<Writer + Send + 'static>>,
- // Thread-local stderr
- stderr: Option<Box<Writer + Send + 'static>>,
}
impl Builder {
Builder {
name: None,
stack_size: None,
- stdout: None,
- stderr: None,
}
}
/// Redirect thread-local stdout.
#[unstable(feature = "std_misc",
reason = "Will likely go away after proc removal")]
- pub fn stdout(mut self, stdout: Box<Writer + Send + 'static>) -> Builder {
- self.stdout = Some(stdout);
+ #[deprecated(since = "1.0.0",
+ reason = "the old I/O module is deprecated and this function \
+ will be removed with no replacement")]
+ #[allow(deprecated)]
+ pub fn stdout(self, _stdout: Box<Writer + Send + 'static>) -> Builder {
self
}
/// Redirect thread-local stderr.
#[unstable(feature = "std_misc",
reason = "Will likely go away after proc removal")]
- pub fn stderr(mut self, stderr: Box<Writer + Send + 'static>) -> Builder {
- self.stderr = Some(stderr);
+ #[deprecated(since = "1.0.0",
+ reason = "the old I/O module is deprecated and this function \
+ will be removed with no replacement")]
+ #[allow(deprecated)]
+ pub fn stderr(self, _stderr: Box<Writer + Send + 'static>) -> Builder {
self
}
}
fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
- let Builder { name, stack_size, stdout, stderr } = self;
+ let Builder { name, stack_size } = self;
let stack_size = stack_size.unwrap_or(rt::min_stack());
}
let mut output = None;
- let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
- Thunk::new(move || {
- let _ = stdout.map(stdio::set_stdout);
- let _ = stderr.map(stdio::set_stderr);
- f.invoke(())
- })
- } else {
- f
- };
-
let try_result = {
let ptr = &mut output;