1 // Copyright 2013-2014 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.
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.
11 // ignore-lexer-test FIXME #15883
13 // FIXME: cover these topics:
14 // path, reader, writer, stream, raii (close not needed),
15 // stdio, print!, println!, file access, process spawning,
19 //! I/O, including files, networking, timers, and processes
21 //! > **Warning**: This module is currently called `old_io` for a reason! The
22 //! > module is currently being redesigned in a number of RFCs. For more details
23 //! > follow the RFC repository in connection with [RFC 517][base] or follow
24 //! > some of these sub-RFCs
26 //! > * [String handling][osstr]
27 //! > * [Core I/O support][core]
28 //! > * [Deadlines][deadlines]
29 //! > * [std::env][env]
30 //! > * [std::process][process]
32 //! [base]: https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md
33 //! [osstr]: https://github.com/rust-lang/rfcs/pull/575
34 //! [core]: https://github.com/rust-lang/rfcs/pull/576
35 //! [deadlines]: https://github.com/rust-lang/rfcs/pull/577
36 //! [env]: https://github.com/rust-lang/rfcs/pull/578
37 //! [process]: https://github.com/rust-lang/rfcs/pull/579
39 //! `std::io` provides Rust's basic I/O types,
40 //! for reading and writing to files, TCP, UDP,
41 //! and other types of sockets and pipes,
42 //! manipulating the file system, spawning processes.
46 //! Some examples of obvious things you might want to do
48 //! * Read lines from stdin
51 //! # #![feature(old_io, old_path)]
52 //! use std::old_io as io;
53 //! use std::old_io::*;
55 //! let mut stdin = io::stdin();
56 //! for line in stdin.lock().lines() {
57 //! print!("{}", line.unwrap());
61 //! * Read a complete file
64 //! # #![feature(old_io, old_path)]
65 //! use std::old_io::*;
66 //! use std::old_path::Path;
68 //! let contents = File::open(&Path::new("message.txt")).read_to_end();
71 //! * Write a line to a file
74 //! # #![feature(old_io, old_path)]
75 //! # #![allow(unused_must_use)]
76 //! use std::old_io::*;
77 //! use std::old_path::Path;
79 //! let mut file = File::create(&Path::new("message.txt"));
80 //! file.write_all(b"hello, file!\n");
82 //! # ::std::old_io::fs::unlink(&Path::new("message.txt"));
85 //! * Iterate over the lines of a file
88 //! # #![feature(old_io, old_path)]
89 //! use std::old_io::*;
90 //! use std::old_path::Path;
92 //! let path = Path::new("message.txt");
93 //! let mut file = BufferedReader::new(File::open(&path));
94 //! for line in file.lines() {
95 //! print!("{}", line.unwrap());
99 //! * Pull the lines of a file into a vector of strings
102 //! # #![feature(old_io, old_path)]
103 //! use std::old_io::*;
104 //! use std::old_path::Path;
106 //! let path = Path::new("message.txt");
107 //! let mut file = BufferedReader::new(File::open(&path));
108 //! let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
111 //! * Make a simple TCP client connection and request
114 //! # #![feature(old_io)]
115 //! # #![allow(unused_must_use)]
116 //! use std::old_io::*;
118 //! # // connection doesn't fail if a server is running on 8080
119 //! # // locally, we still want to be type checking this code, so lets
120 //! # // just stop it running (#11576)
122 //! let mut socket = TcpStream::connect("127.0.0.1:8080").unwrap();
123 //! socket.write_all(b"GET / HTTP/1.0\n\n");
124 //! let response = socket.read_to_end();
128 //! * Make a simple TCP server
131 //! # #![feature(old_io)]
134 //! # #![allow(dead_code)]
135 //! use std::old_io::*;
138 //! let listener = TcpListener::bind("127.0.0.1:80");
140 //! // bind the listener to the specified address
141 //! let mut acceptor = listener.listen();
143 //! fn handle_client(mut stream: TcpStream) {
145 //! # &mut stream; // silence unused mutability/variable warning
147 //! // accept connections and process them, spawning a new tasks for each one
148 //! for stream in acceptor.incoming() {
150 //! Err(e) => { /* connection failed */ }
152 //! thread::spawn(move|| {
153 //! // connection succeeded
154 //! handle_client(stream)
160 //! // close the socket server
168 //! I/O is an area where nearly every operation can result in unexpected
169 //! errors. Errors should be painfully visible when they happen, and handling them
170 //! should be easy to work with. It should be convenient to handle specific I/O
171 //! errors, and it should also be convenient to not deal with I/O errors.
173 //! Rust's I/O employs a combination of techniques to reduce boilerplate
174 //! while still providing feedback about errors. The basic strategy:
176 //! * All I/O operations return `IoResult<T>` which is equivalent to
177 //! `Result<T, IoError>`. The `Result` type is defined in the `std::result`
179 //! * If the `Result` type goes unused, then the compiler will by default emit a
180 //! warning about the unused result. This is because `Result` has the
181 //! `#[must_use]` attribute.
182 //! * Common traits are implemented for `IoResult`, e.g.
183 //! `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
184 //! to be 'unwrapped' before use.
186 //! These features combine in the API to allow for expressions like
187 //! `File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n")`
188 //! without having to worry about whether "diary.txt" exists or whether
189 //! the write succeeds. As written, if either `new` or `write_line`
190 //! encounters an error then the result of the entire expression will
193 //! If you wanted to handle the error though you might write:
196 //! # #![feature(old_io, old_path)]
197 //! # #![allow(unused_must_use)]
198 //! use std::old_io::*;
199 //! use std::old_path::Path;
201 //! match File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n") {
202 //! Ok(()) => (), // succeeded
203 //! Err(e) => println!("failed to write to my diary: {}", e),
206 //! # ::std::old_io::fs::unlink(&Path::new("diary.txt"));
209 //! So what actually happens if `create` encounters an error?
210 //! It's important to know that what `new` returns is not a `File`
211 //! but an `IoResult<File>`. If the file does not open, then `new` will simply
212 //! return `Err(..)`. Because there is an implementation of `Writer` (the trait
213 //! required ultimately required for types to implement `write_line`) there is no
214 //! need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
215 //! on it. If `new` returned an `Err(..)` then the followup call to `write_line`
216 //! will also return an error.
220 //! Explicit pattern matching on `IoResult`s can get quite verbose, especially
221 //! when performing many I/O operations. Some examples (like those above) are
222 //! alleviated with extra methods implemented on `IoResult`, but others have more
223 //! complex interdependencies among each I/O operation.
225 //! The `try!` macro from `std::macros` is provided as a method of early-return
226 //! inside `Result`-returning functions. It expands to an early-return on `Err`
227 //! and otherwise unwraps the contained `Ok` value.
229 //! If you wanted to read several `u32`s from a file and return their product:
232 //! # #![feature(old_io, old_path)]
233 //! use std::old_io::*;
234 //! use std::old_path::Path;
236 //! fn file_product(p: &Path) -> IoResult<u32> {
237 //! let mut f = File::open(p);
238 //! let x1 = try!(f.read_le_u32());
239 //! let x2 = try!(f.read_le_u32());
244 //! match file_product(&Path::new("numbers.bin")) {
245 //! Ok(x) => println!("{}", x),
246 //! Err(e) => println!("Failed to read numbers!")
250 //! With `try!` in `file_product`, each `read_le_u32` need not be directly
251 //! concerned with error handling; instead its caller is responsible for
252 //! responding to errors that may occur while attempting to read the numbers.
254 #![unstable(feature = "old_io")]
255 #![deny(unused_must_use)]
256 #![allow(deprecated)] // seriously this is all deprecated
257 #![allow(unused_imports)]
258 #![deprecated(since = "1.0.0",
259 reasons = "APIs have been replaced with new I/O modules such as \
260 std::{io, fs, net, process}")]
262 pub use self::SeekStyle::*;
263 pub use self::FileMode::*;
264 pub use self::FileAccess::*;
265 pub use self::IoErrorKind::*;
267 use default::Default;
271 use iter::{Iterator, IteratorExt};
272 use marker::{PhantomFn, Sized};
276 use option::Option::{Some, None};
280 use result::Result::{Ok, Err};
289 pub use self::stdio::stdin;
290 pub use self::stdio::stdout;
291 pub use self::stdio::stderr;
292 pub use self::stdio::print;
293 pub use self::stdio::println;
295 pub use self::fs::File;
296 pub use self::timer::Timer;
297 pub use self::net::ip::IpAddr;
298 pub use self::net::tcp::TcpListener;
299 pub use self::net::tcp::TcpStream;
300 pub use self::pipe::PipeStream;
301 pub use self::process::{Process, Command};
302 pub use self::tempfile::TempDir;
304 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
305 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
307 pub use self::comm_adapters::{ChanReader, ChanWriter};
326 /// The default buffer size for various I/O operations
327 // libuv recommends 64k buffers to maximize throughput
328 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
329 const DEFAULT_BUF_SIZE: usize = 1024 * 64;
331 /// A convenient typedef of the return value of any I/O action.
332 pub type IoResult<T> = Result<T, IoError>;
334 /// The type passed to I/O condition handlers to indicate error
338 /// Is something like this sufficient? It's kind of archaic
339 #[derive(PartialEq, Eq, Clone, Debug)]
341 /// An enumeration which can be matched against for determining the flavor
343 pub kind: IoErrorKind,
344 /// A human-readable description about the error
345 pub desc: &'static str,
346 /// Detailed information about this error, not always available
347 pub detail: Option<String>
351 /// Convert an `errno` value into an `IoError`.
353 /// If `detail` is `true`, the `detail` field of the `IoError`
354 /// struct is filled with an allocated string describing the error
355 /// in more detail, retrieved from the operating system.
356 pub fn from_errno(errno: i32, detail: bool) -> IoError {
357 let mut err = sys::decode_error(errno as i32);
358 if detail && err.kind == OtherIoError {
359 err.detail = Some(os::error_string(errno).to_lowercase());
364 /// Retrieve the last error to occur as a (detailed) IoError.
366 /// This uses the OS `errno`, and so there should not be any task
367 /// descheduling or migration (other than that performed by the
368 /// operating system) between the call(s) for which errors are
369 /// being checked and the call of this function.
370 pub fn last_error() -> IoError {
371 IoError::from_errno(os::errno(), true)
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl fmt::Display for IoError {
377 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
379 IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
380 write!(fmt, "{}", detail),
381 IoError { detail: None, desc, .. } =>
382 write!(fmt, "{}", desc),
383 IoError { detail: Some(ref detail), desc, .. } =>
384 write!(fmt, "{} ({})", desc, detail)
389 impl Error for IoError {
390 fn description(&self) -> &str { self.desc }
393 /// A list specifying general categories of I/O error.
394 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
395 pub enum IoErrorKind {
396 /// Any I/O error not part of this list.
398 /// The operation could not complete because end of file was reached.
400 /// The file was not found.
402 /// The file permissions disallowed access to this file.
404 /// A network connection failed for some reason not specified in this list.
406 /// The network operation failed because the network connection was closed.
408 /// The connection was refused by the remote server.
410 /// The connection was reset by the remote server.
412 /// The connection was aborted (terminated) by the remote server.
414 /// The network operation failed because it was not connected yet.
416 /// The operation failed because a pipe was closed.
418 /// A file already existed with that name.
420 /// No file exists at that location.
422 /// The path did not specify the type of file that this operation required. For example,
423 /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
424 MismatchedFileTypeForOperation,
425 /// The operation temporarily failed (for example, because a signal was received), and retrying
428 /// No I/O functionality is available for this task.
430 /// A parameter was incorrect in a way that caused an I/O error not part of this list.
432 /// The I/O operation's timeout expired, causing it to be canceled.
434 /// This write operation failed to write all of its data.
436 /// Normally the write() method on a Writer guarantees that all of its data
437 /// has been written, but some operations may be terminated after only
438 /// partially writing some data. An example of this is a timed out write
439 /// which successfully wrote a known number of bytes, but bailed out after
442 /// The payload contained as part of this variant is the number of bytes
443 /// which are known to have been successfully written.
445 /// The Reader returned 0 bytes from `read()` too many times.
449 /// A trait that lets you add a `detail` to an IoError easily
450 trait UpdateIoError {
451 /// Returns an IoError with updated description and detail
452 fn update_err<D>(self, desc: &'static str, detail: D) -> Self where
453 D: FnOnce(&IoError) -> String;
455 /// Returns an IoError with updated detail
456 fn update_detail<D>(self, detail: D) -> Self where
457 D: FnOnce(&IoError) -> String;
459 /// Returns an IoError with update description
460 fn update_desc(self, desc: &'static str) -> Self;
463 impl<T> UpdateIoError for IoResult<T> {
464 fn update_err<D>(self, desc: &'static str, detail: D) -> IoResult<T> where
465 D: FnOnce(&IoError) -> String,
467 self.map_err(move |mut e| {
468 let detail = detail(&e);
470 e.detail = Some(detail);
475 fn update_detail<D>(self, detail: D) -> IoResult<T> where
476 D: FnOnce(&IoError) -> String,
478 self.map_err(move |mut e| { e.detail = Some(detail(&e)); e })
481 fn update_desc(self, desc: &'static str) -> IoResult<T> {
482 self.map_err(|mut e| { e.desc = desc; e })
486 static NO_PROGRESS_LIMIT: usize = 1000;
488 /// A trait for objects which are byte-oriented streams. Readers are defined by
489 /// one method, `read`. This function will block until data is available,
490 /// filling in the provided buffer with any data read.
492 /// Readers are intended to be composable with one another. Many objects
493 /// throughout the I/O and related libraries take and provide types which
494 /// implement the `Reader` trait.
497 // Only method which need to get implemented for this trait
499 /// Read bytes, up to the length of `buf` and place them in `buf`.
500 /// Returns the number of bytes read. The number of bytes read may
501 /// be less than the number requested, even 0. Returns `Err` on EOF.
505 /// If an error occurs during this I/O operation, then it is returned as
506 /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
507 /// inspected for in the error's `kind` field. Also note that reading 0
508 /// bytes is not considered an error in all circumstances
510 /// # Implementation Note
512 /// When implementing this method on a new Reader, you are strongly encouraged
513 /// not to return 0 if you can avoid it.
514 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize>;
516 // Convenient helper methods based on the above methods
518 /// Reads at least `min` bytes and places them in `buf`.
519 /// Returns the number of bytes read.
521 /// This will continue to call `read` until at least `min` bytes have been
522 /// read. If `read` returns 0 too many times, `NoProgress` will be
527 /// If an error occurs at any point, that error is returned, and no further
529 fn read_at_least(&mut self, min: usize, buf: &mut [u8]) -> IoResult<usize> {
532 detail: Some(String::from_str("the buffer is too short")),
533 ..standard_error(InvalidInput)
540 match self.read(&mut buf[read..]) {
543 if zeroes >= NO_PROGRESS_LIMIT {
544 return Err(standard_error(NoProgress));
551 err@Err(_) => return err
558 /// Reads a single byte. Returns `Err` on EOF.
559 fn read_byte(&mut self) -> IoResult<u8> {
561 try!(self.read_at_least(1, &mut buf));
565 /// Reads up to `len` bytes and appends them to a vector.
566 /// Returns the number of bytes read. The number of bytes read may be
567 /// less than the number requested, even 0. Returns Err on EOF.
571 /// If an error occurs during this I/O operation, then it is returned
572 /// as `Err(IoError)`. See `read()` for more details.
573 fn push(&mut self, len: usize, buf: &mut Vec<u8>) -> IoResult<usize> {
574 let start_len = buf.len();
578 let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
581 unsafe { buf.set_len(start_len + n) };
585 /// Reads at least `min` bytes, but no more than `len`, and appends them to
587 /// Returns the number of bytes read.
589 /// This will continue to call `read` until at least `min` bytes have been
590 /// read. If `read` returns 0 too many times, `NoProgress` will be
595 /// If an error occurs at any point, that error is returned, and no further
597 fn push_at_least(&mut self, min: usize, len: usize, buf: &mut Vec<u8>) -> IoResult<usize> {
600 detail: Some(String::from_str("the buffer is too short")),
601 ..standard_error(InvalidInput)
605 let start_len = buf.len();
608 // we can't just use self.read_at_least(min, slice) because we need to push
609 // successful reads onto the vector before any returned errors.
614 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
615 try!(self.read_at_least(1, s))
617 unsafe { buf.set_len(start_len + read) };
622 /// Reads exactly `len` bytes and gives you back a new vector of length
627 /// Fails with the same conditions as `read`. Additionally returns error
628 /// on EOF. Note that if an error is returned, then some number of bytes may
629 /// have already been consumed from the underlying reader, and they are lost
630 /// (not returned as part of the error). If this is unacceptable, then it is
631 /// recommended to use the `push_at_least` or `read` methods.
632 fn read_exact(&mut self, len: usize) -> IoResult<Vec<u8>> {
633 let mut buf = Vec::with_capacity(len);
634 match self.push_at_least(len, len, &mut buf) {
640 /// Reads all remaining bytes from the stream.
644 /// Returns any non-EOF error immediately. Previously read bytes are
645 /// discarded when an error is returned.
647 /// When EOF is encountered, all bytes read up to that point are returned.
648 fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
649 let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
651 match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
653 Err(ref e) if e.kind == EndOfFile => break,
654 Err(e) => return Err(e)
660 /// Reads all of the remaining bytes of this stream, interpreting them as a
661 /// UTF-8 encoded stream. The corresponding string is returned.
665 /// This function returns all of the same errors as `read_to_end` with an
666 /// additional error if the reader's contents are not a valid sequence of
668 fn read_to_string(&mut self) -> IoResult<String> {
669 self.read_to_end().and_then(|s| {
670 match String::from_utf8(s) {
672 Err(_) => Err(standard_error(InvalidInput)),
677 // Byte conversion helpers
679 /// Reads `n` little-endian unsigned integer bytes.
681 /// `n` must be between 1 and 8, inclusive.
682 fn read_le_uint_n(&mut self, nbytes: usize) -> IoResult<u64> {
683 assert!(nbytes > 0 && nbytes <= 8);
689 val += (try!(self.read_u8()) as u64) << pos;
696 /// Reads `n` little-endian signed integer bytes.
698 /// `n` must be between 1 and 8, inclusive.
699 fn read_le_int_n(&mut self, nbytes: usize) -> IoResult<i64> {
700 self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
703 /// Reads `n` big-endian unsigned integer bytes.
705 /// `n` must be between 1 and 8, inclusive.
706 fn read_be_uint_n(&mut self, nbytes: usize) -> IoResult<u64> {
707 assert!(nbytes > 0 && nbytes <= 8);
713 val += (try!(self.read_u8()) as u64) << i * 8;
718 /// Reads `n` big-endian signed integer bytes.
720 /// `n` must be between 1 and 8, inclusive.
721 fn read_be_int_n(&mut self, nbytes: usize) -> IoResult<i64> {
722 self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
725 /// Reads a little-endian unsigned integer.
727 /// The number of bytes returned is system-dependent.
728 fn read_le_uint(&mut self) -> IoResult<usize> {
729 self.read_le_uint_n(usize::BYTES as usize).map(|i| i as usize)
732 /// Reads a little-endian integer.
734 /// The number of bytes returned is system-dependent.
735 fn read_le_int(&mut self) -> IoResult<isize> {
736 self.read_le_int_n(isize::BYTES as usize).map(|i| i as isize)
739 /// Reads a big-endian unsigned integer.
741 /// The number of bytes returned is system-dependent.
742 fn read_be_uint(&mut self) -> IoResult<usize> {
743 self.read_be_uint_n(usize::BYTES as usize).map(|i| i as usize)
746 /// Reads a big-endian integer.
748 /// The number of bytes returned is system-dependent.
749 fn read_be_int(&mut self) -> IoResult<isize> {
750 self.read_be_int_n(isize::BYTES as usize).map(|i| i as isize)
753 /// Reads a big-endian `u64`.
755 /// `u64`s are 8 bytes long.
756 fn read_be_u64(&mut self) -> IoResult<u64> {
757 self.read_be_uint_n(8)
760 /// Reads a big-endian `u32`.
762 /// `u32`s are 4 bytes long.
763 fn read_be_u32(&mut self) -> IoResult<u32> {
764 self.read_be_uint_n(4).map(|i| i as u32)
767 /// Reads a big-endian `u16`.
769 /// `u16`s are 2 bytes long.
770 fn read_be_u16(&mut self) -> IoResult<u16> {
771 self.read_be_uint_n(2).map(|i| i as u16)
774 /// Reads a big-endian `i64`.
776 /// `i64`s are 8 bytes long.
777 fn read_be_i64(&mut self) -> IoResult<i64> {
778 self.read_be_int_n(8)
781 /// Reads a big-endian `i32`.
783 /// `i32`s are 4 bytes long.
784 fn read_be_i32(&mut self) -> IoResult<i32> {
785 self.read_be_int_n(4).map(|i| i as i32)
788 /// Reads a big-endian `i16`.
790 /// `i16`s are 2 bytes long.
791 fn read_be_i16(&mut self) -> IoResult<i16> {
792 self.read_be_int_n(2).map(|i| i as i16)
795 /// Reads a big-endian `f64`.
797 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
798 fn read_be_f64(&mut self) -> IoResult<f64> {
799 self.read_be_u64().map(|i| unsafe {
800 transmute::<u64, f64>(i)
804 /// Reads a big-endian `f32`.
806 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
807 fn read_be_f32(&mut self) -> IoResult<f32> {
808 self.read_be_u32().map(|i| unsafe {
809 transmute::<u32, f32>(i)
813 /// Reads a little-endian `u64`.
815 /// `u64`s are 8 bytes long.
816 fn read_le_u64(&mut self) -> IoResult<u64> {
817 self.read_le_uint_n(8)
820 /// Reads a little-endian `u32`.
822 /// `u32`s are 4 bytes long.
823 fn read_le_u32(&mut self) -> IoResult<u32> {
824 self.read_le_uint_n(4).map(|i| i as u32)
827 /// Reads a little-endian `u16`.
829 /// `u16`s are 2 bytes long.
830 fn read_le_u16(&mut self) -> IoResult<u16> {
831 self.read_le_uint_n(2).map(|i| i as u16)
834 /// Reads a little-endian `i64`.
836 /// `i64`s are 8 bytes long.
837 fn read_le_i64(&mut self) -> IoResult<i64> {
838 self.read_le_int_n(8)
841 /// Reads a little-endian `i32`.
843 /// `i32`s are 4 bytes long.
844 fn read_le_i32(&mut self) -> IoResult<i32> {
845 self.read_le_int_n(4).map(|i| i as i32)
848 /// Reads a little-endian `i16`.
850 /// `i16`s are 2 bytes long.
851 fn read_le_i16(&mut self) -> IoResult<i16> {
852 self.read_le_int_n(2).map(|i| i as i16)
855 /// Reads a little-endian `f64`.
857 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
858 fn read_le_f64(&mut self) -> IoResult<f64> {
859 self.read_le_u64().map(|i| unsafe {
860 transmute::<u64, f64>(i)
864 /// Reads a little-endian `f32`.
866 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
867 fn read_le_f32(&mut self) -> IoResult<f32> {
868 self.read_le_u32().map(|i| unsafe {
869 transmute::<u32, f32>(i)
875 /// `u8`s are 1 byte.
876 fn read_u8(&mut self) -> IoResult<u8> {
882 /// `i8`s are 1 byte.
883 fn read_i8(&mut self) -> IoResult<i8> {
884 self.read_byte().map(|i| i as i8)
888 /// A reader which can be converted to a RefReader.
889 pub trait ByRefReader {
890 /// Creates a wrapper around a mutable reference to the reader.
892 /// This is useful to allow applying adaptors while still
893 /// retaining ownership of the original value.
894 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
897 impl<T: Reader> ByRefReader for T {
898 fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
899 RefReader { inner: self }
903 /// A reader which can be converted to bytes.
904 pub trait BytesReader {
905 /// Create an iterator that reads a single byte on
906 /// each iteration, until EOF.
910 /// Any error other than `EndOfFile` that is produced by the underlying Reader
911 /// is returned by the iterator and should be handled by the caller.
912 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self>;
915 impl<T: Reader> BytesReader for T {
916 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, T> {
917 extensions::Bytes::new(self)
921 impl<'a> Reader for Box<Reader+'a> {
922 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
923 let reader: &mut Reader = &mut **self;
928 impl<'a> Reader for &'a mut (Reader+'a) {
929 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { (*self).read(buf) }
932 /// Returns a slice of `v` between `start` and `end`.
934 /// Similar to `slice()` except this function only bounds the slice on the
935 /// capacity of `v`, not the length.
939 /// Panics when `start` or `end` point outside the capacity of `v`, or when
941 // Private function here because we aren't sure if we want to expose this as
942 // API yet. If so, it should be a method on Vec.
943 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: usize, end: usize) -> &'a mut [T] {
946 assert!(start <= end);
947 assert!(end <= v.capacity());
948 slice::from_raw_parts_mut(
949 v.as_mut_ptr().offset(start as isize),
954 /// A `RefReader` is a struct implementing `Reader` which contains a reference
955 /// to another reader. This is often useful when composing streams.
960 /// # #![feature(old_io)]
961 /// use std::old_io as io;
962 /// use std::old_io::*;
963 /// use std::old_io::util::LimitReader;
965 /// fn process_input<R: Reader>(r: R) {}
967 /// let mut stream = io::stdin();
969 /// // Only allow the function to process at most one kilobyte of input
971 /// let stream = LimitReader::new(stream.by_ref(), 1024);
972 /// process_input(stream);
975 /// // 'stream' is still available for use here
977 pub struct RefReader<'a, R:'a> {
978 /// The underlying reader which this is referencing
982 impl<'a, R: Reader> Reader for RefReader<'a, R> {
983 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { self.inner.read(buf) }
986 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
987 fn fill_buf(&mut self) -> IoResult<&[u8]> { self.inner.fill_buf() }
988 fn consume(&mut self, amt: usize) { self.inner.consume(amt) }
991 fn extend_sign(val: u64, nbytes: usize) -> i64 {
992 let shift = (8 - nbytes) * 8;
993 (val << shift) as i64 >> shift
996 /// A trait for objects which are byte-oriented streams. Writers are defined by
997 /// one method, `write`. This function will block until the provided buffer of
998 /// bytes has been entirely written, and it will return any failures which occur.
1000 /// Another commonly overridden method is the `flush` method for writers such as
1001 /// buffered writers.
1003 /// Writers are intended to be composable with one another. Many objects
1004 /// throughout the I/O and related libraries take and provide types which
1005 /// implement the `Writer` trait.
1007 /// Write the entirety of a given buffer
1011 /// If an error happens during the I/O operation, the error is returned as
1012 /// `Err`. Note that it is considered an error if the entire buffer could
1013 /// not be written, and if an error is returned then it is unknown how much
1014 /// data (if any) was actually written.
1015 fn write_all(&mut self, buf: &[u8]) -> IoResult<()>;
1017 /// Deprecated, this method was renamed to `write_all`
1018 #[unstable(feature = "io")]
1019 #[deprecated(since = "1.0.0", reason = "renamed to `write_all`")]
1020 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write_all(buf) }
1022 /// Flush this output stream, ensuring that all intermediately buffered
1023 /// contents reach their destination.
1025 /// This is by default a no-op and implementers of the `Writer` trait should
1026 /// decide whether their stream needs to be buffered or not.
1027 fn flush(&mut self) -> IoResult<()> { Ok(()) }
1029 /// Writes a formatted string into this writer, returning any error
1032 /// This method is primarily used to interface with the `format_args!`
1033 /// macro, but it is rare that this should explicitly be called. The
1034 /// `write!` macro should be favored to invoke this method instead.
1038 /// This function will return any I/O error reported while formatting.
1039 fn write_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
1040 // Create a shim which translates a Writer to a fmt::Write and saves
1041 // off I/O errors. instead of discarding them
1042 struct Adaptor<'a, T: ?Sized +'a> {
1044 error: IoResult<()>,
1047 impl<'a, T: ?Sized + Writer> fmt::Write for Adaptor<'a, T> {
1048 fn write_str(&mut self, s: &str) -> fmt::Result {
1049 match self.inner.write_all(s.as_bytes()) {
1052 self.error = Err(e);
1059 let mut output = Adaptor { inner: self, error: Ok(()) };
1060 match fmt::write(&mut output, fmt) {
1062 Err(..) => output.error
1067 /// Write a rust string into this sink.
1069 /// The bytes written will be the UTF-8 encoded version of the input string.
1070 /// If other encodings are desired, it is recommended to compose this stream
1071 /// with another performing the conversion, or to use `write` with a
1072 /// converted byte-array instead.
1074 fn write_str(&mut self, s: &str) -> IoResult<()> {
1075 self.write_all(s.as_bytes())
1078 /// Writes a string into this sink, and then writes a literal newline (`\n`)
1079 /// byte afterwards. Note that the writing of the newline is *not* atomic in
1080 /// the sense that the call to `write` is invoked twice (once with the
1081 /// string and once with a newline character).
1083 /// If other encodings or line ending flavors are desired, it is recommended
1084 /// that the `write` method is used specifically instead.
1086 fn write_line(&mut self, s: &str) -> IoResult<()> {
1087 self.write_str(s).and_then(|()| self.write_all(&[b'\n']))
1090 /// Write a single char, encoded as UTF-8.
1092 fn write_char(&mut self, c: char) -> IoResult<()> {
1093 let mut buf = [0; 4];
1094 let n = c.encode_utf8(&mut buf).unwrap_or(0);
1095 self.write_all(&buf[..n])
1098 /// Write the result of passing n through `isize::to_str_bytes`.
1100 fn write_int(&mut self, n: isize) -> IoResult<()> {
1101 write!(self, "{}", n)
1104 /// Write the result of passing n through `usize::to_str_bytes`.
1106 fn write_uint(&mut self, n: usize) -> IoResult<()> {
1107 write!(self, "{}", n)
1110 /// Write a little-endian usize (number of bytes depends on system).
1112 fn write_le_uint(&mut self, n: usize) -> IoResult<()> {
1113 extensions::u64_to_le_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
1116 /// Write a little-endian isize (number of bytes depends on system).
1118 fn write_le_int(&mut self, n: isize) -> IoResult<()> {
1119 extensions::u64_to_le_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
1122 /// Write a big-endian usize (number of bytes depends on system).
1124 fn write_be_uint(&mut self, n: usize) -> IoResult<()> {
1125 extensions::u64_to_be_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
1128 /// Write a big-endian isize (number of bytes depends on system).
1130 fn write_be_int(&mut self, n: isize) -> IoResult<()> {
1131 extensions::u64_to_be_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
1134 /// Write a big-endian u64 (8 bytes).
1136 fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1137 extensions::u64_to_be_bytes(n, 8, |v| self.write_all(v))
1140 /// Write a big-endian u32 (4 bytes).
1142 fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1143 extensions::u64_to_be_bytes(n as u64, 4, |v| self.write_all(v))
1146 /// Write a big-endian u16 (2 bytes).
1148 fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1149 extensions::u64_to_be_bytes(n as u64, 2, |v| self.write_all(v))
1152 /// Write a big-endian i64 (8 bytes).
1154 fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1155 extensions::u64_to_be_bytes(n as u64, 8, |v| self.write_all(v))
1158 /// Write a big-endian i32 (4 bytes).
1160 fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1161 extensions::u64_to_be_bytes(n as u64, 4, |v| self.write_all(v))
1164 /// Write a big-endian i16 (2 bytes).
1166 fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1167 extensions::u64_to_be_bytes(n as u64, 2, |v| self.write_all(v))
1170 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1172 fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1174 self.write_be_u64(transmute(f))
1178 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1180 fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1182 self.write_be_u32(transmute(f))
1186 /// Write a little-endian u64 (8 bytes).
1188 fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1189 extensions::u64_to_le_bytes(n, 8, |v| self.write_all(v))
1192 /// Write a little-endian u32 (4 bytes).
1194 fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1195 extensions::u64_to_le_bytes(n as u64, 4, |v| self.write_all(v))
1198 /// Write a little-endian u16 (2 bytes).
1200 fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1201 extensions::u64_to_le_bytes(n as u64, 2, |v| self.write_all(v))
1204 /// Write a little-endian i64 (8 bytes).
1206 fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1207 extensions::u64_to_le_bytes(n as u64, 8, |v| self.write_all(v))
1210 /// Write a little-endian i32 (4 bytes).
1212 fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1213 extensions::u64_to_le_bytes(n as u64, 4, |v| self.write_all(v))
1216 /// Write a little-endian i16 (2 bytes).
1218 fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1219 extensions::u64_to_le_bytes(n as u64, 2, |v| self.write_all(v))
1222 /// Write a little-endian IEEE754 double-precision floating-point
1225 fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1227 self.write_le_u64(transmute(f))
1231 /// Write a little-endian IEEE754 single-precision floating-point
1234 fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1236 self.write_le_u32(transmute(f))
1240 /// Write a u8 (1 byte).
1242 fn write_u8(&mut self, n: u8) -> IoResult<()> {
1243 self.write_all(&[n])
1246 /// Write an i8 (1 byte).
1248 fn write_i8(&mut self, n: i8) -> IoResult<()> {
1249 self.write_all(&[n as u8])
1253 /// A writer which can be converted to a RefWriter.
1254 pub trait ByRefWriter {
1255 /// Creates a wrapper around a mutable reference to the writer.
1257 /// This is useful to allow applying wrappers while still
1258 /// retaining ownership of the original value.
1260 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1263 impl<T: Writer> ByRefWriter for T {
1264 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1265 RefWriter { inner: self }
1269 impl<'a> Writer for Box<Writer+'a> {
1271 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
1272 (&mut **self).write_all(buf)
1276 fn flush(&mut self) -> IoResult<()> {
1277 (&mut **self).flush()
1281 impl<'a> Writer for &'a mut (Writer+'a) {
1283 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write_all(buf) }
1286 fn flush(&mut self) -> IoResult<()> { (**self).flush() }
1289 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1290 /// to another writer. This is often useful when composing streams.
1295 /// # #![feature(old_io)]
1296 /// use std::old_io::util::TeeReader;
1297 /// use std::old_io::*;
1299 /// fn process_input<R: Reader>(r: R) {}
1301 /// let mut output = Vec::new();
1304 /// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1305 /// // handle to it in the outer scope
1306 /// let mut tee = TeeReader::new(stdin(), output.by_ref());
1307 /// process_input(tee);
1310 /// println!("input processed: {:?}", output);
1312 pub struct RefWriter<'a, W:'a> {
1313 /// The underlying writer which this is referencing
1317 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1319 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write_all(buf) }
1322 fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1326 /// A Stream is a readable and a writable object. Data written is typically
1327 /// received by the object which reads receive data from.
1328 pub trait Stream: Reader + Writer { }
1330 impl<T: Reader + Writer> Stream for T {}
1332 /// An iterator that reads a line on each iteration,
1333 /// until `.read_line()` encounters `EndOfFile`.
1335 /// # Notes about the Iteration Protocol
1337 /// The `Lines` may yield `None` and thus terminate
1338 /// an iteration, but continue to yield elements if iteration
1339 /// is attempted again.
1343 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1344 /// is returned by the iterator and should be handled by the caller.
1345 pub struct Lines<'r, T:'r> {
1349 impl<'r, T: Buffer> Iterator for Lines<'r, T> {
1350 type Item = IoResult<String>;
1352 fn next(&mut self) -> Option<IoResult<String>> {
1353 match self.buffer.read_line() {
1354 Ok(x) => Some(Ok(x)),
1355 Err(IoError { kind: EndOfFile, ..}) => None,
1356 Err(y) => Some(Err(y))
1361 /// An iterator that reads a utf8-encoded character on each iteration,
1362 /// until `.read_char()` encounters `EndOfFile`.
1364 /// # Notes about the Iteration Protocol
1366 /// The `Chars` may yield `None` and thus terminate
1367 /// an iteration, but continue to yield elements if iteration
1368 /// is attempted again.
1372 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1373 /// is returned by the iterator and should be handled by the caller.
1374 pub struct Chars<'r, T:'r> {
1378 impl<'r, T: Buffer> Iterator for Chars<'r, T> {
1379 type Item = IoResult<char>;
1381 fn next(&mut self) -> Option<IoResult<char>> {
1382 match self.buffer.read_char() {
1383 Ok(x) => Some(Ok(x)),
1384 Err(IoError { kind: EndOfFile, ..}) => None,
1385 Err(y) => Some(Err(y))
1390 /// A Buffer is a type of reader which has some form of internal buffering to
1391 /// allow certain kinds of reading operations to be more optimized than others.
1392 /// This type extends the `Reader` trait with a few methods that are not
1393 /// possible to reasonably implement with purely a read interface.
1394 pub trait Buffer: Reader {
1395 /// Fills the internal buffer of this object, returning the buffer contents.
1396 /// Note that none of the contents will be "read" in the sense that later
1397 /// calling `read` may return the same contents.
1399 /// The `consume` function must be called with the number of bytes that are
1400 /// consumed from this buffer returned to ensure that the bytes are never
1405 /// This function will return an I/O error if the underlying reader was
1406 /// read, but returned an error. Note that it is not an error to return a
1407 /// 0-length buffer.
1408 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1410 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1411 /// so they should no longer be returned in calls to `read`.
1412 fn consume(&mut self, amt: usize);
1414 /// Reads the next line of input, interpreted as a sequence of UTF-8
1415 /// encoded Unicode codepoints. If a newline is encountered, then the
1416 /// newline is contained in the returned string.
1421 /// # #![feature(old_io)]
1422 /// use std::old_io::*;
1424 /// let mut reader = BufReader::new(b"hello\nworld");
1425 /// assert_eq!("hello\n", &*reader.read_line().unwrap());
1430 /// This function has the same error semantics as `read_until`:
1432 /// * All non-EOF errors will be returned immediately
1433 /// * If an error is returned previously consumed bytes are lost
1434 /// * EOF is only returned if no bytes have been read
1435 /// * Reach EOF may mean that the delimiter is not present in the return
1438 /// Additionally, this function can fail if the line of input read is not a
1439 /// valid UTF-8 sequence of bytes.
1440 fn read_line(&mut self) -> IoResult<String> {
1441 self.read_until(b'\n').and_then(|line|
1442 match String::from_utf8(line) {
1444 Err(_) => Err(standard_error(InvalidInput)),
1449 /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1450 /// specified byte is encountered, reading ceases and the bytes up to and
1451 /// including the delimiter are returned.
1455 /// If any I/O error is encountered other than EOF, the error is immediately
1456 /// returned. Note that this may discard bytes which have already been read,
1457 /// and those bytes will *not* be returned. It is recommended to use other
1458 /// methods if this case is worrying.
1460 /// If EOF is encountered, then this function will return EOF if 0 bytes
1461 /// have been read, otherwise the pending byte buffer is returned. This
1462 /// is the reason that the byte buffer returned may not always contain the
1464 fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1465 let mut res = Vec::new();
1468 let (done, used) = {
1469 let available = match self.fill_buf() {
1471 Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1474 Err(e) => return Err(e)
1476 match available.iter().position(|&b| b == byte) {
1478 res.push_all(&available[..i + 1]);
1482 res.push_all(available);
1483 (false, available.len())
1494 /// Reads the next utf8-encoded character from the underlying stream.
1498 /// If an I/O error occurs, or EOF, then this function will return `Err`.
1499 /// This function will also return error if the stream does not contain a
1500 /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1501 fn read_char(&mut self) -> IoResult<char> {
1502 let first_byte = try!(self.read_byte());
1503 let width = unicode::str::utf8_char_width(first_byte);
1504 if width == 1 { return Ok(first_byte as char) }
1505 if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1506 let mut buf = [first_byte, 0, 0, 0];
1509 while start < width {
1510 match try!(self.read(&mut buf[start .. width])) {
1511 n if n == width - start => break,
1512 n if n < width - start => { start += n; }
1513 _ => return Err(standard_error(InvalidInput)),
1517 match str::from_utf8(&buf[..width]).ok() {
1518 Some(s) => Ok(s.char_at(0)),
1519 None => Err(standard_error(InvalidInput))
1524 /// Extension methods for the Buffer trait which are included in the prelude.
1525 pub trait BufferPrelude {
1526 /// Create an iterator that reads a utf8-encoded character on each iteration
1531 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1532 /// is returned by the iterator and should be handled by the caller.
1533 fn chars<'r>(&'r mut self) -> Chars<'r, Self>;
1535 /// Create an iterator that reads a line on each iteration until EOF.
1539 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1540 /// is returned by the iterator and should be handled by the caller.
1541 fn lines<'r>(&'r mut self) -> Lines<'r, Self>;
1544 impl<T: Buffer> BufferPrelude for T {
1545 fn chars<'r>(&'r mut self) -> Chars<'r, T> {
1546 Chars { buffer: self }
1549 fn lines<'r>(&'r mut self) -> Lines<'r, T> {
1550 Lines { buffer: self }
1554 /// When seeking, the resulting cursor is offset from a base by the offset given
1555 /// to the `seek` function. The base used is specified by this enumeration.
1557 pub enum SeekStyle {
1558 /// Seek from the beginning of the stream
1560 /// Seek from the end of the stream
1562 /// Seek from the current position
1566 /// An object implementing `Seek` internally has some form of cursor which can
1567 /// be moved within a stream of bytes. The stream typically has a fixed size,
1568 /// allowing seeking relative to either end.
1570 /// Return position of file cursor in the stream
1571 fn tell(&self) -> IoResult<u64>;
1573 /// Seek to an offset in a stream
1575 /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1576 /// allowed, but seeking before position 0 is not allowed.
1580 /// * Seeking to a negative offset is considered an error
1581 /// * Seeking past the end of the stream does not modify the underlying
1582 /// stream, but the next write may cause the previous data to be filled in
1583 /// with a bit pattern.
1584 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1587 /// A listener is a value that can consume itself to start listening for
1590 /// Doing so produces some sort of Acceptor.
1591 pub trait Listener<A: Acceptor> {
1592 /// Spin up the listener and start queuing incoming connections
1596 /// Returns `Err` if this listener could not be bound to listen for
1597 /// connections. In all cases, this listener is consumed.
1598 fn listen(self) -> IoResult<A>;
1601 /// An acceptor is a value that presents incoming connections
1602 pub trait Acceptor {
1603 /// Type of connection that is accepted by this acceptor.
1606 /// Wait for and accept an incoming connection
1610 /// Returns `Err` if an I/O error is encountered.
1611 fn accept(&mut self) -> IoResult<Self::Connection>;
1613 /// Create an iterator over incoming connection attempts.
1615 /// Note that I/O errors will be yielded by the iterator itself.
1616 fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1617 IncomingConnections { inc: self }
1621 /// An infinite iterator over incoming connection attempts.
1622 /// Calling `next` will block the task until a connection is attempted.
1624 /// Since connection attempts can continue forever, this iterator always returns
1625 /// `Some`. The `Some` contains the `IoResult` representing whether the
1626 /// connection attempt was successful. A successful connection will be wrapped
1627 /// in `Ok`. A failed connection is represented as an `Err`.
1628 pub struct IncomingConnections<'a, A: ?Sized +'a> {
1632 impl<'a, A: ?Sized + Acceptor> Iterator for IncomingConnections<'a, A> {
1633 type Item = IoResult<A::Connection>;
1635 fn next(&mut self) -> Option<IoResult<A::Connection>> {
1636 Some(self.inc.accept())
1640 /// Creates a standard error for a commonly used flavor of error. The `detail`
1641 /// field of the returned error will always be `None`.
1646 /// # #![feature(old_io)]
1647 /// use std::old_io as io;
1649 /// let eof = io::standard_error(io::EndOfFile);
1650 /// let einval = io::standard_error(io::InvalidInput);
1652 pub fn standard_error(kind: IoErrorKind) -> IoError {
1653 let desc = match kind {
1654 EndOfFile => "end of file",
1655 IoUnavailable => "I/O is unavailable",
1656 InvalidInput => "invalid input",
1657 OtherIoError => "unknown I/O error",
1658 FileNotFound => "file not found",
1659 PermissionDenied => "permission denied",
1660 ConnectionFailed => "connection failed",
1661 Closed => "stream is closed",
1662 ConnectionRefused => "connection refused",
1663 ConnectionReset => "connection reset",
1664 ConnectionAborted => "connection aborted",
1665 NotConnected => "not connected",
1666 BrokenPipe => "broken pipe",
1667 PathAlreadyExists => "file already exists",
1668 PathDoesntExist => "no such file",
1669 MismatchedFileTypeForOperation => "mismatched file type",
1670 ResourceUnavailable => "resource unavailable",
1671 TimedOut => "operation timed out",
1672 ShortWrite(..) => "short write",
1673 NoProgress => "no progress",
1682 /// A mode specifies how a file should be opened or created. These modes are
1683 /// passed to `File::open_mode` and are used to control where the file is
1684 /// positioned when it is initially opened.
1685 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1687 /// Opens a file positioned at the beginning.
1689 /// Opens a file positioned at EOF.
1691 /// Opens a file, truncating it if it already exists.
1695 /// Access permissions with which the file should be opened. `File`s
1696 /// opened with `Read` will return an error if written to.
1697 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1698 pub enum FileAccess {
1699 /// Read-only access, requests to write will result in an error
1701 /// Write-only access, requests to read will result in an error
1703 /// Read-write access, no requests are denied by default
1707 /// Different kinds of files which can be identified by a call to stat
1708 #[derive(Copy, PartialEq, Debug, Hash, Clone)]
1710 /// This is a normal file, corresponding to `S_IFREG`
1713 /// This file is a directory, corresponding to `S_IFDIR`
1716 /// This file is a named pipe, corresponding to `S_IFIFO`
1719 /// This file is a block device, corresponding to `S_IFBLK`
1722 /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1725 /// The type of this file is not recognized as one of the other categories
1729 /// A structure used to describe metadata information about a file. This
1730 /// structure is created through the `stat` method on a `Path`.
1735 /// # #![feature(old_io, old_path)]
1737 /// use std::old_io::fs::PathExtensions;
1738 /// use std::old_path::Path;
1740 /// let info = match Path::new("foo.txt").stat() {
1741 /// Ok(stat) => stat,
1742 /// Err(e) => panic!("couldn't read foo.txt: {}", e),
1745 /// println!("byte size: {}", info.size);
1747 #[derive(Copy, Hash)]
1748 pub struct FileStat {
1749 /// The size of the file, in bytes
1751 /// The kind of file this path points to (directory, file, pipe, etc.)
1753 /// The file permissions currently on the file
1754 pub perm: FilePermission,
1756 // FIXME(#10301): These time fields are pretty useless without an actual
1757 // time representation, what are the milliseconds relative
1760 /// The time that the file was created at, in platform-dependent
1763 /// The time that this file was last modified, in platform-dependent
1766 /// The time that this file was last accessed, in platform-dependent
1770 /// Information returned by stat() which is not guaranteed to be
1771 /// platform-independent. This information may be useful on some platforms,
1772 /// but it may have different meanings or no meaning at all on other
1775 /// Usage of this field is discouraged, but if access is desired then the
1776 /// fields are located here.
1777 #[unstable(feature = "io")]
1778 pub unstable: UnstableFileStat,
1781 /// This structure represents all of the possible information which can be
1782 /// returned from a `stat` syscall which is not contained in the `FileStat`
1783 /// structure. This information is not necessarily platform independent, and may
1784 /// have different meanings or no meaning at all on some platforms.
1785 #[unstable(feature = "io")]
1786 #[derive(Copy, Hash)]
1787 pub struct UnstableFileStat {
1788 /// The ID of the device containing the file.
1790 /// The file serial number.
1794 /// The number of hard links to this file.
1796 /// The user ID of the file.
1798 /// The group ID of the file.
1800 /// The optimal block size for I/O.
1802 /// The blocks allocated for this file.
1804 /// User-defined flags for the file.
1806 /// The file generation number.
1812 /// A set of permissions for a file or directory is represented by a set of
1813 /// flags which are or'd together.
1815 flags FilePermission: u32 {
1816 const USER_READ = 0o400,
1817 const USER_WRITE = 0o200,
1818 const USER_EXECUTE = 0o100,
1819 const GROUP_READ = 0o040,
1820 const GROUP_WRITE = 0o020,
1821 const GROUP_EXECUTE = 0o010,
1822 const OTHER_READ = 0o004,
1823 const OTHER_WRITE = 0o002,
1824 const OTHER_EXECUTE = 0o001,
1826 const USER_RWX = USER_READ.bits | USER_WRITE.bits | USER_EXECUTE.bits,
1827 const GROUP_RWX = GROUP_READ.bits | GROUP_WRITE.bits | GROUP_EXECUTE.bits,
1828 const OTHER_RWX = OTHER_READ.bits | OTHER_WRITE.bits | OTHER_EXECUTE.bits,
1830 /// Permissions for user owned files, equivalent to 0644 on unix-like
1832 const USER_FILE = USER_READ.bits | USER_WRITE.bits | GROUP_READ.bits | OTHER_READ.bits,
1834 /// Permissions for user owned directories, equivalent to 0755 on
1835 /// unix-like systems.
1836 const USER_DIR = USER_RWX.bits | GROUP_READ.bits | GROUP_EXECUTE.bits |
1837 OTHER_READ.bits | OTHER_EXECUTE.bits,
1839 /// Permissions for user owned executables, equivalent to 0755
1840 /// on unix-like systems.
1841 const USER_EXEC = USER_DIR.bits,
1843 /// All possible permissions enabled.
1844 const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl Default for FilePermission {
1851 #[stable(feature = "rust1", since = "1.0.0")]
1853 fn default() -> FilePermission { FilePermission::empty() }
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl fmt::Display for FilePermission {
1858 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1859 write!(f, "{:04o}", self.bits)
1865 use self::BadReaderBehavior::*;
1866 use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
1868 use prelude::v1::{Ok, Vec};
1871 #[derive(Clone, PartialEq, Debug)]
1872 enum BadReaderBehavior {
1873 GoodBehavior(usize),
1877 struct BadReader<T> {
1879 behavior: Vec<BadReaderBehavior>,
1882 impl<T: Reader> BadReader<T> {
1883 fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1884 BadReader { behavior: behavior, r: r }
1888 impl<T: Reader> Reader for BadReader<T> {
1889 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
1890 let BadReader { ref mut behavior, ref mut r } = *self;
1892 if behavior.is_empty() {
1893 // fall back on good
1896 match (&mut **behavior)[0] {
1897 GoodBehavior(0) => (),
1898 GoodBehavior(ref mut x) => {
1902 BadBehavior(0) => (),
1903 BadBehavior(ref mut x) => {
1914 fn test_read_at_least() {
1915 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1916 vec![GoodBehavior(usize::MAX)]);
1917 let buf = &mut [0; 5];
1918 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1919 assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1920 assert!(r.read_at_least(0, buf).is_ok());
1922 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1923 vec![BadBehavior(50), GoodBehavior(usize::MAX)]);
1924 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1926 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1927 vec![BadBehavior(1), GoodBehavior(1),
1928 BadBehavior(50), GoodBehavior(usize::MAX)]);
1929 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1930 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1932 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1933 vec![BadBehavior(usize::MAX)]);
1934 assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1936 let mut r = MemReader::new(b"hello, world!".to_vec());
1937 assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1938 assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1942 fn test_push_at_least() {
1943 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1944 vec![GoodBehavior(usize::MAX)]);
1945 let mut buf = Vec::new();
1946 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1947 assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1949 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1950 vec![BadBehavior(50), GoodBehavior(usize::MAX)]);
1951 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1953 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1954 vec![BadBehavior(1), GoodBehavior(1),
1955 BadBehavior(50), GoodBehavior(usize::MAX)]);
1956 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1957 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1959 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1960 vec![BadBehavior(usize::MAX)]);
1961 assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1963 let mut r = MemReader::new(b"hello, world!".to_vec());
1964 assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
1971 assert_eq!(format!("{}", USER_READ), "0400");
1972 assert_eq!(format!("{}", USER_FILE), "0644");
1973 assert_eq!(format!("{}", USER_EXEC), "0755");
1974 assert_eq!(format!("{}", USER_RWX), "0700");
1975 assert_eq!(format!("{}", GROUP_RWX), "0070");
1976 assert_eq!(format!("{}", OTHER_RWX), "0007");
1977 assert_eq!(format!("{}", ALL_PERMISSIONS), "0777");
1978 assert_eq!(format!("{}", USER_READ | USER_WRITE | OTHER_WRITE), "0602");
1981 fn _ensure_buffer_is_object_safe<T: Buffer>(x: &T) -> &Buffer {