Skip to content

Commit 5cf9905

Browse files
committed
std: Add io module again
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]: rust-lang/rfcs#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.
1 parent 7858cb4 commit 5cf9905

File tree

10 files changed

+2546
-4
lines changed

10 files changed

+2546
-4
lines changed

Diff for: src/libstd/io/buffered.rs

+676
Large diffs are not rendered by default.

Diff for: src/libstd/io/cursor.rs

+408
Large diffs are not rendered by default.

Diff for: src/libstd/io/error.rs

+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use boxed::Box;
12+
use clone::Clone;
13+
use error::Error as StdError;
14+
use fmt;
15+
use option::Option::{self, Some, None};
16+
use result;
17+
use string::String;
18+
use sys;
19+
20+
/// A type for results generated by I/O related functions where the `Err` type
21+
/// is hard-wired to `io::Error`.
22+
///
23+
/// This typedef is generally used to avoid writing out `io::Error` directly and
24+
/// is otherwise a direct mapping to `std::result::Result`.
25+
pub type Result<T> = result::Result<T, Error>;
26+
27+
/// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
28+
/// associated traits.
29+
///
30+
/// Errors mostly originate from the underlying OS, but custom instances of
31+
/// `Error` can be created with crafted error messages and a particular value of
32+
/// `ErrorKind`.
33+
#[derive(PartialEq, Eq, Clone, Debug)]
34+
pub struct Error {
35+
repr: Repr,
36+
}
37+
38+
#[derive(PartialEq, Eq, Clone, Debug)]
39+
enum Repr {
40+
Os(i32),
41+
Custom(Box<Custom>),
42+
}
43+
44+
#[derive(PartialEq, Eq, Clone, Debug)]
45+
struct Custom {
46+
kind: ErrorKind,
47+
desc: &'static str,
48+
detail: Option<String>
49+
}
50+
51+
/// A list specifying general categories of I/O error.
52+
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
53+
pub enum ErrorKind {
54+
/// The file was not found.
55+
FileNotFound,
56+
/// The file permissions disallowed access to this file.
57+
PermissionDenied,
58+
/// The connection was refused by the remote server.
59+
ConnectionRefused,
60+
/// The connection was reset by the remote server.
61+
ConnectionReset,
62+
/// The connection was aborted (terminated) by the remote server.
63+
ConnectionAborted,
64+
/// The network operation failed because it was not connected yet.
65+
NotConnected,
66+
/// The operation failed because a pipe was closed.
67+
BrokenPipe,
68+
/// A file already existed with that name.
69+
PathAlreadyExists,
70+
/// No file exists at that location.
71+
PathDoesntExist,
72+
/// The path did not specify the type of file that this operation required.
73+
/// For example, attempting to copy a directory with the `fs::copy()`
74+
/// operation will fail with this error.
75+
MismatchedFileTypeForOperation,
76+
/// The operation temporarily failed (for example, because a signal was
77+
/// received), and retrying may succeed.
78+
ResourceUnavailable,
79+
/// A parameter was incorrect in a way that caused an I/O error not part of
80+
/// this list.
81+
InvalidInput,
82+
/// The I/O operation's timeout expired, causing it to be canceled.
83+
TimedOut,
84+
/// An error returned when an operation could not be completed because a
85+
/// call to `write` returned `Ok(0)`.
86+
///
87+
/// This typically means that an operation could only succeed if it wrote a
88+
/// particular number of bytes but only a smaller number of bytes could be
89+
/// written.
90+
WriteZero,
91+
/// This operation was interrupted
92+
Interrupted,
93+
/// Any I/O error not part of this list.
94+
Other,
95+
}
96+
97+
impl Error {
98+
/// Creates a new custom error from a specified kind/description/detail.
99+
pub fn new(kind: ErrorKind,
100+
description: &'static str,
101+
detail: Option<String>) -> Error {
102+
Error {
103+
repr: Repr::Custom(Box::new(Custom {
104+
kind: kind,
105+
desc: description,
106+
detail: detail,
107+
}))
108+
}
109+
}
110+
111+
/// Returns an error representing the last OS error which occurred.
112+
///
113+
/// This function reads the value of `errno` for the target platform (e.g.
114+
/// `GetLastError` on Windows) and will return a corresponding instance of
115+
/// `Error` for the error code.
116+
pub fn last_os_error() -> Error {
117+
Error::from_os_error(sys::os::errno() as i32)
118+
}
119+
120+
/// Creates a new instance of an `Error` from a particular OS error code.
121+
pub fn from_os_error(code: i32) -> Error {
122+
Error { repr: Repr::Os(code) }
123+
}
124+
125+
/// Return the corresponding `ErrorKind` for this error.
126+
pub fn kind(&self) -> ErrorKind {
127+
match self.repr {
128+
Repr::Os(code) => sys::decode_error_kind(code),
129+
Repr::Custom(ref c) => c.kind,
130+
}
131+
}
132+
133+
/// Returns a short description for this error message
134+
pub fn description(&self) -> &str {
135+
match self.repr {
136+
Repr::Os(..) => "os error",
137+
Repr::Custom(ref c) => c.desc,
138+
}
139+
}
140+
141+
/// Returns a detailed error message for this error (if one is available)
142+
pub fn detail(&self) -> Option<String> {
143+
match self.repr {
144+
Repr::Os(code) => Some(sys::os::error_string(code)),
145+
Repr::Custom(ref s) => s.detail.clone(),
146+
}
147+
}
148+
}
149+
150+
impl fmt::Display for Error {
151+
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
152+
match self.repr {
153+
Repr::Os(code) => {
154+
let detail = sys::os::error_string(code);
155+
write!(fmt, "{} (os error {})", detail, code)
156+
}
157+
Repr::Custom(ref c) => {
158+
match **c {
159+
Custom {
160+
kind: ErrorKind::Other,
161+
desc: "unknown error",
162+
detail: Some(ref detail)
163+
} => {
164+
write!(fmt, "{}", detail)
165+
}
166+
Custom { detail: None, desc, .. } =>
167+
write!(fmt, "{}", desc),
168+
Custom { detail: Some(ref detail), desc, .. } =>
169+
write!(fmt, "{} ({})", desc, detail)
170+
}
171+
}
172+
}
173+
}
174+
}
175+
176+
impl StdError for Error {
177+
fn description(&self) -> &str {
178+
match self.repr {
179+
Repr::Os(..) => "os error",
180+
Repr::Custom(ref c) => c.desc,
181+
}
182+
}
183+
}

Diff for: src/libstd/io/impls.rs

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use core::prelude::*;
12+
13+
use boxed::Box;
14+
use cmp;
15+
use io::{self, SeekFrom, Read, Write, Seek, BufRead};
16+
use mem;
17+
use slice;
18+
use vec::Vec;
19+
20+
// =============================================================================
21+
// Forwarding implementations
22+
23+
impl<'a, R: Read + ?Sized> Read for &'a mut R {
24+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) }
25+
}
26+
impl<'a, W: Write + ?Sized> Write for &'a mut W {
27+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
28+
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
29+
}
30+
impl<'a, S: Seek + ?Sized> Seek for &'a mut S {
31+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
32+
}
33+
impl<'a, B: BufRead + ?Sized> BufRead for &'a mut B {
34+
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
35+
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
36+
}
37+
38+
impl<R: Read + ?Sized> Read for Box<R> {
39+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) }
40+
}
41+
impl<W: Write + ?Sized> Write for Box<W> {
42+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
43+
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
44+
}
45+
impl<S: Seek + ?Sized> Seek for Box<S> {
46+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
47+
}
48+
impl<B: BufRead + ?Sized> BufRead for Box<B> {
49+
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
50+
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
51+
}
52+
53+
// =============================================================================
54+
// In-memory buffer implementations
55+
56+
impl<'a> Read for &'a [u8] {
57+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
58+
let amt = cmp::min(buf.len(), self.len());
59+
let (a, b) = self.split_at(amt);
60+
slice::bytes::copy_memory(buf, a);
61+
*self = b;
62+
Ok(amt)
63+
}
64+
}
65+
66+
impl<'a> BufRead for &'a [u8] {
67+
fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) }
68+
fn consume(&mut self, amt: usize) { *self = &self[amt..]; }
69+
}
70+
71+
impl<'a> Write for &'a mut [u8] {
72+
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
73+
let amt = cmp::min(data.len(), self.len());
74+
let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
75+
slice::bytes::copy_memory(a, &data[..amt]);
76+
*self = b;
77+
Ok(amt)
78+
}
79+
fn flush(&mut self) -> io::Result<()> { Ok(()) }
80+
}
81+
82+
impl Write for Vec<u8> {
83+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
84+
self.push_all(buf);
85+
Ok(buf.len())
86+
}
87+
fn flush(&mut self) -> io::Result<()> { Ok(()) }
88+
}

0 commit comments

Comments
 (0)