提交 b53695b4 编写于 作者: A Alex Crichton

rollup merge of #21835: alexcrichton/iov2

This commit is an implementation of [RFC 576][rfc] which adds back the `std::io`
module to the standard library. No functionality in `std::old_io` has been
deprecated just yet, and the new `std::io` module is behind the same `io`
feature gate.

[rfc]: https://github.com/rust-lang/rfcs/pull/576

A good bit of functionality was copied over from `std::old_io`, but many tweaks
were required for the new method signatures. Behavior such as precisely when
buffered objects call to the underlying object may have been tweaked slightly in
the transition. All implementations were audited to use composition wherever
possible. For example the custom `pos` and `cap` cursors in `BufReader` were
removed in favor of just using `Cursor<Vec<u8>>`.

A few liberties were taken during this implementation which were not explicitly
spelled out in the RFC:

* The old `LineBufferedWriter` is now named `LineWriter`
* The internal representation of `Error` now favors OS error codes (a
  0-allocation path) and contains a `Box` for extra semantic data.
* The io prelude currently reexports `Seek` as `NewSeek` to prevent conflicts
  with the real prelude reexport of `old_io::Seek`
* The `chars` method was moved from `BufReadExt` to `ReadExt`.
* The `chars` iterator returns a custom error with a variant that explains that
  the data was not valid UTF-8.
此差异已折叠。
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(missing_copy_implementations)]
use prelude::v1::*;
use io::prelude::*;
use cmp;
use io::{self, SeekFrom, Error, ErrorKind};
use iter::repeat;
use num::Int;
use slice;
/// A `Cursor` is a type which wraps another I/O object to provide a `Seek`
/// implementation.
///
/// Cursors are currently typically used with memory buffer objects in order to
/// allow `Seek` plus `Read` and `Write` implementations. For example, common
/// cursor types include:
///
/// * `Cursor<Vec<u8>>`
/// * `Cursor<&[u8]>`
///
/// Implementations of the I/O traits for `Cursor<T>` are not currently generic
/// over `T` itself. Instead, specific implementations are provided for various
/// in-memory buffer types like `Vec<u8>` and `&[u8]`.
pub struct Cursor<T> {
inner: T,
pos: u64,
}
impl<T> Cursor<T> {
/// Create a new cursor wrapping the provided underlying I/O object.
pub fn new(inner: T) -> Cursor<T> {
Cursor { pos: 0, inner: inner }
}
/// Consume this cursor, returning the underlying value.
pub fn into_inner(self) -> T { self.inner }
/// Get a reference to the underlying value in this cursor.
pub fn get_ref(&self) -> &T { &self.inner }
/// Get a mutable reference to the underlying value in this cursor.
///
/// Care should be taken to avoid modifying the internal I/O state of the
/// underlying value as it may corrupt this cursor's position.
pub fn get_mut(&mut self) -> &mut T { &mut self.inner }
/// Returns the current value of this cursor
pub fn position(&self) -> u64 { self.pos }
/// Sets the value of this cursor
pub fn set_position(&mut self, pos: u64) { self.pos = pos; }
}
macro_rules! seek {
() => {
fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
let pos = match style {
SeekFrom::Start(n) => { self.pos = n; return Ok(n) }
SeekFrom::End(n) => self.inner.len() as i64 + n,
SeekFrom::Current(n) => self.pos as i64 + n,
};
if pos < 0 {
Err(Error::new(ErrorKind::InvalidInput,
"invalid seek to a negative position",
None))
} else {
self.pos = pos as u64;
Ok(self.pos)
}
}
}
}
impl<'a> io::Seek for Cursor<&'a [u8]> { seek!(); }
impl<'a> io::Seek for Cursor<&'a mut [u8]> { seek!(); }
impl io::Seek for Cursor<Vec<u8>> { seek!(); }
macro_rules! read {
() => {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = try!(Read::read(&mut try!(self.fill_buf()), buf));
self.pos += n as u64;
Ok(n)
}
}
}
impl<'a> Read for Cursor<&'a [u8]> { read!(); }
impl<'a> Read for Cursor<&'a mut [u8]> { read!(); }
impl Read for Cursor<Vec<u8>> { read!(); }
macro_rules! buffer {
() => {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
let amt = cmp::min(self.pos, self.inner.len() as u64);
Ok(&self.inner[(amt as usize)..])
}
fn consume(&mut self, amt: usize) { self.pos += amt as u64; }
}
}
impl<'a> BufRead for Cursor<&'a [u8]> { buffer!(); }
impl<'a> BufRead for Cursor<&'a mut [u8]> { buffer!(); }
impl<'a> BufRead for Cursor<Vec<u8>> { buffer!(); }
impl<'a> Write for Cursor<&'a mut [u8]> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let pos = cmp::min(self.pos, self.inner.len() as u64);
let amt = try!((&mut self.inner[(pos as usize)..]).write(data));
self.pos += amt as u64;
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl Write for Cursor<Vec<u8>> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Make sure the internal buffer is as least as big as where we
// currently are
let pos = self.position();
let amt = pos.saturating_sub(self.inner.len() as u64);
self.inner.extend(repeat(0).take(amt as usize));
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let space = self.inner.len() - pos as usize;
let (left, right) = buf.split_at(cmp::min(space, buf.len()));
slice::bytes::copy_memory(&mut self.inner[(pos as usize)..], left);
self.inner.push_all(right);
// Bump us forward
self.set_position(pos + buf.len() as u64);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
#[cfg(test)]
mod tests {
use core::prelude::*;
use io::prelude::*;
use io::{Cursor, SeekFrom};
use vec::Vec;
#[test]
fn test_vec_writer() {
let mut writer = Vec::new();
assert_eq!(writer.write(&[0]), Ok(1));
assert_eq!(writer.write(&[1, 2, 3]), Ok(3));
assert_eq!(writer.write(&[4, 5, 6, 7]), Ok(4));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer, b);
}
#[test]
fn test_mem_writer() {
let mut writer = Cursor::new(Vec::new());
assert_eq!(writer.write(&[0]), Ok(1));
assert_eq!(writer.write(&[1, 2, 3]), Ok(3));
assert_eq!(writer.write(&[4, 5, 6, 7]), Ok(4));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(&writer.get_ref()[], b);
}
#[test]
fn test_buf_writer() {
let mut buf = [0 as u8; 9];
{
let mut writer = Cursor::new(&mut buf[]);
assert_eq!(writer.position(), 0);
assert_eq!(writer.write(&[0]), Ok(1));
assert_eq!(writer.position(), 1);
assert_eq!(writer.write(&[1, 2, 3]), Ok(3));
assert_eq!(writer.write(&[4, 5, 6, 7]), Ok(4));
assert_eq!(writer.position(), 8);
assert_eq!(writer.write(&[]), Ok(0));
assert_eq!(writer.position(), 8);
assert_eq!(writer.write(&[8, 9]), Ok(1));
assert_eq!(writer.write(&[10]), Ok(0));
}
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8];
assert_eq!(buf, b);
}
#[test]
fn test_buf_writer_seek() {
let mut buf = [0 as u8; 8];
{
let mut writer = Cursor::new(&mut buf[]);
assert_eq!(writer.position(), 0);
assert_eq!(writer.write(&[1]), Ok(1));
assert_eq!(writer.position(), 1);
assert_eq!(writer.seek(SeekFrom::Start(2)), Ok(2));
assert_eq!(writer.position(), 2);
assert_eq!(writer.write(&[2]), Ok(1));
assert_eq!(writer.position(), 3);
assert_eq!(writer.seek(SeekFrom::Current(-2)), Ok(1));
assert_eq!(writer.position(), 1);
assert_eq!(writer.write(&[3]), Ok(1));
assert_eq!(writer.position(), 2);
assert_eq!(writer.seek(SeekFrom::End(-1)), Ok(7));
assert_eq!(writer.position(), 7);
assert_eq!(writer.write(&[4]), Ok(1));
assert_eq!(writer.position(), 8);
}
let b: &[_] = &[1, 3, 2, 0, 0, 0, 0, 4];
assert_eq!(buf, b);
}
#[test]
fn test_buf_writer_error() {
let mut buf = [0 as u8; 2];
let mut writer = Cursor::new(&mut buf[]);
assert_eq!(writer.write(&[0]), Ok(1));
assert_eq!(writer.write(&[0, 0]), Ok(1));
assert_eq!(writer.write(&[0, 0]), Ok(0));
}
#[test]
fn test_mem_reader() {
let mut reader = Cursor::new(vec!(0u8, 1, 2, 3, 4, 5, 6, 7));
let mut buf = [];
assert_eq!(reader.read(&mut buf), Ok(0));
assert_eq!(reader.position(), 0);
let mut buf = [0];
assert_eq!(reader.read(&mut buf), Ok(1));
assert_eq!(reader.position(), 1);
let b: &[_] = &[0];
assert_eq!(buf, b);
let mut buf = [0; 4];
assert_eq!(reader.read(&mut buf), Ok(4));
assert_eq!(reader.position(), 5);
let b: &[_] = &[1, 2, 3, 4];
assert_eq!(buf, b);
assert_eq!(reader.read(&mut buf), Ok(3));
let b: &[_] = &[5, 6, 7];
assert_eq!(&buf[..3], b);
assert_eq!(reader.read(&mut buf), Ok(0));
}
#[test]
fn read_to_end() {
let mut reader = Cursor::new(vec!(0u8, 1, 2, 3, 4, 5, 6, 7));
let mut v = Vec::new();
reader.read_to_end(&mut v).ok().unwrap();
assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]);
}
#[test]
fn test_slice_reader() {
let in_buf = vec![0u8, 1, 2, 3, 4, 5, 6, 7];
let mut reader = &mut in_buf.as_slice();
let mut buf = [];
assert_eq!(reader.read(&mut buf), Ok(0));
let mut buf = [0];
assert_eq!(reader.read(&mut buf), Ok(1));
assert_eq!(reader.len(), 7);
let b: &[_] = &[0];
assert_eq!(buf.as_slice(), b);
let mut buf = [0; 4];
assert_eq!(reader.read(&mut buf), Ok(4));
assert_eq!(reader.len(), 3);
let b: &[_] = &[1, 2, 3, 4];
assert_eq!(buf.as_slice(), b);
assert_eq!(reader.read(&mut buf), Ok(3));
let b: &[_] = &[5, 6, 7];
assert_eq!(&buf[..3], b);
assert_eq!(reader.read(&mut buf), Ok(0));
}
#[test]
fn test_buf_reader() {
let in_buf = vec![0u8, 1, 2, 3, 4, 5, 6, 7];
let mut reader = Cursor::new(in_buf.as_slice());
let mut buf = [];
assert_eq!(reader.read(&mut buf), Ok(0));
assert_eq!(reader.position(), 0);
let mut buf = [0];
assert_eq!(reader.read(&mut buf), Ok(1));
assert_eq!(reader.position(), 1);
let b: &[_] = &[0];
assert_eq!(buf, b);
let mut buf = [0; 4];
assert_eq!(reader.read(&mut buf), Ok(4));
assert_eq!(reader.position(), 5);
let b: &[_] = &[1, 2, 3, 4];
assert_eq!(buf, b);
assert_eq!(reader.read(&mut buf), Ok(3));
let b: &[_] = &[5, 6, 7];
assert_eq!(&buf[..3], b);
assert_eq!(reader.read(&mut buf), Ok(0));
}
#[test]
fn test_read_char() {
let b = b"Vi\xE1\xBB\x87t";
let mut c = Cursor::new(b).chars();
assert_eq!(c.next(), Some(Ok('V')));
assert_eq!(c.next(), Some(Ok('i')));
assert_eq!(c.next(), Some(Ok('ệ')));
assert_eq!(c.next(), Some(Ok('t')));
assert_eq!(c.next(), None);
}
#[test]
fn test_read_bad_char() {
let b = b"\x80";
let mut c = Cursor::new(b).chars();
assert!(c.next().unwrap().is_err());
}
#[test]
fn seek_past_end() {
let buf = [0xff];
let mut r = Cursor::new(&buf[]);
assert_eq!(r.seek(SeekFrom::Start(10)), Ok(10));
assert_eq!(r.read(&mut [0]), Ok(0));
let mut r = Cursor::new(vec!(10u8));
assert_eq!(r.seek(SeekFrom::Start(10)), Ok(10));
assert_eq!(r.read(&mut [0]), Ok(0));
let mut buf = [0];
let mut r = Cursor::new(&mut buf[]);
assert_eq!(r.seek(SeekFrom::Start(10)), Ok(10));
assert_eq!(r.write(&[3]), Ok(0));
}
#[test]
fn seek_before_0() {
let buf = [0xff_u8];
let mut r = Cursor::new(&buf[]);
assert!(r.seek(SeekFrom::End(-2)).is_err());
let mut r = Cursor::new(vec!(10u8));
assert!(r.seek(SeekFrom::End(-2)).is_err());
let mut buf = [0];
let mut r = Cursor::new(&mut buf[]);
assert!(r.seek(SeekFrom::End(-2)).is_err());
}
#[test]
fn test_seekable_mem_writer() {
let mut writer = Cursor::new(Vec::<u8>::new());
assert_eq!(writer.position(), 0);
assert_eq!(writer.write(&[0]), Ok(1));
assert_eq!(writer.position(), 1);
assert_eq!(writer.write(&[1, 2, 3]), Ok(3));
assert_eq!(writer.write(&[4, 5, 6, 7]), Ok(4));
assert_eq!(writer.position(), 8);
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(&writer.get_ref()[], b);
assert_eq!(writer.seek(SeekFrom::Start(0)), Ok(0));
assert_eq!(writer.position(), 0);
assert_eq!(writer.write(&[3, 4]), Ok(2));
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(&writer.get_ref()[], b);
assert_eq!(writer.seek(SeekFrom::Current(1)), Ok(3));
assert_eq!(writer.write(&[0, 1]), Ok(2));
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(&writer.get_ref()[], b);
assert_eq!(writer.seek(SeekFrom::End(-1)), Ok(7));
assert_eq!(writer.write(&[1, 2]), Ok(2));
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(&writer.get_ref()[], b);
assert_eq!(writer.seek(SeekFrom::End(1)), Ok(10));
assert_eq!(writer.write(&[1]), Ok(1));
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(&writer.get_ref()[], b);
}
#[test]
fn vec_seek_past_end() {
let mut r = Cursor::new(Vec::new());
assert_eq!(r.seek(SeekFrom::Start(10)), Ok(10));
assert_eq!(r.write(&[3]), Ok(1));
}
#[test]
fn vec_seek_before_0() {
let mut r = Cursor::new(Vec::new());
assert!(r.seek(SeekFrom::End(-2)).is_err());
}
}
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use boxed::Box;
use clone::Clone;
use error::Error as StdError;
use fmt;
use option::Option::{self, Some, None};
use result;
use string::String;
use sys;
/// A type for results generated by I/O related functions where the `Err` type
/// is hard-wired to `io::Error`.
///
/// This typedef is generally used to avoid writing out `io::Error` directly and
/// is otherwise a direct mapping to `std::result::Result`.
pub type Result<T> = result::Result<T, Error>;
/// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
/// associated traits.
///
/// Errors mostly originate from the underlying OS, but custom instances of
/// `Error` can be created with crafted error messages and a particular value of
/// `ErrorKind`.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Error {
repr: Repr,
}
#[derive(PartialEq, Eq, Clone, Debug)]
enum Repr {
Os(i32),
Custom(Box<Custom>),
}
#[derive(PartialEq, Eq, Clone, Debug)]
struct Custom {
kind: ErrorKind,
desc: &'static str,
detail: Option<String>
}
/// A list specifying general categories of I/O error.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
pub enum ErrorKind {
/// The file was not found.
FileNotFound,
/// The file permissions disallowed access to this file.
PermissionDenied,
/// The connection was refused by the remote server.
ConnectionRefused,
/// The connection was reset by the remote server.
ConnectionReset,
/// The connection was aborted (terminated) by the remote server.
ConnectionAborted,
/// The network operation failed because it was not connected yet.
NotConnected,
/// The operation failed because a pipe was closed.
BrokenPipe,
/// A file already existed with that name.
PathAlreadyExists,
/// No file exists at that location.
PathDoesntExist,
/// The path did not specify the type of file that this operation required.
/// For example, attempting to copy a directory with the `fs::copy()`
/// operation will fail with this error.
MismatchedFileTypeForOperation,
/// The operation temporarily failed (for example, because a signal was
/// received), and retrying may succeed.
ResourceUnavailable,
/// A parameter was incorrect in a way that caused an I/O error not part of
/// this list.
InvalidInput,
/// The I/O operation's timeout expired, causing it to be canceled.
TimedOut,
/// An error returned when an operation could not be completed because a
/// call to `write` returned `Ok(0)`.
///
/// This typically means that an operation could only succeed if it wrote a
/// particular number of bytes but only a smaller number of bytes could be
/// written.
WriteZero,
/// This operation was interrupted
Interrupted,
/// Any I/O error not part of this list.
Other,
}
impl Error {
/// Creates a new custom error from a specified kind/description/detail.
pub fn new(kind: ErrorKind,
description: &'static str,
detail: Option<String>) -> Error {
Error {
repr: Repr::Custom(Box::new(Custom {
kind: kind,
desc: description,
detail: detail,
}))
}
}
/// Returns an error representing the last OS error which occurred.
///
/// 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.
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.
pub fn from_os_error(code: i32) -> Error {
Error { repr: Repr::Os(code) }
}
/// Return the corresponding `ErrorKind` for this error.
pub fn kind(&self) -> ErrorKind {
match self.repr {
Repr::Os(code) => sys::decode_error_kind(code),
Repr::Custom(ref c) => c.kind,
}
}
/// Returns a short description for this error message
pub fn description(&self) -> &str {
match self.repr {
Repr::Os(..) => "os error",
Repr::Custom(ref c) => c.desc,
}
}
/// Returns a detailed error message for this error (if one is available)
pub fn detail(&self) -> Option<String> {
match self.repr {
Repr::Os(code) => Some(sys::os::error_string(code)),
Repr::Custom(ref s) => s.detail.clone(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.repr {
Repr::Os(code) => {
let detail = sys::os::error_string(code);
write!(fmt, "{} (os error {})", detail, code)
}
Repr::Custom(ref c) => {
match **c {
Custom {
kind: ErrorKind::Other,
desc: "unknown error",
detail: Some(ref detail)
} => {
write!(fmt, "{}", detail)
}
Custom { detail: None, desc, .. } =>
write!(fmt, "{}", desc),
Custom { detail: Some(ref detail), desc, .. } =>
write!(fmt, "{} ({})", desc, detail)
}
}
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
match self.repr {
Repr::Os(..) => "os error",
Repr::Custom(ref c) => c.desc,
}
}
}
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use boxed::Box;
use cmp;
use io::{self, SeekFrom, Read, Write, Seek, BufRead};
use mem;
use slice;
use vec::Vec;
// =============================================================================
// Forwarding implementations
impl<'a, R: Read + ?Sized> Read for &'a mut R {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) }
}
impl<'a, W: Write + ?Sized> Write for &'a mut W {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
}
impl<'a, S: Seek + ?Sized> Seek for &'a mut S {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
}
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) }
}
impl<R: Read + ?Sized> Read for Box<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) }
}
impl<W: Write + ?Sized> Write for Box<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
}
impl<S: Seek + ?Sized> Seek for Box<S> {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
}
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) }
}
// =============================================================================
// In-memory buffer implementations
impl<'a> Read for &'a [u8] {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let amt = cmp::min(buf.len(), self.len());
let (a, b) = self.split_at(amt);
slice::bytes::copy_memory(buf, a);
*self = b;
Ok(amt)
}
}
impl<'a> BufRead for &'a [u8] {
fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) }
fn consume(&mut self, amt: usize) { *self = &self[amt..]; }
}
impl<'a> Write for &'a mut [u8] {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = cmp::min(data.len(), self.len());
let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
slice::bytes::copy_memory(a, &data[..amt]);
*self = b;
Ok(amt)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl Write for Vec<u8> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.push_all(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
此差异已折叠。
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The I/O Prelude
//!
//! The purpose of this module is to alleviate imports of many common I/O traits
//! by adding a glob import to the top of I/O heavy modules:
//!
//! ```
//! use std::io::prelude::*;
//! ```
//!
//! This module contains reexports of many core I/O traits such as `Read`,
//! `Write`, `ReadExt`, and `WriteExt`. Structures and functions are not
//! contained in this module.
pub use super::{Read, ReadExt, Write, WriteExt, BufRead, BufReadExt};
// FIXME: pub use as `Seek` when the name isn't in the actual prelude any more
pub use super::Seek as NewSeek;
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(missing_copy_implementations)]
use prelude::v1::*;
use io::{self, Read, Write, ErrorKind};
/// Copies the entire contents of a reader into a writer.
///
/// This function will continuously read data from `r` and then write it into
/// `w` in a streaming fashion until `r` returns EOF.
///
/// On success the total number of bytes that were copied from `r` to `w` is
/// returned.
///
/// # Errors
///
/// This function will return an error immediately if any call to `read` or
/// `write` returns an error. All instances of `ErrorKind::Interrupted` are
/// handled by this function and the underlying operation is retried.
pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> {
let mut buf = [0; super::DEFAULT_BUF_SIZE];
let mut written = 0;
loop {
let len = match r.read(&mut buf) {
Ok(0) => return Ok(written),
Ok(len) => len,
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
try!(w.write_all(&buf[..len]));
written += len as u64;
}
}
/// A reader which is always at EOF.
pub struct Empty { _priv: () }
/// Creates an instance of an empty reader.
///
/// All reads from the returned reader will return `Ok(0)`.
pub fn empty() -> Empty { Empty { _priv: () } }
impl Read for Empty {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
}
/// A reader which infinitely yields one byte.
pub struct Repeat { byte: u8 }
/// Creates an instance of a reader that infinitely repeats one byte.
///
/// All reads from this reader will succeed by filling the specified buffer with
/// the given byte.
pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
impl Read for Repeat {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
for slot in buf.iter_mut() {
*slot = self.byte;
}
Ok(buf.len())
}
}
/// A writer which will move data into the void.
pub struct Sink { _priv: () }
/// Creates an instance of a writer which will successfully consume all data.
///
/// All calls to `write` on the returned instance will return `Ok(buf.len())`
/// and the contents of the buffer will not be inspected.
pub fn sink() -> Sink { Sink { _priv: () } }
impl Write for Sink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
#[cfg(test)]
mod test {
use prelude::v1::*;
use io::prelude::*;
use io::{sink, empty, repeat};
#[test]
fn sink_sinks() {
let mut s = sink();
assert_eq!(s.write(&[]), Ok(0));
assert_eq!(s.write(&[0]), Ok(1));
assert_eq!(s.write(&[0; 1024]), Ok(1024));
assert_eq!(s.by_ref().write(&[0; 1024]), Ok(1024));
}
#[test]
fn empty_reads() {
let mut e = empty();
assert_eq!(e.read(&mut []), Ok(0));
assert_eq!(e.read(&mut [0]), Ok(0));
assert_eq!(e.read(&mut [0; 1024]), Ok(0));
assert_eq!(e.by_ref().read(&mut [0; 1024]), Ok(0));
}
#[test]
fn repeat_repeats() {
let mut r = repeat(4);
let mut b = [0; 1024];
assert_eq!(r.read(&mut b), Ok(1024));
assert!(b.iter().all(|b| *b == 4));
}
#[test]
fn take_some_bytes() {
assert_eq!(repeat(4).take(100).bytes().count(), 100);
assert_eq!(repeat(4).take(100).bytes().next(), Some(Ok(4)));
assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
}
#[test]
fn tee() {
let mut buf = [0; 10];
{
let mut ptr: &mut [u8] = &mut buf;
assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]), Ok(5));
}
assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
}
#[test]
fn broadcast() {
let mut buf1 = [0; 10];
let mut buf2 = [0; 10];
{
let mut ptr1: &mut [u8] = &mut buf1;
let mut ptr2: &mut [u8] = &mut buf2;
assert_eq!((&mut ptr1).broadcast(&mut ptr2)
.write(&[1, 2, 3]), Ok(3));
}
assert_eq!(buf1, buf2);
assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
}
}
......@@ -128,9 +128,8 @@
#![deny(missing_docs)]
#[cfg(test)]
#[macro_use]
extern crate log;
#[cfg(test)] extern crate test;
#[cfg(test)] #[macro_use] extern crate log;
#[macro_use]
#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
......@@ -248,6 +247,7 @@
pub mod ffi;
pub mod fmt;
pub mod old_io;
pub mod io;
pub mod os;
pub mod env;
pub mod path;
......
......@@ -18,10 +18,11 @@
use prelude::v1::*;
use ffi;
use old_io::{self, IoResult, IoError};
use io::ErrorKind;
use libc;
use num::{Int, SignedInt};
use num;
use old_io::{self, IoResult, IoError};
use str;
use sys_common::mkerr_libc;
......@@ -133,6 +134,35 @@ pub fn decode_error_detailed(errno: i32) -> IoError {
err
}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => ErrorKind::NotConnected,
libc::ECONNABORTED => ErrorKind::ConnectionAborted,
libc::EADDRNOTAVAIL => ErrorKind::ConnectionRefused,
libc::EADDRINUSE => ErrorKind::ConnectionRefused,
libc::ENOENT => ErrorKind::FileNotFound,
libc::EISDIR => ErrorKind::InvalidInput,
libc::EINTR => ErrorKind::Interrupted,
libc::EINVAL => ErrorKind::InvalidInput,
libc::ENOTTY => ErrorKind::MismatchedFileTypeForOperation,
libc::ETIMEDOUT => ErrorKind::TimedOut,
libc::ECANCELED => ErrorKind::TimedOut,
libc::consts::os::posix88::EEXIST => ErrorKind::PathAlreadyExists,
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
ErrorKind::ResourceUnavailable,
_ => ErrorKind::Other,
}
}
#[inline]
pub fn retry<T, F> (mut f: F) -> T where
T: SignedInt,
......
......@@ -15,6 +15,7 @@
use prelude::v1::*;
use ffi::OsStr;
use io::ErrorKind;
use libc;
use mem;
use old_io::{self, IoResult, IoError};
......@@ -143,6 +144,34 @@ pub fn decode_error_detailed(errno: i32) -> IoError {
err
}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ERROR_ACCESS_DENIED => ErrorKind::PermissionDenied,
libc::ERROR_ALREADY_EXISTS => ErrorKind::PathAlreadyExists,
libc::ERROR_BROKEN_PIPE => ErrorKind::BrokenPipe,
libc::ERROR_FILE_NOT_FOUND => ErrorKind::FileNotFound,
libc::ERROR_INVALID_FUNCTION => ErrorKind::InvalidInput,
libc::ERROR_INVALID_HANDLE => ErrorKind::MismatchedFileTypeForOperation,
libc::ERROR_INVALID_NAME => ErrorKind::InvalidInput,
libc::ERROR_NOTHING_TO_TERMINATE => ErrorKind::InvalidInput,
libc::ERROR_NO_DATA => ErrorKind::BrokenPipe,
libc::ERROR_OPERATION_ABORTED => ErrorKind::TimedOut,
libc::WSAEACCES => ErrorKind::PermissionDenied,
libc::WSAEADDRINUSE => ErrorKind::ConnectionRefused,
libc::WSAEADDRNOTAVAIL => ErrorKind::ConnectionRefused,
libc::WSAECONNABORTED => ErrorKind::ConnectionAborted,
libc::WSAECONNREFUSED => ErrorKind::ConnectionRefused,
libc::WSAECONNRESET => ErrorKind::ConnectionReset,
libc::WSAEINVAL => ErrorKind::InvalidInput,
libc::WSAENOTCONN => ErrorKind::NotConnected,
libc::WSAEWOULDBLOCK => ErrorKind::ResourceUnavailable,
_ => ErrorKind::Other,
}
}
#[inline]
pub fn retry<I, F>(f: F) -> I where F: FnOnce() -> I { f() } // PR rust-lang/rust/#17020
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册