diff options
| author | bors <bors@rust-lang.org> | 2015-03-13 20:22:16 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2015-03-13 20:22:16 +0000 |
| commit | 3e4be02b80a3dd27bce20870958fe0aef7e7336d (patch) | |
| tree | 156b54e84eeb1df2818be29b53ab7f35b5bc80f0 /src/libstd | |
| parent | 9eb69abad8ffbce840e7dc7038ddea434dc987f1 (diff) | |
| parent | 981bf5f690d1d7c5cf3e1419ac7a7c86dbc7a4d5 (diff) | |
| download | rust-3e4be02b80a3dd27bce20870958fe0aef7e7336d.tar.gz rust-3e4be02b80a3dd27bce20870958fe0aef7e7336d.zip | |
Auto merge of #23292 - alexcrichton:stabilize-io, r=aturon
The new `std::io` module has had some time to bake now, and this commit
stabilizes its functionality. There are still portions of the module which
remain unstable, and below contains a summart of the actions taken.
This commit also deprecates the entire contents of the `old_io` module in a
blanket fashion. All APIs should now have a reasonable replacement in the
new I/O modules.
Stable APIs:
* `std::io` (the name)
* `std::io::prelude` (the name)
* `Read`
* `Read::read`
* `Read::{read_to_end, read_to_string}` after being modified to return a `usize`
for the number of bytes read.
* `ReadExt`
* `Write`
* `Write::write`
* `Write::{write_all, write_fmt}`
* `WriteExt`
* `BufRead`
* `BufRead::{fill_buf, consume}`
* `BufRead::{read_line, read_until}` after being modified to return a `usize`
for the number of bytes read.
* `BufReadExt`
* `BufReader`
* `BufReader::{new, with_capacity}`
* `BufReader::{get_ref, get_mut, into_inner}`
* `{Read,BufRead} for BufReader`
* `BufWriter`
* `BufWriter::{new, with_capacity}`
* `BufWriter::{get_ref, get_mut, into_inner}`
* `Write for BufWriter`
* `IntoInnerError`
* `IntoInnerError::{error, into_inner}`
* `{Error,Display} for IntoInnerError`
* `LineWriter`
* `LineWriter::{new, with_capacity}` - `with_capacity` was added
* `LineWriter::{get_ref, get_mut, into_inner}` - `get_mut` was added)
* `Write for LineWriter`
* `BufStream`
* `BufStream::{new, with_capacities}`
* `BufStream::{get_ref, get_mut, into_inner}`
* `{BufRead,Read,Write} for BufStream`
* `stdin`
* `Stdin`
* `Stdin::lock`
* `Stdin::read_line` - added method
* `StdinLock`
* `Read for Stdin`
* `{Read,BufRead} for StdinLock`
* `stdout`
* `Stdout`
* `Stdout::lock`
* `StdoutLock`
* `Write for Stdout`
* `Write for StdoutLock`
* `stderr`
* `Stderr`
* `Stderr::lock`
* `StderrLock`
* `Write for Stderr`
* `Write for StderrLock`
* `io::Result`
* `io::Error`
* `io::Error::last_os_error`
* `{Display, Error} for Error`
Unstable APIs:
(reasons can be found in the commit itself)
* `Write::flush`
* `Seek`
* `ErrorKind`
* `Error::new`
* `Error::from_os_error`
* `Error::kind`
Deprecated APIs
* `Error::description` - available via the `Error` trait
* `Error::detail` - available via the `Display` implementation
* `thread::Builder::{stdout, stderr}`
Changes in functionality:
* `old_io::stdio::set_stderr` is now a noop as the infrastructure for printing
backtraces has migrated to `std::io`.
[breaking-change]
Diffstat (limited to 'src/libstd')
35 files changed, 384 insertions, 281 deletions
diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 44564ebf53d..677894ba6e4 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -17,6 +17,7 @@ use io; use iter::IteratorExt; use libc; use mem; +#[allow(deprecated)] use old_io; use ops::Deref; use option::Option::{self, Some, None}; @@ -298,6 +299,7 @@ impl FromError<NulError> for io::Error { } #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] impl FromError<NulError> for old_io::IoError { fn from_error(_: NulError) -> old_io::IoError { old_io::IoError { diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 3603f127504..03416eb86a0 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -16,8 +16,7 @@ use prelude::v1::*; 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; @@ -28,6 +27,7 @@ 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>>, @@ -35,11 +35,13 @@ pub struct BufReader<R> { 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, @@ -48,6 +50,7 @@ impl<R: Read> BufReader<R> { } /// 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. @@ -55,14 +58,17 @@ impl<R: Read> BufReader<R> { /// # 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 @@ -77,6 +83,7 @@ impl<R: Read> Read for BufReader<R> { } } +#[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 @@ -112,6 +119,7 @@ impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug { /// 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>, @@ -120,15 +128,18 @@ pub struct BufWriter<W> { /// 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), @@ -148,6 +159,7 @@ impl<W: Write> BufWriter<W> { break; } Ok(n) => written += n, + Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => { ret = Err(e); break } } @@ -165,6 +177,7 @@ impl<W: Write> BufWriter<W> { } /// 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. @@ -172,11 +185,13 @@ impl<W: Write> BufWriter<W> { /// # 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)), @@ -185,6 +200,7 @@ impl<W: Write> BufWriter<W> { } } +#[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() { @@ -224,23 +240,30 @@ impl<W> IntoInnerError<W> { /// 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) @@ -251,26 +274,41 @@ impl<W> fmt::Display for IntoInnerError<W> { /// (`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) @@ -278,6 +316,7 @@ impl<W: Write> LineWriter<W> { } } +#[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') { @@ -320,12 +359,13 @@ impl<W: Read> Read for InternalBufWriter<W> { /// 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>> } @@ -333,6 +373,7 @@ pub struct BufStream<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); @@ -343,11 +384,13 @@ impl<S: Read + Write> BufStream<S> { /// 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() @@ -359,6 +402,7 @@ impl<S: Read + Write> BufStream<S> { /// /// 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() @@ -368,6 +412,7 @@ impl<S: Read + Write> BufStream<S> { /// /// 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)| { @@ -378,17 +423,20 @@ impl<S: Read + Write> BufStream<S> { } } +#[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) diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index 9f3cd8c8b15..530c6728107 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -10,7 +10,7 @@ use boxed::Box; use clone::Clone; -use error::Error as StdError; +use error; use fmt; use option::Option::{self, Some, None}; use result; @@ -22,6 +22,7 @@ use sys; /// /// 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 @@ -31,6 +32,7 @@ pub type Result<T> = result::Result<T, Error>; /// `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, } @@ -50,6 +52,10 @@ struct Custom { /// 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, @@ -96,6 +102,9 @@ pub enum ErrorKind { 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 { @@ -113,16 +122,20 @@ impl 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), @@ -131,6 +144,9 @@ impl Error { } /// 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", @@ -139,6 +155,8 @@ impl 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)), @@ -147,6 +165,7 @@ impl Error { } } +#[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.repr { @@ -173,7 +192,8 @@ impl fmt::Display for Error { } } -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", diff --git a/src/libstd/io/impls.rs b/src/libstd/io/impls.rs index c968415d3ef..16298240acf 100644 --- a/src/libstd/io/impls.rs +++ b/src/libstd/io/impls.rs @@ -27,10 +27,10 @@ impl<'a, R: Read + ?Sized> Read for &'a mut R { 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) } } @@ -53,10 +53,10 @@ impl<'a, S: Seek + ?Sized> Seek for &'a mut S { 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) } } @@ -66,10 +66,10 @@ impl<R: Read + ?Sized> Read for Box<R> { 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) } } @@ -92,10 +92,10 @@ impl<S: Seek + ?Sized> Seek for Box<S> { 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) } } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 9137068076b..3fddaaad807 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -14,13 +14,11 @@ //! > 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; @@ -41,6 +39,8 @@ pub use self::error::{Result, Error, ErrorKind}; pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat}; pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr}; pub use self::stdio::{StdoutLock, StderrLock, StdinLock}; +#[doc(no_inline, hidden)] +pub use self::stdio::set_panic; #[macro_use] mod lazy; @@ -111,8 +111,8 @@ fn with_end_to_cap<F>(v: &mut Vec<u8>, f: F) -> Result<usize> // 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] @@ -126,7 +126,7 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<()> 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)) }) @@ -137,14 +137,15 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<()> } } -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), } @@ -159,6 +160,7 @@ fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<()> { /// 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. @@ -187,6 +189,7 @@ pub trait 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`. @@ -198,7 +201,8 @@ pub trait Read { /// 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 /// @@ -209,19 +213,24 @@ pub trait Read { /// 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 @@ -233,18 +242,13 @@ pub trait Read { // 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. /// @@ -253,7 +257,7 @@ pub trait ReadExt: Read + Sized { /// `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 } } @@ -270,7 +274,7 @@ pub trait ReadExt: Read + Sized { #[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 } } @@ -280,7 +284,7 @@ pub trait ReadExt: Read + Sized { /// 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 } } @@ -291,7 +295,7 @@ pub trait ReadExt: Read + Sized { /// 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 } } @@ -304,13 +308,11 @@ pub trait ReadExt: Read + Sized { #[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, @@ -322,6 +324,7 @@ impl<T: Read> ReadExt for T {} /// 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. /// @@ -347,6 +350,7 @@ pub trait Write { /// /// 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 @@ -356,6 +360,7 @@ pub trait Write { /// /// 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. @@ -368,6 +373,7 @@ pub trait 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) { @@ -396,6 +402,7 @@ pub trait Write { /// # 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 @@ -422,18 +429,13 @@ pub trait Write { 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. @@ -446,19 +448,21 @@ pub trait WriteExt: Write + Sized { #[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 /// @@ -479,6 +483,7 @@ pub trait Seek { /// 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), @@ -499,7 +504,8 @@ pub enum SeekFrom { } 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() { @@ -519,8 +525,9 @@ fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) } }; r.consume(used); + read += used; if done || used == 0 { - return Ok(()); + return Ok(read); } } } @@ -530,6 +537,7 @@ fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) /// /// 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. /// @@ -546,10 +554,16 @@ pub trait BufRead: Read { /// /// 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. @@ -560,7 +574,8 @@ pub trait BufRead: Read { /// `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 /// @@ -569,7 +584,8 @@ pub trait BufRead: Read { /// /// 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) } @@ -581,7 +597,8 @@ pub trait BufRead: Read { /// 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 /// @@ -589,17 +606,14 @@ pub trait BufRead: Read { /// 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`. /// @@ -611,7 +625,7 @@ pub trait BufReadExt: BufRead + Sized { /// 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 } } @@ -624,22 +638,21 @@ pub trait BufReadExt: BufRead + Sized { /// 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)); @@ -732,11 +745,13 @@ impl<T: BufRead> BufRead for Take<T> { /// 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)); @@ -771,6 +786,7 @@ impl<R: Read> Iterator for Bytes<R> { /// 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, } @@ -778,6 +794,7 @@ pub struct Chars<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. @@ -787,6 +804,7 @@ pub enum CharsError { Other(Error), } +#[unstable(feature = "io", reason = "awaiting stability of ReadExt::chars")] impl<R: Read> Iterator for Chars<R> { type Item = result::Result<char, CharsError>; @@ -818,14 +836,15 @@ impl<R: Read> Iterator for Chars<R> { } } -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(), @@ -833,6 +852,7 @@ impl StdError for CharsError { } } +#[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 { @@ -848,19 +868,21 @@ impl fmt::Display for CharsError { /// 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(); } @@ -887,8 +909,8 @@ impl<B: BufRead> Iterator for Lines<B> { 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(); } @@ -910,18 +932,18 @@ mod tests { fn read_until() { let mut buf = Cursor::new(b"12"); let mut v = Vec::new(); - assert_eq!(buf.read_until(b'3', &mut v), Ok(())); + assert_eq!(buf.read_until(b'3', &mut v), Ok(2)); assert_eq!(v, b"12"); let mut buf = Cursor::new(b"1233"); let mut v = Vec::new(); - assert_eq!(buf.read_until(b'3', &mut v), Ok(())); + assert_eq!(buf.read_until(b'3', &mut v), Ok(3)); assert_eq!(v, b"123"); v.truncate(0); - assert_eq!(buf.read_until(b'3', &mut v), Ok(())); + assert_eq!(buf.read_until(b'3', &mut v), Ok(1)); assert_eq!(v, b"3"); v.truncate(0); - assert_eq!(buf.read_until(b'3', &mut v), Ok(())); + assert_eq!(buf.read_until(b'3', &mut v), Ok(0)); assert_eq!(v, []); } @@ -943,18 +965,18 @@ mod tests { fn read_line() { let mut buf = Cursor::new(b"12"); let mut v = String::new(); - assert_eq!(buf.read_line(&mut v), Ok(())); + assert_eq!(buf.read_line(&mut v), Ok(2)); assert_eq!(v, "12"); let mut buf = Cursor::new(b"12\n\n"); let mut v = String::new(); - assert_eq!(buf.read_line(&mut v), Ok(())); + assert_eq!(buf.read_line(&mut v), Ok(3)); assert_eq!(v, "12\n"); v.truncate(0); - assert_eq!(buf.read_line(&mut v), Ok(())); + assert_eq!(buf.read_line(&mut v), Ok(1)); assert_eq!(v, "\n"); v.truncate(0); - assert_eq!(buf.read_line(&mut v), Ok(())); + assert_eq!(buf.read_line(&mut v), Ok(0)); assert_eq!(v, ""); } @@ -976,12 +998,12 @@ mod tests { fn read_to_end() { let mut c = Cursor::new(b""); let mut v = Vec::new(); - assert_eq!(c.read_to_end(&mut v), Ok(())); + assert_eq!(c.read_to_end(&mut v), Ok(0)); assert_eq!(v, []); let mut c = Cursor::new(b"1"); let mut v = Vec::new(); - assert_eq!(c.read_to_end(&mut v), Ok(())); + assert_eq!(c.read_to_end(&mut v), Ok(1)); assert_eq!(v, b"1"); } @@ -989,12 +1011,12 @@ mod tests { fn read_to_string() { let mut c = Cursor::new(b""); let mut v = String::new(); - assert_eq!(c.read_to_string(&mut v), Ok(())); + assert_eq!(c.read_to_string(&mut v), Ok(0)); assert_eq!(v, ""); let mut c = Cursor::new(b"1"); let mut v = String::new(); - assert_eq!(c.read_to_string(&mut v), Ok(())); + assert_eq!(c.read_to_string(&mut v), Ok(1)); assert_eq!(v, "1"); let mut c = Cursor::new(b"\xff"); diff --git a/src/libstd/io/prelude.rs b/src/libstd/io/prelude.rs index 637b1950985..6bf0ebd1a59 100644 --- a/src/libstd/io/prelude.rs +++ b/src/libstd/io/prelude.rs @@ -21,7 +21,9 @@ //! `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 diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 4027f741654..3b4e396953d 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -86,6 +86,7 @@ impl Write for StderrRaw { /// /// 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>>>, } @@ -94,6 +95,7 @@ pub struct Stdin { /// /// 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>>, } @@ -110,6 +112,7 @@ pub struct StdinLock<'a> { /// /// 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 { @@ -136,30 +139,41 @@ impl 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) } @@ -186,6 +200,7 @@ const OUT_MAX: usize = ::usize::MAX; /// 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 @@ -197,6 +212,7 @@ pub struct Stdout { /// /// 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>>, } @@ -211,6 +227,7 @@ pub struct StdoutLock<'a> { /// /// 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 { @@ -228,11 +245,13 @@ impl 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) @@ -247,6 +266,7 @@ impl Write for Stdout { 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)]) @@ -257,6 +277,7 @@ impl<'a> Write for StdoutLock<'a> { /// 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>>, } @@ -265,6 +286,7 @@ pub struct Stderr { /// /// 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>, } @@ -278,6 +300,7 @@ pub struct StderrLock<'a> { /// /// 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 { @@ -295,11 +318,13 @@ impl 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) @@ -314,9 +339,33 @@ impl Write for Stderr { 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)]) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } + +/// Resets the task-local stdout handle to the specified writer +/// +/// This will replace the current task's stdout handle, returning the old +/// handle. All future calls to `print` and friends will emit their output to +/// this specified handle. +/// +/// Note that this does not need to be called for all new tasks; the default +/// output handle is to the process's stdout stream. +#[unstable(feature = "set_panic", + reason = "this function may disappear completely or be replaced \ + with a more general mechanism")] +#[doc(hidden)] +pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> { + use panicking::LOCAL_STDERR; + use mem; + LOCAL_STDERR.with(move |slot| { + mem::replace(&mut *slot.borrow_mut(), Some(sink)) + }).and_then(|mut s| { + let _ = s.flush(); + Some(s) + }) +} diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index a05d6752073..81e2113cfdf 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -298,6 +298,7 @@ mod std { pub use sync; // used for select!() pub use error; // used for try!() pub use fmt; // used for any formatting strings + #[allow(deprecated)] pub use old_io; // used for println!() pub use option; // used for bitflags!{} pub use rt; // used for panic!() diff --git a/src/libstd/old_io/mod.rs b/src/libstd/old_io/mod.rs index f71698fa725..9d438978f42 100644 --- a/src/libstd/old_io/mod.rs +++ b/src/libstd/old_io/mod.rs @@ -242,6 +242,9 @@ #![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::*; diff --git a/src/libstd/old_io/stdio.rs b/src/libstd/old_io/stdio.rs index 70e8a4ceff0..34b4ec94a44 100644 --- a/src/libstd/old_io/stdio.rs +++ b/src/libstd/old_io/stdio.rs @@ -31,10 +31,9 @@ use boxed; use boxed::Box; use cell::RefCell; use clone::Clone; -use panicking::LOCAL_STDERR; use fmt; use old_io::{Reader, Writer, IoResult, IoError, OtherIoError, Buffer, - standard_error, EndOfFile, LineBufferedWriter, BufferedReader}; + standard_error, EndOfFile, LineBufferedWriter, BufferedReader}; use marker::{Sync, Send}; use libc; use mem; @@ -319,14 +318,10 @@ pub fn set_stdout(stdout: Box<Writer + Send>) -> Option<Box<Writer + Send>> { /// /// Note that this does not need to be called for all new tasks; the default /// output handle is to the process's stderr stream. -pub fn set_stderr(stderr: Box<Writer + Send>) -> Option<Box<Writer + Send>> { - let mut new = Some(stderr); - LOCAL_STDERR.with(|slot| { - mem::replace(&mut *slot.borrow_mut(), new.take()) - }).and_then(|mut s| { - let _ = s.flush(); - Some(s) - }) +#[unstable(feature = "old_io")] +#[deprecated(since = "1.0.0", reason = "replaced with std::io::set_panic")] +pub fn set_stderr(_stderr: Box<Writer + Send>) -> Option<Box<Writer + Send>> { + None } // Helper to access the local task's stdout handle @@ -554,19 +549,4 @@ mod tests { }); assert_eq!(r.read_to_string().unwrap(), "hello!\n"); } - - #[test] - fn capture_stderr() { - use old_io::{ChanReader, ChanWriter, Reader}; - - let (tx, rx) = channel(); - let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); - // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. - let _t = thread::spawn(move || -> () { - set_stderr(Box::new(w)); - panic!("my special message"); - }); - let s = r.read_to_string().unwrap(); - assert!(s.contains("my special message")); - } } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 53882c7b833..866f7caffe8 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -25,6 +25,7 @@ //! OS-ignorant code by default. #![unstable(feature = "os")] +#![deprecated(since = "1.0.0", reason = "replaced with std::env APIs")] #![allow(missing_docs)] #![allow(non_snake_case)] diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs index 2e05f6d974e..3e0584d9ab4 100644 --- a/src/libstd/panicking.rs +++ b/src/libstd/panicking.rs @@ -11,29 +11,22 @@ #![unstable(feature = "std_misc")] use prelude::v1::*; +use io::prelude::*; use any::Any; use cell::RefCell; -use old_io::IoResult; use rt::{backtrace, unwind}; -use rt::util::{Stderr, Stdio}; +use sys::stdio::Stderr; use thread; // Defined in this module instead of old_io::stdio so that the unwinding thread_local! { - pub static LOCAL_STDERR: RefCell<Option<Box<Writer + Send>>> = { + pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = { RefCell::new(None) } } -impl Writer for Stdio { - fn write_all(&mut self, bytes: &[u8]) -> IoResult<()> { - let _ = self.write_bytes(bytes); - Ok(()) - } -} - -pub fn on_panic(obj: &(Any+Send), file: &'static str, line: uint) { +pub fn on_panic(obj: &(Any+Send), file: &'static str, line: usize) { let msg = match obj.downcast_ref::<&'static str>() { Some(s) => *s, None => match obj.downcast_ref::<String>() { @@ -41,7 +34,7 @@ pub fn on_panic(obj: &(Any+Send), file: &'static str, line: uint) { None => "Box<Any>", } }; - let mut err = Stderr; + let mut err = Stderr::new(); let thread = thread::current(); let name = thread.name().unwrap_or("<unnamed>"); let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take()); diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index dc557403153..e72fd7b3320 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -11,16 +11,14 @@ // ignore-lexer-test FIXME #15677 use prelude::v1::*; +use io::prelude::*; -use cmp; use env; use fmt; use intrinsics; -use libc::{self, uintptr_t}; -use os; -use slice; -use str; +use libc::uintptr_t; use sync::atomic::{self, Ordering}; +use sys::stdio::Stderr; /// Dynamically inquire about whether we're running under V. /// You should usually not use this unless your test definitely @@ -62,7 +60,9 @@ pub fn min_stack() -> uint { /// Get's the number of scheduler threads requested by the environment /// either `RUST_THREADS` or `num_cpus`. +#[allow(deprecated)] pub fn default_sched_threads() -> uint { + use os; match env::var("RUST_THREADS") { Ok(nstr) => { let opt_n: Option<uint> = nstr.parse().ok(); @@ -88,76 +88,17 @@ pub fn default_sched_threads() -> uint { pub const ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert); -pub struct Stdio(libc::c_int); - -#[allow(non_upper_case_globals)] -pub const Stdout: Stdio = Stdio(libc::STDOUT_FILENO); -#[allow(non_upper_case_globals)] -pub const Stderr: Stdio = Stdio(libc::STDERR_FILENO); - -impl Stdio { - pub fn write_bytes(&mut self, data: &[u8]) { - #[cfg(unix)] - type WriteLen = libc::size_t; - #[cfg(windows)] - type WriteLen = libc::c_uint; - unsafe { - let Stdio(fd) = *self; - libc::write(fd, - data.as_ptr() as *const libc::c_void, - data.len() as WriteLen); - } - } -} - -impl fmt::Write for Stdio { - fn write_str(&mut self, data: &str) -> fmt::Result { - self.write_bytes(data.as_bytes()); - Ok(()) // yes, we're lying - } -} - pub fn dumb_print(args: fmt::Arguments) { - let _ = Stderr.write_fmt(args); + let _ = write!(&mut Stderr::new(), "{}", args); } pub fn abort(args: fmt::Arguments) -> ! { - use fmt::Write; - - struct BufWriter<'a> { - buf: &'a mut [u8], - pos: uint, - } - impl<'a> fmt::Write for BufWriter<'a> { - fn write_str(&mut self, bytes: &str) -> fmt::Result { - let left = &mut self.buf[self.pos..]; - let to_write = &bytes.as_bytes()[..cmp::min(bytes.len(), left.len())]; - slice::bytes::copy_memory(left, to_write); - self.pos += to_write.len(); - Ok(()) - } - } - - // Convert the arguments into a stack-allocated string - let mut msg = [0; 512]; - let mut w = BufWriter { buf: &mut msg, pos: 0 }; - let _ = write!(&mut w, "{}", args); - let msg = str::from_utf8(&w.buf[..w.pos]).unwrap_or("aborted"); - let msg = if msg.is_empty() {"aborted"} else {msg}; - rterrln!("fatal runtime error: {}", msg); + rterrln!("fatal runtime error: {}", args); unsafe { intrinsics::abort(); } } pub unsafe fn report_overflow() { use thread; - - // See the message below for why this is not emitted to the - // ^ Where did the message below go? - // task's logger. This has the additional conundrum of the - // logger may not be initialized just yet, meaning that an FFI - // call would happen to initialized it (calling out to libuv), - // and the FFI call needs 2MB of stack when we just ran out. - rterrln!("\nthread '{}' has overflowed its stack", thread::current().name().unwrap_or("<unknown>")); } diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index 50a9f204799..c42a755b444 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -9,8 +9,9 @@ // except according to those terms. use prelude::v1::*; +use io::prelude::*; -use old_io::IoResult; +use io; #[cfg(target_pointer_width = "64")] pub const HEX_WIDTH: uint = 18; @@ -35,7 +36,7 @@ pub const HEX_WIDTH: uint = 10; // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. -pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { +pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> { // First validate the symbol. If it doesn't look like anything we're // expecting, we just print it literally. Note that we must handle non-rust // symbols because we could have any function in the backtrace. @@ -72,12 +73,12 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { // Alright, let's do this. if !valid { - try!(writer.write_str(s)); + try!(writer.write_all(s.as_bytes())); } else { let mut first = true; while inner.len() > 0 { if !first { - try!(writer.write_str("::")); + try!(writer.write_all(b"::")); } else { first = false; } @@ -93,11 +94,11 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { macro_rules! demangle { ($($pat:expr, => $demangled:expr),*) => ({ $(if rest.starts_with($pat) { - try!(writer.write_str($demangled)); + try!(writer.write_all($demangled)); rest = &rest[$pat.len()..]; } else)* { - try!(writer.write_str(rest)); + try!(writer.write_all(rest.as_bytes())); break; } @@ -106,29 +107,29 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { // see src/librustc/back/link.rs for these mappings demangle! ( - "$SP$", => "@", - "$BP$", => "*", - "$RF$", => "&", - "$LT$", => "<", - "$GT$", => ">", - "$LP$", => "(", - "$RP$", => ")", - "$C$", => ",", + "$SP$", => b"@", + "$BP$", => b"*", + "$RF$", => b"&", + "$LT$", => b"<", + "$GT$", => b">", + "$LP$", => b"(", + "$RP$", => b")", + "$C$", => b",", // in theory we can demangle any Unicode code point, but // for simplicity we just catch the common ones. - "$u7e$", => "~", - "$u20$", => " ", - "$u27$", => "'", - "$u5b$", => "[", - "$u5d$", => "]" + "$u7e$", => b"~", + "$u20$", => b" ", + "$u27$", => b"'", + "$u5b$", => b"[", + "$u5d$", => b"]" ) } else { let idx = match rest.find('$') { None => rest.len(), Some(i) => i, }; - try!(writer.write_str(&rest[..idx])); + try!(writer.write_all(rest[..idx].as_bytes())); rest = &rest[idx..]; } } diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs index 9a89b290980..29c05b1e0d8 100644 --- a/src/libstd/sys/common/mod.rs +++ b/src/libstd/sys/common/mod.rs @@ -37,6 +37,7 @@ pub mod wtf8; // common error constructors +#[allow(deprecated)] pub fn eof() -> IoError { IoError { kind: old_io::EndOfFile, @@ -45,6 +46,7 @@ pub fn eof() -> IoError { } } +#[allow(deprecated)] pub fn timeout(desc: &'static str) -> IoError { IoError { kind: old_io::TimedOut, @@ -53,6 +55,7 @@ pub fn timeout(desc: &'static str) -> IoError { } } +#[allow(deprecated)] pub fn short_write(n: uint, desc: &'static str) -> IoError { IoError { kind: if n == 0 { old_io::TimedOut } else { old_io::ShortWrite(n) }, @@ -61,6 +64,7 @@ pub fn short_write(n: uint, desc: &'static str) -> IoError { } } +#[allow(deprecated)] pub fn unimpl() -> IoError { IoError { kind: old_io::IoUnavailable, @@ -70,6 +74,7 @@ pub fn unimpl() -> IoError { } // unix has nonzero values as errors +#[allow(deprecated)] pub fn mkerr_libc<T: Int>(ret: T) -> IoResult<()> { if ret != Int::zero() { Err(last_error()) diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 24d709e9928..3fa9f5d07aa 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -84,9 +84,10 @@ /// all unix platforms we support right now, so it at least gets the job done. use prelude::v1::*; +use io::prelude::*; use ffi::CStr; -use old_io::IoResult; +use io; use libc; use mem; use str; @@ -105,7 +106,7 @@ use sys_common::backtrace::*; /// only viable option. #[cfg(all(target_os = "ios", target_arch = "arm"))] #[inline(never)] -pub fn write(w: &mut Writer) -> IoResult<()> { +pub fn write(w: &mut Write) -> io::Result<()> { use result; extern { @@ -135,13 +136,11 @@ pub fn write(w: &mut Writer) -> IoResult<()> { #[cfg(not(all(target_os = "ios", target_arch = "arm")))] #[inline(never)] // if we know this is a function call, we can skip it when // tracing -pub fn write(w: &mut Writer) -> IoResult<()> { - use old_io::IoError; - +pub fn write(w: &mut Write) -> io::Result<()> { struct Context<'a> { idx: int, - writer: &'a mut (Writer+'a), - last_error: Option<IoError>, + writer: &'a mut (Write+'a), + last_error: Option<io::Error>, } // When using libbacktrace, we use some necessary global state, so we @@ -223,8 +222,8 @@ pub fn write(w: &mut Writer) -> IoResult<()> { } #[cfg(any(target_os = "macos", target_os = "ios"))] -fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void, - _symaddr: *mut libc::c_void) -> IoResult<()> { +fn print(w: &mut Write, idx: int, addr: *mut libc::c_void, + _symaddr: *mut libc::c_void) -> io::Result<()> { use intrinsics; #[repr(C)] struct Dl_info { @@ -249,8 +248,8 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void, } #[cfg(not(any(target_os = "macos", target_os = "ios")))] -fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void, - symaddr: *mut libc::c_void) -> IoResult<()> { +fn print(w: &mut Write, idx: int, addr: *mut libc::c_void, + symaddr: *mut libc::c_void) -> io::Result<()> { use env; use ffi::AsOsStr; use os::unix::prelude::*; @@ -442,8 +441,8 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void, } // Finally, after all that work above, we can emit a symbol. -fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, - s: Option<&[u8]>) -> IoResult<()> { +fn output(w: &mut Write, idx: int, addr: *mut libc::c_void, + s: Option<&[u8]>) -> io::Result<()> { try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH)); match s.and_then(|s| str::from_utf8(s).ok()) { Some(string) => try!(demangle(w, string)), @@ -453,8 +452,8 @@ fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, } #[allow(dead_code)] -fn output_fileline(w: &mut Writer, file: &[u8], line: libc::c_int, - more: bool) -> IoResult<()> { +fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int, + more: bool) -> io::Result<()> { let file = str::from_utf8(file).ok().unwrap_or("<unknown>"); // prior line: " ##: {:2$} - func" try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH)); diff --git a/src/libstd/sys/unix/ext.rs b/src/libstd/sys/unix/ext.rs index ca7f7c4c0ca..3dd05319194 100644 --- a/src/libstd/sys/unix/ext.rs +++ b/src/libstd/sys/unix/ext.rs @@ -43,7 +43,7 @@ use sys::os_str::Buf; use sys_common::{AsInner, AsInnerMut, IntoInner, FromInner}; use libc::{self, gid_t, uid_t}; -use old_io; +#[allow(deprecated)] use old_io; /// Raw file descriptors. pub type Fd = libc::c_int; @@ -67,6 +67,7 @@ impl AsRawFd for fs::File { } } +#[allow(deprecated)] impl AsRawFd for old_io::pipe::PipeStream { fn as_raw_fd(&self) -> Fd { self.as_inner().fd() diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index f23619955e2..c839ce65298 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -9,6 +9,7 @@ // except according to those terms. //! Blocking posix-based file I/O +#![allow(deprecated)] #![allow(deprecated)] // this module itself is essentially deprecated diff --git a/src/libstd/sys/unix/helper_signal.rs b/src/libstd/sys/unix/helper_signal.rs index ed9bd0a239f..ff29dea254f 100644 --- a/src/libstd/sys/unix/helper_signal.rs +++ b/src/libstd/sys/unix/helper_signal.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(deprecated)] + use libc; use os; diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index 865ea987279..a8cee74828d 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -60,10 +60,12 @@ pub type wrlen = libc::size_t; pub type msglen_t = libc::size_t; pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); } +#[allow(deprecated)] pub fn last_error() -> IoError { decode_error_detailed(os::errno() as i32) } +#[allow(deprecated)] pub fn last_net_error() -> IoError { last_error() } @@ -72,6 +74,7 @@ extern "system" { fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char; } +#[allow(deprecated)] pub fn last_gai_error(s: libc::c_int) -> IoError { let mut err = decode_error(s); @@ -83,6 +86,7 @@ pub fn last_gai_error(s: libc::c_int) -> IoError { } /// Convert an `errno` value into a high-level error variant and description. +#[allow(deprecated)] pub fn decode_error(errno: i32) -> IoError { // FIXME: this should probably be a bit more descriptive... let (kind, desc) = match errno { @@ -119,12 +123,14 @@ pub fn decode_error(errno: i32) -> IoError { IoError { kind: kind, desc: desc, detail: None } } +#[allow(deprecated)] pub fn decode_error_detailed(errno: i32) -> IoError { let mut err = decode_error(errno); err.detail = Some(os::error_string(errno)); err } +#[allow(deprecated)] pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno as libc::c_int { libc::ECONNREFUSED => ErrorKind::ConnectionRefused, @@ -155,6 +161,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { } #[inline] +#[allow(deprecated)] pub fn retry<T, F> (mut f: F) -> T where T: SignedInt, F: FnMut() -> T, @@ -194,11 +201,13 @@ pub fn ms_to_timeval(ms: u64) -> libc::timeval { } } +#[allow(deprecated)] pub fn wouldblock() -> bool { let err = os::errno(); err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32 } +#[allow(deprecated)] pub fn set_nonblocking(fd: sock_t, nb: bool) { let set = nb as libc::c_int; mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) })).unwrap(); diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 3266da5eb31..d332556d188 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -22,7 +22,7 @@ use io; use iter; use libc::{self, c_int, c_char, c_void}; use mem; -use old_io::{IoError, IoResult}; +#[allow(deprecated)] use old_io::{IoError, IoResult}; use ptr; use path::{self, PathBuf}; use slice; @@ -398,7 +398,7 @@ pub fn env() -> Env { let mut environ = *environ(); if environ as usize == 0 { panic!("os::env() failure getting env string from OS: {}", - IoError::last_error()); + io::Error::last_os_error()); } let mut result = Vec::new(); while *environ != ptr::null() { @@ -434,7 +434,7 @@ pub fn setenv(k: &OsStr, v: &OsStr) { let k = k.to_cstring().unwrap(); let v = v.to_cstring().unwrap(); if libc::funcs::posix01::unistd::setenv(k.as_ptr(), v.as_ptr(), 1) != 0 { - panic!("failed setenv: {}", IoError::last_error()); + panic!("failed setenv: {}", io::Error::last_os_error()); } } } @@ -443,11 +443,12 @@ pub fn unsetenv(n: &OsStr) { unsafe { let nbuf = n.to_cstring().unwrap(); if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 { - panic!("failed unsetenv: {}", IoError::last_error()); + panic!("failed unsetenv: {}", io::Error::last_os_error()); } } } +#[allow(deprecated)] pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { let mut fds = [0; 2]; if libc::pipe(fds.as_mut_ptr()) == 0 { diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index 9cddfca69cb..daa981720f6 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(deprecated)] + use prelude::v1::*; use ffi::CString; diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index 2f9610fa5b5..5f5101e96d7 100644 --- a/src/libstd/sys/unix/stdio.rs +++ b/src/libstd/sys/unix/stdio.rs @@ -50,3 +50,13 @@ impl Stderr { return ret; } } + +// FIXME: right now this raw stderr handle is used in a few places because +// std::io::stderr_raw isn't exposed, but once that's exposed this impl +// should go away +impl io::Write for Stderr { + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + Stderr::write(self, data) + } + fn flush(&mut self) -> io::Result<()> { Ok(()) } +} diff --git a/src/libstd/sys/unix/timer.rs b/src/libstd/sys/unix/timer.rs index ce9748ede85..ef0274fdda9 100644 --- a/src/libstd/sys/unix/timer.rs +++ b/src/libstd/sys/unix/timer.rs @@ -46,6 +46,8 @@ //! //! Note that all time units in this file are in *milliseconds*. +#![allow(deprecated)] + use prelude::v1::*; use self::Req::*; diff --git a/src/libstd/sys/unix/tty.rs b/src/libstd/sys/unix/tty.rs index 1d74b36a625..f607f7c6a2f 100644 --- a/src/libstd/sys/unix/tty.rs +++ b/src/libstd/sys/unix/tty.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(deprecated)] + use prelude::v1::*; use sys::fs::FileDesc; diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index b464ba70911..8638099ca69 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -28,9 +28,10 @@ use prelude::v1::*; use dynamic_lib::DynamicLibrary; +use io; +use io::prelude::*; use ffi::CStr; use intrinsics; -use old_io::IoResult; use libc; use mem; use ptr; @@ -292,7 +293,7 @@ impl Drop for Cleanup { fn drop(&mut self) { (self.SymCleanup)(self.handle); } } -pub fn write(w: &mut Writer) -> IoResult<()> { +pub fn write(w: &mut Write) -> io::Result<()> { // According to windows documentation, all dbghelp functions are // single-threaded. static LOCK: StaticMutex = MUTEX_INIT; diff --git a/src/libstd/sys/windows/condvar.rs b/src/libstd/sys/windows/condvar.rs index 071637e3a93..67552255fdb 100644 --- a/src/libstd/sys/windows/condvar.rs +++ b/src/libstd/sys/windows/condvar.rs @@ -12,7 +12,7 @@ use prelude::v1::*; use cell::UnsafeCell; use libc::{self, DWORD}; -use os; +use sys::os; use sys::mutex::{self, Mutex}; use sys::sync as ffi; use time::Duration; @@ -46,7 +46,7 @@ impl Condvar { 0); if r == 0 { const ERROR_TIMEOUT: DWORD = 0x5B4; - debug_assert_eq!(os::errno() as uint, ERROR_TIMEOUT as uint); + debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize); false } else { true diff --git a/src/libstd/sys/windows/ext.rs b/src/libstd/sys/windows/ext.rs index 1d63da813c9..dc820a4ce45 100644 --- a/src/libstd/sys/windows/ext.rs +++ b/src/libstd/sys/windows/ext.rs @@ -25,6 +25,7 @@ use net; use sys::os_str::Buf; use sys_common::{AsInner, FromInner, AsInnerMut}; +#[allow(deprecated)] use old_io; /// Raw HANDLEs. @@ -52,6 +53,7 @@ impl AsRawHandle for fs::File { } } +#[allow(deprecated)] impl AsRawHandle for old_io::pipe::PipeStream { fn as_raw_handle(&self) -> Handle { self.as_inner().handle() diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 46085826e60..6b0f6a78c85 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -64,6 +64,7 @@ pub type msglen_t = libc::c_int; pub unsafe fn close_sock(sock: sock_t) { let _ = libc::closesocket(sock); } // windows has zero values as errors +#[allow(deprecated)] fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) @@ -72,6 +73,7 @@ fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { } } +#[allow(deprecated)] pub fn last_error() -> IoError { let errno = os::errno() as i32; let mut err = decode_error(errno); @@ -79,6 +81,7 @@ pub fn last_error() -> IoError { err } +#[allow(deprecated)] pub fn last_net_error() -> IoError { let errno = unsafe { c::WSAGetLastError() as i32 }; let mut err = decode_error(errno); @@ -86,11 +89,13 @@ pub fn last_net_error() -> IoError { err } +#[allow(deprecated)] pub fn last_gai_error(_errno: i32) -> IoError { last_net_error() } /// Convert an `errno` value into a high-level error variant and description. +#[allow(deprecated)] pub fn decode_error(errno: i32) -> IoError { let (kind, desc) = match errno { libc::EOF => (old_io::EndOfFile, "end of file"), @@ -134,6 +139,7 @@ pub fn decode_error(errno: i32) -> IoError { IoError { kind: kind, desc: desc, detail: None } } +#[allow(deprecated)] pub fn decode_error_detailed(errno: i32) -> IoError { let mut err = decode_error(errno); err.detail = Some(os::error_string(errno)); @@ -178,11 +184,13 @@ pub fn ms_to_timeval(ms: u64) -> libc::timeval { } } +#[allow(deprecated)] pub fn wouldblock() -> bool { let err = os::errno(); err == libc::WSAEWOULDBLOCK as i32 } +#[allow(deprecated)] pub fn set_nonblocking(fd: sock_t, nb: bool) { let mut set = nb as libc::c_ulong; if unsafe { c::ioctlsocket(fd, c::FIONBIO, &mut set) } != 0 { @@ -205,6 +213,7 @@ pub fn init_net() { } } +#[allow(deprecated)] pub fn to_utf16(s: Option<&str>) -> IoResult<Vec<u16>> { match s { Some(s) => Ok(to_utf16_os(OsStr::from_str(s))), @@ -283,6 +292,7 @@ fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()> } } +#[allow(deprecated)] fn fill_utf16_buf<F1, F2, T>(f1: F1, f2: F2) -> IoResult<T> where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, F2: FnOnce(&[u16]) -> T diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 89cf8a08a68..ecd538abfb4 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -22,6 +22,7 @@ use io; use libc::types::os::arch::extra::LPWCH; use libc::{self, c_int, c_void}; use mem; +#[allow(deprecated)] use old_io::{IoError, IoResult}; use ops::Range; use path::{self, PathBuf}; @@ -134,7 +135,7 @@ pub fn env() -> Env { let ch = GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", - IoError::last_error()); + io::Error::last_os_error()); } Env { base: ch, cur: ch } } @@ -269,7 +270,7 @@ pub fn setenv(k: &OsStr, v: &OsStr) { unsafe { if libc::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) == 0 { - panic!("failed to set env: {}", IoError::last_error()); + panic!("failed to set env: {}", io::Error::last_os_error()); } } } @@ -278,7 +279,7 @@ pub fn unsetenv(n: &OsStr) { let v = super::to_utf16_os(n); unsafe { if libc::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) == 0 { - panic!("failed to unset env: {}", IoError::last_error()); + panic!("failed to unset env: {}", io::Error::last_os_error()); } } } @@ -333,6 +334,7 @@ pub fn page_size() -> usize { } } +#[allow(deprecated)] pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { // Windows pipes work subtly differently than unix pipes, and their // inheritance has to be handled in a different way that I do not diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 1f228b7d32e..2b03e9e7431 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -84,6 +84,8 @@ //! the test suite passing (the suite is in libstd), and that's good enough for //! me! +#![allow(deprecated)] + use prelude::v1::*; use libc; diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index 72ce8b7c6e3..d1bff0e135d 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -135,6 +135,16 @@ impl Stderr { } } +// FIXME: right now this raw stderr handle is used in a few places because +// std::io::stderr_raw isn't exposed, but once that's exposed this impl +// should go away +impl io::Write for Stderr { + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + Stderr::write(self, data) + } + fn flush(&mut self) -> io::Result<()> { Ok(()) } +} + impl NoClose { fn new(handle: libc::HANDLE) -> NoClose { NoClose(Some(Handle::new(handle))) diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index a23a90a9cf8..91a7f694181 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -20,6 +20,8 @@ //! Other than that, the implementation is pretty straightforward in terms of //! the other two implementations of timers with nothing *that* new showing up. +#![allow(deprecated)] + use prelude::v1::*; use self::Req::*; diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index 37dce423a68..f542cb2323e 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -25,6 +25,8 @@ //! wrapper that performs encoding/decoding, this implementation should switch //! to working in raw UTF-16, with such a wrapper around it. +#![allow(deprecated)] + use prelude::v1::*; use old_io::{self, IoError, IoResult, MemReader}; diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 5c5f9f75fd9..adc3b77407a 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -148,7 +148,6 @@ use cell::UnsafeCell; use fmt; use io; use marker::PhantomData; -use old_io::stdio; use rt::{self, unwind}; use sync::{Mutex, Condvar, Arc}; use thunk::Thunk; @@ -165,10 +164,6 @@ pub struct Builder { 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 { @@ -179,8 +174,6 @@ impl Builder { Builder { name: None, stack_size: None, - stdout: None, - stderr: None, } } @@ -202,16 +195,22 @@ impl Builder { /// 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 } @@ -259,7 +258,7 @@ impl Builder { } 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()); @@ -290,16 +289,6 @@ impl Builder { } 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; @@ -916,20 +905,6 @@ mod test { } #[test] - fn test_stdout() { - let (tx, rx) = channel(); - let mut reader = ChanReader::new(rx); - let stdout = ChanWriter::new(tx); - - Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| { - print!("Hello, world!"); - }).unwrap().join(); - - let output = reader.read_to_string().unwrap(); - assert_eq!(output, "Hello, world!".to_string()); - } - - #[test] fn test_park_timeout_unpark_before() { for _ in 0..10 { thread::current().unpark(); |
