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 //! `std::io` provides Rust's basic I/O types,
22 //! for reading and writing to files, TCP, UDP,
23 //! and other types of sockets and pipes,
24 //! manipulating the file system, spawning processes.
28 //! Some examples of obvious things you might want to do
30 //! * Read lines from stdin
35 //! for line in io::stdin().lock().lines() {
36 //! print!("{}", line.unwrap());
40 //! * Read a complete file
43 //! use std::io::File;
45 //! let contents = File::open(&Path::new("message.txt")).read_to_end();
48 //! * Write a line to a file
51 //! # #![allow(unused_must_use)]
52 //! use std::io::File;
54 //! let mut file = File::create(&Path::new("message.txt"));
55 //! file.write(b"hello, file!\n");
57 //! # ::std::io::fs::unlink(&Path::new("message.txt"));
60 //! * Iterate over the lines of a file
63 //! use std::io::BufferedReader;
64 //! use std::io::File;
66 //! let path = Path::new("message.txt");
67 //! let mut file = BufferedReader::new(File::open(&path));
68 //! for line in file.lines() {
69 //! print!("{}", line.unwrap());
73 //! * Pull the lines of a file into a vector of strings
76 //! use std::io::BufferedReader;
77 //! use std::io::File;
79 //! let path = Path::new("message.txt");
80 //! let mut file = BufferedReader::new(File::open(&path));
81 //! let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
84 //! * Make a simple TCP client connection and request
87 //! # #![allow(unused_must_use)]
88 //! use std::io::TcpStream;
90 //! # // connection doesn't fail if a server is running on 8080
91 //! # // locally, we still want to be type checking this code, so lets
92 //! # // just stop it running (#11576)
94 //! let mut socket = TcpStream::connect("127.0.0.1:8080").unwrap();
95 //! socket.write(b"GET / HTTP/1.0\n\n");
96 //! let response = socket.read_to_end();
100 //! * Make a simple TCP server
105 //! # #![allow(dead_code)]
106 //! use std::io::{TcpListener, TcpStream};
107 //! use std::io::{Acceptor, Listener};
108 //! use std::thread::Thread;
110 //! let listener = TcpListener::bind("127.0.0.1:80");
112 //! // bind the listener to the specified address
113 //! let mut acceptor = listener.listen();
115 //! fn handle_client(mut stream: TcpStream) {
117 //! # &mut stream; // silence unused mutability/variable warning
119 //! // accept connections and process them, spawning a new tasks for each one
120 //! for stream in acceptor.incoming() {
122 //! Err(e) => { /* connection failed */ }
123 //! Ok(stream) => Thread::spawn(move|| {
124 //! // connection succeeded
125 //! handle_client(stream)
130 //! // close the socket server
138 //! I/O is an area where nearly every operation can result in unexpected
139 //! errors. Errors should be painfully visible when they happen, and handling them
140 //! should be easy to work with. It should be convenient to handle specific I/O
141 //! errors, and it should also be convenient to not deal with I/O errors.
143 //! Rust's I/O employs a combination of techniques to reduce boilerplate
144 //! while still providing feedback about errors. The basic strategy:
146 //! * All I/O operations return `IoResult<T>` which is equivalent to
147 //! `Result<T, IoError>`. The `Result` type is defined in the `std::result`
149 //! * If the `Result` type goes unused, then the compiler will by default emit a
150 //! warning about the unused result. This is because `Result` has the
151 //! `#[must_use]` attribute.
152 //! * Common traits are implemented for `IoResult`, e.g.
153 //! `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
154 //! to be 'unwrapped' before use.
156 //! These features combine in the API to allow for expressions like
157 //! `File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")`
158 //! without having to worry about whether "diary.txt" exists or whether
159 //! the write succeeds. As written, if either `new` or `write_line`
160 //! encounters an error then the result of the entire expression will
163 //! If you wanted to handle the error though you might write:
166 //! # #![allow(unused_must_use)]
167 //! use std::io::File;
169 //! match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") {
170 //! Ok(()) => (), // succeeded
171 //! Err(e) => println!("failed to write to my diary: {}", e),
174 //! # ::std::io::fs::unlink(&Path::new("diary.txt"));
177 //! So what actually happens if `create` encounters an error?
178 //! It's important to know that what `new` returns is not a `File`
179 //! but an `IoResult<File>`. If the file does not open, then `new` will simply
180 //! return `Err(..)`. Because there is an implementation of `Writer` (the trait
181 //! required ultimately required for types to implement `write_line`) there is no
182 //! need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
183 //! on it. If `new` returned an `Err(..)` then the followup call to `write_line`
184 //! will also return an error.
188 //! Explicit pattern matching on `IoResult`s can get quite verbose, especially
189 //! when performing many I/O operations. Some examples (like those above) are
190 //! alleviated with extra methods implemented on `IoResult`, but others have more
191 //! complex interdependencies among each I/O operation.
193 //! The `try!` macro from `std::macros` is provided as a method of early-return
194 //! inside `Result`-returning functions. It expands to an early-return on `Err`
195 //! and otherwise unwraps the contained `Ok` value.
197 //! If you wanted to read several `u32`s from a file and return their product:
200 //! use std::io::{File, IoResult};
202 //! fn file_product(p: &Path) -> IoResult<u32> {
203 //! let mut f = File::open(p);
204 //! let x1 = try!(f.read_le_u32());
205 //! let x2 = try!(f.read_le_u32());
210 //! match file_product(&Path::new("numbers.bin")) {
211 //! Ok(x) => println!("{}", x),
212 //! Err(e) => println!("Failed to read numbers!")
216 //! With `try!` in `file_product`, each `read_le_u32` need not be directly
217 //! concerned with error handling; instead its caller is responsible for
218 //! responding to errors that may occur while attempting to read the numbers.
221 #![deny(unused_must_use)]
223 pub use self::SeekStyle::*;
224 pub use self::FileMode::*;
225 pub use self::FileAccess::*;
226 pub use self::IoErrorKind::*;
230 use default::Default;
231 use error::{FromError, Error};
234 use iter::{Iterator, IteratorExt};
239 use option::Option::{Some, None};
243 use result::Result::{Ok, Err};
251 use unicode::char::UnicodeChar;
255 pub use self::stdio::stdin;
256 pub use self::stdio::stdout;
257 pub use self::stdio::stderr;
258 pub use self::stdio::print;
259 pub use self::stdio::println;
261 pub use self::fs::File;
262 pub use self::timer::Timer;
263 pub use self::net::ip::IpAddr;
264 pub use self::net::tcp::TcpListener;
265 pub use self::net::tcp::TcpStream;
266 pub use self::net::udp::UdpStream;
267 pub use self::pipe::PipeStream;
268 pub use self::process::{Process, Command};
269 pub use self::tempfile::TempDir;
271 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
272 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
274 pub use self::comm_adapters::{ChanReader, ChanWriter};
291 /// The default buffer size for various I/O operations
292 // libuv recommends 64k buffers to maximize throughput
293 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
294 const DEFAULT_BUF_SIZE: uint = 1024 * 64;
296 /// A convenient typedef of the return value of any I/O action.
297 pub type IoResult<T> = Result<T, IoError>;
299 /// The type passed to I/O condition handlers to indicate error
303 /// Is something like this sufficient? It's kind of archaic
304 #[deriving(PartialEq, Eq, Clone)]
306 /// An enumeration which can be matched against for determining the flavor
308 pub kind: IoErrorKind,
309 /// A human-readable description about the error
310 pub desc: &'static str,
311 /// Detailed information about this error, not always available
312 pub detail: Option<String>
316 /// Convert an `errno` value into an `IoError`.
318 /// If `detail` is `true`, the `detail` field of the `IoError`
319 /// struct is filled with an allocated string describing the error
320 /// in more detail, retrieved from the operating system.
321 pub fn from_errno(errno: uint, detail: bool) -> IoError {
322 let mut err = sys::decode_error(errno as i32);
323 if detail && err.kind == OtherIoError {
324 err.detail = Some(os::error_string(errno).chars()
325 .map(|c| c.to_lowercase()).collect())
330 /// Retrieve the last error to occur as a (detailed) IoError.
332 /// This uses the OS `errno`, and so there should not be any task
333 /// descheduling or migration (other than that performed by the
334 /// operating system) between the call(s) for which errors are
335 /// being checked and the call of this function.
336 pub fn last_error() -> IoError {
337 IoError::from_errno(os::errno() as uint, true)
341 impl fmt::Show for IoError {
342 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
344 IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
345 write!(fmt, "{}", detail),
346 IoError { detail: None, desc, .. } =>
347 write!(fmt, "{}", desc),
348 IoError { detail: Some(ref detail), desc, .. } =>
349 write!(fmt, "{} ({})", desc, detail)
354 impl Error for IoError {
355 fn description(&self) -> &str {
359 fn detail(&self) -> Option<String> {
364 impl FromError<IoError> for Box<Error> {
365 fn from_error(err: IoError) -> Box<Error> {
370 /// A list specifying general categories of I/O error.
371 #[deriving(Copy, PartialEq, Eq, Clone, Show)]
372 pub enum IoErrorKind {
373 /// Any I/O error not part of this list.
375 /// The operation could not complete because end of file was reached.
377 /// The file was not found.
379 /// The file permissions disallowed access to this file.
381 /// A network connection failed for some reason not specified in this list.
383 /// The network operation failed because the network connection was closed.
385 /// The connection was refused by the remote server.
387 /// The connection was reset by the remote server.
389 /// The connection was aborted (terminated) by the remote server.
391 /// The network operation failed because it was not connected yet.
393 /// The operation failed because a pipe was closed.
395 /// A file already existed with that name.
397 /// No file exists at that location.
399 /// The path did not specify the type of file that this operation required. For example,
400 /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
401 MismatchedFileTypeForOperation,
402 /// The operation temporarily failed (for example, because a signal was received), and retrying
405 /// No I/O functionality is available for this task.
407 /// A parameter was incorrect in a way that caused an I/O error not part of this list.
409 /// The I/O operation's timeout expired, causing it to be canceled.
411 /// This write operation failed to write all of its data.
413 /// Normally the write() method on a Writer guarantees that all of its data
414 /// has been written, but some operations may be terminated after only
415 /// partially writing some data. An example of this is a timed out write
416 /// which successfully wrote a known number of bytes, but bailed out after
419 /// The payload contained as part of this variant is the number of bytes
420 /// which are known to have been successfully written.
422 /// The Reader returned 0 bytes from `read()` too many times.
426 /// A trait that lets you add a `detail` to an IoError easily
427 trait UpdateIoError<T> {
428 /// Returns an IoError with updated description and detail
429 fn update_err<D>(self, desc: &'static str, detail: D) -> Self where
430 D: FnOnce(&IoError) -> String;
432 /// Returns an IoError with updated detail
433 fn update_detail<D>(self, detail: D) -> Self where
434 D: FnOnce(&IoError) -> String;
436 /// Returns an IoError with update description
437 fn update_desc(self, desc: &'static str) -> Self;
440 impl<T> UpdateIoError<T> for IoResult<T> {
441 fn update_err<D>(self, desc: &'static str, detail: D) -> IoResult<T> where
442 D: FnOnce(&IoError) -> String,
444 self.map_err(move |mut e| {
445 let detail = detail(&e);
447 e.detail = Some(detail);
452 fn update_detail<D>(self, detail: D) -> IoResult<T> where
453 D: FnOnce(&IoError) -> String,
455 self.map_err(move |mut e| { e.detail = Some(detail(&e)); e })
458 fn update_desc(self, desc: &'static str) -> IoResult<T> {
459 self.map_err(|mut e| { e.desc = desc; e })
463 static NO_PROGRESS_LIMIT: uint = 1000;
465 /// A trait for objects which are byte-oriented streams. Readers are defined by
466 /// one method, `read`. This function will block until data is available,
467 /// filling in the provided buffer with any data read.
469 /// Readers are intended to be composable with one another. Many objects
470 /// throughout the I/O and related libraries take and provide types which
471 /// implement the `Reader` trait.
474 // Only method which need to get implemented for this trait
476 /// Read bytes, up to the length of `buf` and place them in `buf`.
477 /// Returns the number of bytes read. The number of bytes read may
478 /// be less than the number requested, even 0. Returns `Err` on EOF.
482 /// If an error occurs during this I/O operation, then it is returned as
483 /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
484 /// inspected for in the error's `kind` field. Also note that reading 0
485 /// bytes is not considered an error in all circumstances
487 /// # Implementation Note
489 /// When implementing this method on a new Reader, you are strongly encouraged
490 /// not to return 0 if you can avoid it.
491 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
493 // Convenient helper methods based on the above methods
495 /// Reads at least `min` bytes and places them in `buf`.
496 /// Returns the number of bytes read.
498 /// This will continue to call `read` until at least `min` bytes have been
499 /// read. If `read` returns 0 too many times, `NoProgress` will be
504 /// If an error occurs at any point, that error is returned, and no further
506 fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
509 detail: Some(String::from_str("the buffer is too short")),
510 ..standard_error(InvalidInput)
517 match self.read(buf.slice_from_mut(read)) {
520 if zeroes >= NO_PROGRESS_LIMIT {
521 return Err(standard_error(NoProgress));
528 err@Err(_) => return err
535 /// Reads a single byte. Returns `Err` on EOF.
536 fn read_byte(&mut self) -> IoResult<u8> {
538 try!(self.read_at_least(1, &mut buf));
542 /// Reads up to `len` bytes and appends them to a vector.
543 /// Returns the number of bytes read. The number of bytes read may be
544 /// less than the number requested, even 0. Returns Err on EOF.
548 /// If an error occurs during this I/O operation, then it is returned
549 /// as `Err(IoError)`. See `read()` for more details.
550 fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
551 let start_len = buf.len();
555 let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
558 unsafe { buf.set_len(start_len + n) };
562 /// Reads at least `min` bytes, but no more than `len`, and appends them to
564 /// Returns the number of bytes read.
566 /// This will continue to call `read` until at least `min` bytes have been
567 /// read. If `read` returns 0 too many times, `NoProgress` will be
572 /// If an error occurs at any point, that error is returned, and no further
574 fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
577 detail: Some(String::from_str("the buffer is too short")),
578 ..standard_error(InvalidInput)
582 let start_len = buf.len();
585 // we can't just use self.read_at_least(min, slice) because we need to push
586 // successful reads onto the vector before any returned errors.
591 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
592 try!(self.read_at_least(1, s))
594 unsafe { buf.set_len(start_len + read) };
599 /// Reads exactly `len` bytes and gives you back a new vector of length
604 /// Fails with the same conditions as `read`. Additionally returns error
605 /// on EOF. Note that if an error is returned, then some number of bytes may
606 /// have already been consumed from the underlying reader, and they are lost
607 /// (not returned as part of the error). If this is unacceptable, then it is
608 /// recommended to use the `push_at_least` or `read` methods.
609 fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
610 let mut buf = Vec::with_capacity(len);
611 match self.push_at_least(len, len, &mut buf) {
617 /// Reads all remaining bytes from the stream.
621 /// Returns any non-EOF error immediately. Previously read bytes are
622 /// discarded when an error is returned.
624 /// When EOF is encountered, all bytes read up to that point are returned.
625 fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
626 let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
628 match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
630 Err(ref e) if e.kind == EndOfFile => break,
631 Err(e) => return Err(e)
637 /// Reads all of the remaining bytes of this stream, interpreting them as a
638 /// UTF-8 encoded stream. The corresponding string is returned.
642 /// This function returns all of the same errors as `read_to_end` with an
643 /// additional error if the reader's contents are not a valid sequence of
645 fn read_to_string(&mut self) -> IoResult<String> {
646 self.read_to_end().and_then(|s| {
647 match String::from_utf8(s) {
649 Err(_) => Err(standard_error(InvalidInput)),
654 // Byte conversion helpers
656 /// Reads `n` little-endian unsigned integer bytes.
658 /// `n` must be between 1 and 8, inclusive.
659 fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
660 assert!(nbytes > 0 && nbytes <= 8);
666 val += (try!(self.read_u8()) as u64) << pos;
673 /// Reads `n` little-endian signed integer bytes.
675 /// `n` must be between 1 and 8, inclusive.
676 fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
677 self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
680 /// Reads `n` big-endian unsigned integer bytes.
682 /// `n` must be between 1 and 8, inclusive.
683 fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
684 assert!(nbytes > 0 && nbytes <= 8);
690 val += (try!(self.read_u8()) as u64) << i * 8;
695 /// Reads `n` big-endian signed integer bytes.
697 /// `n` must be between 1 and 8, inclusive.
698 fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
699 self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
702 /// Reads a little-endian unsigned integer.
704 /// The number of bytes returned is system-dependent.
705 fn read_le_uint(&mut self) -> IoResult<uint> {
706 self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
709 /// Reads a little-endian integer.
711 /// The number of bytes returned is system-dependent.
712 fn read_le_int(&mut self) -> IoResult<int> {
713 self.read_le_int_n(int::BYTES).map(|i| i as int)
716 /// Reads a big-endian unsigned integer.
718 /// The number of bytes returned is system-dependent.
719 fn read_be_uint(&mut self) -> IoResult<uint> {
720 self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
723 /// Reads a big-endian integer.
725 /// The number of bytes returned is system-dependent.
726 fn read_be_int(&mut self) -> IoResult<int> {
727 self.read_be_int_n(int::BYTES).map(|i| i as int)
730 /// Reads a big-endian `u64`.
732 /// `u64`s are 8 bytes long.
733 fn read_be_u64(&mut self) -> IoResult<u64> {
734 self.read_be_uint_n(8)
737 /// Reads a big-endian `u32`.
739 /// `u32`s are 4 bytes long.
740 fn read_be_u32(&mut self) -> IoResult<u32> {
741 self.read_be_uint_n(4).map(|i| i as u32)
744 /// Reads a big-endian `u16`.
746 /// `u16`s are 2 bytes long.
747 fn read_be_u16(&mut self) -> IoResult<u16> {
748 self.read_be_uint_n(2).map(|i| i as u16)
751 /// Reads a big-endian `i64`.
753 /// `i64`s are 8 bytes long.
754 fn read_be_i64(&mut self) -> IoResult<i64> {
755 self.read_be_int_n(8)
758 /// Reads a big-endian `i32`.
760 /// `i32`s are 4 bytes long.
761 fn read_be_i32(&mut self) -> IoResult<i32> {
762 self.read_be_int_n(4).map(|i| i as i32)
765 /// Reads a big-endian `i16`.
767 /// `i16`s are 2 bytes long.
768 fn read_be_i16(&mut self) -> IoResult<i16> {
769 self.read_be_int_n(2).map(|i| i as i16)
772 /// Reads a big-endian `f64`.
774 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
775 fn read_be_f64(&mut self) -> IoResult<f64> {
776 self.read_be_u64().map(|i| unsafe {
777 transmute::<u64, f64>(i)
781 /// Reads a big-endian `f32`.
783 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
784 fn read_be_f32(&mut self) -> IoResult<f32> {
785 self.read_be_u32().map(|i| unsafe {
786 transmute::<u32, f32>(i)
790 /// Reads a little-endian `u64`.
792 /// `u64`s are 8 bytes long.
793 fn read_le_u64(&mut self) -> IoResult<u64> {
794 self.read_le_uint_n(8)
797 /// Reads a little-endian `u32`.
799 /// `u32`s are 4 bytes long.
800 fn read_le_u32(&mut self) -> IoResult<u32> {
801 self.read_le_uint_n(4).map(|i| i as u32)
804 /// Reads a little-endian `u16`.
806 /// `u16`s are 2 bytes long.
807 fn read_le_u16(&mut self) -> IoResult<u16> {
808 self.read_le_uint_n(2).map(|i| i as u16)
811 /// Reads a little-endian `i64`.
813 /// `i64`s are 8 bytes long.
814 fn read_le_i64(&mut self) -> IoResult<i64> {
815 self.read_le_int_n(8)
818 /// Reads a little-endian `i32`.
820 /// `i32`s are 4 bytes long.
821 fn read_le_i32(&mut self) -> IoResult<i32> {
822 self.read_le_int_n(4).map(|i| i as i32)
825 /// Reads a little-endian `i16`.
827 /// `i16`s are 2 bytes long.
828 fn read_le_i16(&mut self) -> IoResult<i16> {
829 self.read_le_int_n(2).map(|i| i as i16)
832 /// Reads a little-endian `f64`.
834 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
835 fn read_le_f64(&mut self) -> IoResult<f64> {
836 self.read_le_u64().map(|i| unsafe {
837 transmute::<u64, f64>(i)
841 /// Reads a little-endian `f32`.
843 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
844 fn read_le_f32(&mut self) -> IoResult<f32> {
845 self.read_le_u32().map(|i| unsafe {
846 transmute::<u32, f32>(i)
852 /// `u8`s are 1 byte.
853 fn read_u8(&mut self) -> IoResult<u8> {
859 /// `i8`s are 1 byte.
860 fn read_i8(&mut self) -> IoResult<i8> {
861 self.read_byte().map(|i| i as i8)
865 /// A reader which can be converted to a RefReader.
866 #[deprecated = "use ByRefReader instead"]
867 pub trait AsRefReader {
868 /// Creates a wrapper around a mutable reference to the reader.
870 /// This is useful to allow applying adaptors while still
871 /// retaining ownership of the original value.
872 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
876 impl<T: Reader> AsRefReader for T {
877 fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
878 RefReader { inner: self }
882 /// A reader which can be converted to a RefReader.
883 pub trait ByRefReader {
884 /// Creates a wrapper around a mutable reference to the reader.
886 /// This is useful to allow applying adaptors while still
887 /// retaining ownership of the original value.
888 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
891 impl<T: Reader> ByRefReader for T {
892 fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
893 RefReader { inner: self }
897 /// A reader which can be converted to bytes.
898 pub trait BytesReader {
899 /// Create an iterator that reads a single byte on
900 /// each iteration, until EOF.
904 /// Any error other than `EndOfFile` that is produced by the underlying Reader
905 /// is returned by the iterator and should be handled by the caller.
906 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self>;
909 impl<T: Reader> BytesReader for T {
910 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, T> {
911 extensions::Bytes::new(self)
915 impl<'a> Reader for Box<Reader+'a> {
916 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
917 let reader: &mut Reader = &mut **self;
922 impl<'a> Reader for &'a mut (Reader+'a) {
923 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (*self).read(buf) }
926 /// Returns a slice of `v` between `start` and `end`.
928 /// Similar to `slice()` except this function only bounds the slice on the
929 /// capacity of `v`, not the length.
933 /// Panics when `start` or `end` point outside the capacity of `v`, or when
935 // Private function here because we aren't sure if we want to expose this as
936 // API yet. If so, it should be a method on Vec.
937 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
941 assert!(start <= end);
942 assert!(end <= v.capacity());
944 data: v.as_ptr().offset(start as int),
949 /// A `RefReader` is a struct implementing `Reader` which contains a reference
950 /// to another reader. This is often useful when composing streams.
956 /// # fn process_input<R: Reader>(r: R) {}
959 /// use std::io::ByRefReader;
960 /// use std::io::util::LimitReader;
962 /// let mut stream = io::stdin();
964 /// // Only allow the function to process at most one kilobyte of input
966 /// let stream = LimitReader::new(stream.by_ref(), 1024);
967 /// process_input(stream);
970 /// // 'stream' is still available for use here
974 pub struct RefReader<'a, R:'a> {
975 /// The underlying reader which this is referencing
979 impl<'a, R: Reader> Reader for RefReader<'a, R> {
980 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
983 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
984 fn fill_buf(&mut self) -> IoResult<&[u8]> { self.inner.fill_buf() }
985 fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
988 fn extend_sign(val: u64, nbytes: uint) -> i64 {
989 let shift = (8 - nbytes) * 8;
990 (val << shift) as i64 >> shift
993 /// A trait for objects which are byte-oriented streams. Writers are defined by
994 /// one method, `write`. This function will block until the provided buffer of
995 /// bytes has been entirely written, and it will return any failures which occur.
997 /// Another commonly overridden method is the `flush` method for writers such as
998 /// buffered writers.
1000 /// Writers are intended to be composable with one another. Many objects
1001 /// throughout the I/O and related libraries take and provide types which
1002 /// implement the `Writer` trait.
1004 /// Write the entirety of a given buffer
1008 /// If an error happens during the I/O operation, the error is returned as
1009 /// `Err`. Note that it is considered an error if the entire buffer could
1010 /// not be written, and if an error is returned then it is unknown how much
1011 /// data (if any) was actually written.
1012 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
1014 /// Flush this output stream, ensuring that all intermediately buffered
1015 /// contents reach their destination.
1017 /// This is by default a no-op and implementers of the `Writer` trait should
1018 /// decide whether their stream needs to be buffered or not.
1019 fn flush(&mut self) -> IoResult<()> { Ok(()) }
1021 /// Writes a formatted string into this writer, returning any error
1024 /// This method is primarily used to interface with the `format_args!`
1025 /// macro, but it is rare that this should explicitly be called. The
1026 /// `write!` macro should be favored to invoke this method instead.
1030 /// This function will return any I/O error reported while formatting.
1031 fn write_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
1032 // Create a shim which translates a Writer to a fmt::Writer and saves
1033 // off I/O errors. instead of discarding them
1034 struct Adaptor<'a, Sized? T:'a> {
1036 error: IoResult<()>,
1039 impl<'a, Sized? T: Writer> fmt::Writer for Adaptor<'a, T> {
1040 fn write_str(&mut self, s: &str) -> fmt::Result {
1041 match self.inner.write(s.as_bytes()) {
1044 self.error = Err(e);
1051 let mut output = Adaptor { inner: self, error: Ok(()) };
1052 match fmt::write(&mut output, fmt) {
1054 Err(..) => output.error
1059 /// Write a rust string into this sink.
1061 /// The bytes written will be the UTF-8 encoded version of the input string.
1062 /// If other encodings are desired, it is recommended to compose this stream
1063 /// with another performing the conversion, or to use `write` with a
1064 /// converted byte-array instead.
1066 fn write_str(&mut self, s: &str) -> IoResult<()> {
1067 self.write(s.as_bytes())
1070 /// Writes a string into this sink, and then writes a literal newline (`\n`)
1071 /// byte afterwards. Note that the writing of the newline is *not* atomic in
1072 /// the sense that the call to `write` is invoked twice (once with the
1073 /// string and once with a newline character).
1075 /// If other encodings or line ending flavors are desired, it is recommended
1076 /// that the `write` method is used specifically instead.
1078 fn write_line(&mut self, s: &str) -> IoResult<()> {
1079 self.write_str(s).and_then(|()| self.write(&[b'\n']))
1082 /// Write a single char, encoded as UTF-8.
1084 fn write_char(&mut self, c: char) -> IoResult<()> {
1085 let mut buf = [0u8; 4];
1086 let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
1087 self.write(buf[..n])
1090 /// Write the result of passing n through `int::to_str_bytes`.
1092 fn write_int(&mut self, n: int) -> IoResult<()> {
1093 write!(self, "{}", n)
1096 /// Write the result of passing n through `uint::to_str_bytes`.
1098 fn write_uint(&mut self, n: uint) -> IoResult<()> {
1099 write!(self, "{}", n)
1102 /// Write a little-endian uint (number of bytes depends on system).
1104 fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1105 extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
1108 /// Write a little-endian int (number of bytes depends on system).
1110 fn write_le_int(&mut self, n: int) -> IoResult<()> {
1111 extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
1114 /// Write a big-endian uint (number of bytes depends on system).
1116 fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1117 extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
1120 /// Write a big-endian int (number of bytes depends on system).
1122 fn write_be_int(&mut self, n: int) -> IoResult<()> {
1123 extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
1126 /// Write a big-endian u64 (8 bytes).
1128 fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1129 extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
1132 /// Write a big-endian u32 (4 bytes).
1134 fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1135 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1138 /// Write a big-endian u16 (2 bytes).
1140 fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1141 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1144 /// Write a big-endian i64 (8 bytes).
1146 fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1147 extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1150 /// Write a big-endian i32 (4 bytes).
1152 fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1153 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1156 /// Write a big-endian i16 (2 bytes).
1158 fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1159 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1162 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1164 fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1166 self.write_be_u64(transmute(f))
1170 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1172 fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1174 self.write_be_u32(transmute(f))
1178 /// Write a little-endian u64 (8 bytes).
1180 fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1181 extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
1184 /// Write a little-endian u32 (4 bytes).
1186 fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1187 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1190 /// Write a little-endian u16 (2 bytes).
1192 fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1193 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1196 /// Write a little-endian i64 (8 bytes).
1198 fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1199 extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1202 /// Write a little-endian i32 (4 bytes).
1204 fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1205 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1208 /// Write a little-endian i16 (2 bytes).
1210 fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1211 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1214 /// Write a little-endian IEEE754 double-precision floating-point
1217 fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1219 self.write_le_u64(transmute(f))
1223 /// Write a little-endian IEEE754 single-precision floating-point
1226 fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1228 self.write_le_u32(transmute(f))
1232 /// Write a u8 (1 byte).
1234 fn write_u8(&mut self, n: u8) -> IoResult<()> {
1238 /// Write an i8 (1 byte).
1240 fn write_i8(&mut self, n: i8) -> IoResult<()> {
1241 self.write(&[n as u8])
1245 /// A writer which can be converted to a RefWriter.
1246 #[deprecated = "use ByRefWriter instead"]
1247 pub trait AsRefWriter {
1248 /// Creates a wrapper around a mutable reference to the writer.
1250 /// This is useful to allow applying wrappers while still
1251 /// retaining ownership of the original value.
1253 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1256 #[allow(deprecated)]
1257 impl<T: Writer> AsRefWriter for T {
1258 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1259 RefWriter { inner: self }
1263 /// A writer which can be converted to a RefWriter.
1264 pub trait ByRefWriter {
1265 /// Creates a wrapper around a mutable reference to the writer.
1267 /// This is useful to allow applying wrappers while still
1268 /// retaining ownership of the original value.
1270 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1273 impl<T: Writer> ByRefWriter for T {
1274 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1275 RefWriter { inner: self }
1279 impl<'a> Writer for Box<Writer+'a> {
1281 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
1282 (&mut **self).write(buf)
1286 fn flush(&mut self) -> IoResult<()> {
1287 (&mut **self).flush()
1291 impl<'a> Writer for &'a mut (Writer+'a) {
1293 fn write(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write(buf) }
1296 fn flush(&mut self) -> IoResult<()> { (**self).flush() }
1299 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1300 /// to another writer. This is often useful when composing streams.
1306 /// # fn process_input<R: Reader>(r: R) {}
1308 /// use std::io::util::TeeReader;
1309 /// use std::io::{stdin, ByRefWriter};
1311 /// let mut output = Vec::new();
1314 /// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1315 /// // handle to it in the outer scope
1316 /// let mut tee = TeeReader::new(stdin(), output.by_ref());
1317 /// process_input(tee);
1320 /// println!("input processed: {}", output);
1323 pub struct RefWriter<'a, W:'a> {
1324 /// The underlying writer which this is referencing
1328 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1330 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
1333 fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1337 /// A Stream is a readable and a writable object. Data written is typically
1338 /// received by the object which reads receive data from.
1339 pub trait Stream: Reader + Writer { }
1341 impl<T: Reader + Writer> Stream for T {}
1343 /// An iterator that reads a line on each iteration,
1344 /// until `.read_line()` encounters `EndOfFile`.
1346 /// # Notes about the Iteration Protocol
1348 /// The `Lines` may yield `None` and thus terminate
1349 /// an iteration, but continue to yield elements if iteration
1350 /// is attempted again.
1354 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1355 /// is returned by the iterator and should be handled by the caller.
1356 pub struct Lines<'r, T:'r> {
1360 impl<'r, T: Buffer> Iterator for Lines<'r, T> {
1361 type Item = IoResult<String>;
1363 fn next(&mut self) -> Option<IoResult<String>> {
1364 match self.buffer.read_line() {
1365 Ok(x) => Some(Ok(x)),
1366 Err(IoError { kind: EndOfFile, ..}) => None,
1367 Err(y) => Some(Err(y))
1372 /// An iterator that reads a utf8-encoded character on each iteration,
1373 /// until `.read_char()` encounters `EndOfFile`.
1375 /// # Notes about the Iteration Protocol
1377 /// The `Chars` may yield `None` and thus terminate
1378 /// an iteration, but continue to yield elements if iteration
1379 /// is attempted again.
1383 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1384 /// is returned by the iterator and should be handled by the caller.
1385 pub struct Chars<'r, T:'r> {
1389 impl<'r, T: Buffer> Iterator for Chars<'r, T> {
1390 type Item = IoResult<char>;
1392 fn next(&mut self) -> Option<IoResult<char>> {
1393 match self.buffer.read_char() {
1394 Ok(x) => Some(Ok(x)),
1395 Err(IoError { kind: EndOfFile, ..}) => None,
1396 Err(y) => Some(Err(y))
1401 /// A Buffer is a type of reader which has some form of internal buffering to
1402 /// allow certain kinds of reading operations to be more optimized than others.
1403 /// This type extends the `Reader` trait with a few methods that are not
1404 /// possible to reasonably implement with purely a read interface.
1405 pub trait Buffer: Reader {
1406 /// Fills the internal buffer of this object, returning the buffer contents.
1407 /// Note that none of the contents will be "read" in the sense that later
1408 /// calling `read` may return the same contents.
1410 /// The `consume` function must be called with the number of bytes that are
1411 /// consumed from this buffer returned to ensure that the bytes are never
1416 /// This function will return an I/O error if the underlying reader was
1417 /// read, but returned an error. Note that it is not an error to return a
1418 /// 0-length buffer.
1419 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1421 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1422 /// so they should no longer be returned in calls to `read`.
1423 fn consume(&mut self, amt: uint);
1425 /// Reads the next line of input, interpreted as a sequence of UTF-8
1426 /// encoded Unicode codepoints. If a newline is encountered, then the
1427 /// newline is contained in the returned string.
1432 /// use std::io::BufReader;
1434 /// let mut reader = BufReader::new(b"hello\nworld");
1435 /// assert_eq!("hello\n", &*reader.read_line().unwrap());
1440 /// This function has the same error semantics as `read_until`:
1442 /// * All non-EOF errors will be returned immediately
1443 /// * If an error is returned previously consumed bytes are lost
1444 /// * EOF is only returned if no bytes have been read
1445 /// * Reach EOF may mean that the delimiter is not present in the return
1448 /// Additionally, this function can fail if the line of input read is not a
1449 /// valid UTF-8 sequence of bytes.
1450 fn read_line(&mut self) -> IoResult<String> {
1451 self.read_until(b'\n').and_then(|line|
1452 match String::from_utf8(line) {
1454 Err(_) => Err(standard_error(InvalidInput)),
1459 /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1460 /// specified byte is encountered, reading ceases and the bytes up to and
1461 /// including the delimiter are returned.
1465 /// If any I/O error is encountered other than EOF, the error is immediately
1466 /// returned. Note that this may discard bytes which have already been read,
1467 /// and those bytes will *not* be returned. It is recommended to use other
1468 /// methods if this case is worrying.
1470 /// If EOF is encountered, then this function will return EOF if 0 bytes
1471 /// have been read, otherwise the pending byte buffer is returned. This
1472 /// is the reason that the byte buffer returned may not always contain the
1474 fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1475 let mut res = Vec::new();
1480 let available = match self.fill_buf() {
1482 Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1486 Err(e) => return Err(e)
1488 match available.iter().position(|&b| b == byte) {
1490 res.push_all(available[..i + 1]);
1495 res.push_all(available);
1496 used = available.len();
1506 /// Reads the next utf8-encoded character from the underlying stream.
1510 /// If an I/O error occurs, or EOF, then this function will return `Err`.
1511 /// This function will also return error if the stream does not contain a
1512 /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1513 fn read_char(&mut self) -> IoResult<char> {
1514 let first_byte = try!(self.read_byte());
1515 let width = unicode::str::utf8_char_width(first_byte);
1516 if width == 1 { return Ok(first_byte as char) }
1517 if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1518 let mut buf = [first_byte, 0, 0, 0];
1521 while start < width {
1522 match try!(self.read(buf.slice_mut(start, width))) {
1523 n if n == width - start => break,
1524 n if n < width - start => { start += n; }
1525 _ => return Err(standard_error(InvalidInput)),
1529 match str::from_utf8(buf[..width]).ok() {
1530 Some(s) => Ok(s.char_at(0)),
1531 None => Err(standard_error(InvalidInput))
1536 /// Extension methods for the Buffer trait which are included in the prelude.
1537 pub trait BufferPrelude {
1538 /// Create an iterator that reads a utf8-encoded character on each iteration
1543 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1544 /// is returned by the iterator and should be handled by the caller.
1545 fn chars<'r>(&'r mut self) -> Chars<'r, Self>;
1547 /// Create an iterator that reads a line on each iteration until EOF.
1551 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1552 /// is returned by the iterator and should be handled by the caller.
1553 fn lines<'r>(&'r mut self) -> Lines<'r, Self>;
1556 impl<T: Buffer> BufferPrelude for T {
1557 fn chars<'r>(&'r mut self) -> Chars<'r, T> {
1558 Chars { buffer: self }
1561 fn lines<'r>(&'r mut self) -> Lines<'r, T> {
1562 Lines { buffer: self }
1566 /// When seeking, the resulting cursor is offset from a base by the offset given
1567 /// to the `seek` function. The base used is specified by this enumeration.
1569 pub enum SeekStyle {
1570 /// Seek from the beginning of the stream
1572 /// Seek from the end of the stream
1574 /// Seek from the current position
1578 /// An object implementing `Seek` internally has some form of cursor which can
1579 /// be moved within a stream of bytes. The stream typically has a fixed size,
1580 /// allowing seeking relative to either end.
1582 /// Return position of file cursor in the stream
1583 fn tell(&self) -> IoResult<u64>;
1585 /// Seek to an offset in a stream
1587 /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1588 /// allowed, but seeking before position 0 is not allowed.
1592 /// * Seeking to a negative offset is considered an error
1593 /// * Seeking past the end of the stream does not modify the underlying
1594 /// stream, but the next write may cause the previous data to be filled in
1595 /// with a bit pattern.
1596 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1599 /// A listener is a value that can consume itself to start listening for
1602 /// Doing so produces some sort of Acceptor.
1603 pub trait Listener<T, A: Acceptor<T>> {
1604 /// Spin up the listener and start queuing incoming connections
1608 /// Returns `Err` if this listener could not be bound to listen for
1609 /// connections. In all cases, this listener is consumed.
1610 fn listen(self) -> IoResult<A>;
1613 /// An acceptor is a value that presents incoming connections
1614 pub trait Acceptor<T> {
1615 /// Wait for and accept an incoming connection
1619 /// Returns `Err` if an I/O error is encountered.
1620 fn accept(&mut self) -> IoResult<T>;
1622 /// Create an iterator over incoming connection attempts.
1624 /// Note that I/O errors will be yielded by the iterator itself.
1625 fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1626 IncomingConnections { inc: self }
1630 /// An infinite iterator over incoming connection attempts.
1631 /// Calling `next` will block the task until a connection is attempted.
1633 /// Since connection attempts can continue forever, this iterator always returns
1634 /// `Some`. The `Some` contains the `IoResult` representing whether the
1635 /// connection attempt was successful. A successful connection will be wrapped
1636 /// in `Ok`. A failed connection is represented as an `Err`.
1637 pub struct IncomingConnections<'a, Sized? A:'a> {
1641 impl<'a, T, Sized? A: Acceptor<T>> Iterator for IncomingConnections<'a, A> {
1642 type Item = IoResult<T>;
1644 fn next(&mut self) -> Option<IoResult<T>> {
1645 Some(self.inc.accept())
1649 /// Creates a standard error for a commonly used flavor of error. The `detail`
1650 /// field of the returned error will always be `None`.
1657 /// let eof = io::standard_error(io::EndOfFile);
1658 /// let einval = io::standard_error(io::InvalidInput);
1660 pub fn standard_error(kind: IoErrorKind) -> IoError {
1661 let desc = match kind {
1662 EndOfFile => "end of file",
1663 IoUnavailable => "I/O is unavailable",
1664 InvalidInput => "invalid input",
1665 OtherIoError => "unknown I/O error",
1666 FileNotFound => "file not found",
1667 PermissionDenied => "permission denied",
1668 ConnectionFailed => "connection failed",
1669 Closed => "stream is closed",
1670 ConnectionRefused => "connection refused",
1671 ConnectionReset => "connection reset",
1672 ConnectionAborted => "connection aborted",
1673 NotConnected => "not connected",
1674 BrokenPipe => "broken pipe",
1675 PathAlreadyExists => "file already exists",
1676 PathDoesntExist => "no such file",
1677 MismatchedFileTypeForOperation => "mismatched file type",
1678 ResourceUnavailable => "resource unavailable",
1679 TimedOut => "operation timed out",
1680 ShortWrite(..) => "short write",
1681 NoProgress => "no progress",
1690 /// A mode specifies how a file should be opened or created. These modes are
1691 /// passed to `File::open_mode` and are used to control where the file is
1692 /// positioned when it is initially opened.
1693 #[deriving(Copy, Clone, PartialEq, Eq)]
1695 /// Opens a file positioned at the beginning.
1697 /// Opens a file positioned at EOF.
1699 /// Opens a file, truncating it if it already exists.
1703 /// Access permissions with which the file should be opened. `File`s
1704 /// opened with `Read` will return an error if written to.
1705 #[deriving(Copy, Clone, PartialEq, Eq)]
1706 pub enum FileAccess {
1707 /// Read-only access, requests to write will result in an error
1709 /// Write-only access, requests to read will result in an error
1711 /// Read-write access, no requests are denied by default
1715 /// Different kinds of files which can be identified by a call to stat
1716 #[deriving(Copy, PartialEq, Show, Hash, Clone)]
1718 /// This is a normal file, corresponding to `S_IFREG`
1721 /// This file is a directory, corresponding to `S_IFDIR`
1724 /// This file is a named pipe, corresponding to `S_IFIFO`
1727 /// This file is a block device, corresponding to `S_IFBLK`
1730 /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1733 /// The type of this file is not recognized as one of the other categories
1737 /// A structure used to describe metadata information about a file. This
1738 /// structure is created through the `stat` method on a `Path`.
1743 /// # use std::io::fs::PathExtensions;
1746 /// let info = match Path::new("foo.txt").stat() {
1747 /// Ok(stat) => stat,
1748 /// Err(e) => panic!("couldn't read foo.txt: {}", e),
1751 /// println!("byte size: {}", info.size);
1754 #[deriving(Copy, Hash)]
1755 pub struct FileStat {
1756 /// The size of the file, in bytes
1758 /// The kind of file this path points to (directory, file, pipe, etc.)
1760 /// The file permissions currently on the file
1761 pub perm: FilePermission,
1763 // FIXME(#10301): These time fields are pretty useless without an actual
1764 // time representation, what are the milliseconds relative
1767 /// The time that the file was created at, in platform-dependent
1770 /// The time that this file was last modified, in platform-dependent
1773 /// The time that this file was last accessed, in platform-dependent
1777 /// Information returned by stat() which is not guaranteed to be
1778 /// platform-independent. This information may be useful on some platforms,
1779 /// but it may have different meanings or no meaning at all on other
1782 /// Usage of this field is discouraged, but if access is desired then the
1783 /// fields are located here.
1785 pub unstable: UnstableFileStat,
1788 /// This structure represents all of the possible information which can be
1789 /// returned from a `stat` syscall which is not contained in the `FileStat`
1790 /// structure. This information is not necessarily platform independent, and may
1791 /// have different meanings or no meaning at all on some platforms.
1793 #[deriving(Copy, Hash)]
1794 pub struct UnstableFileStat {
1795 /// The ID of the device containing the file.
1797 /// The file serial number.
1801 /// The number of hard links to this file.
1803 /// The user ID of the file.
1805 /// The group ID of the file.
1807 /// The optimal block size for I/O.
1809 /// The blocks allocated for this file.
1811 /// User-defined flags for the file.
1813 /// The file generation number.
1818 #[doc = "A set of permissions for a file or directory is represented"]
1819 #[doc = "by a set of flags which are or'd together."]
1820 flags FilePermission: u32 {
1821 const USER_READ = 0o400,
1822 const USER_WRITE = 0o200,
1823 const USER_EXECUTE = 0o100,
1824 const GROUP_READ = 0o040,
1825 const GROUP_WRITE = 0o020,
1826 const GROUP_EXECUTE = 0o010,
1827 const OTHER_READ = 0o004,
1828 const OTHER_WRITE = 0o002,
1829 const OTHER_EXECUTE = 0o001,
1831 const USER_RWX = USER_READ.bits | USER_WRITE.bits | USER_EXECUTE.bits,
1832 const GROUP_RWX = GROUP_READ.bits | GROUP_WRITE.bits | GROUP_EXECUTE.bits,
1833 const OTHER_RWX = OTHER_READ.bits | OTHER_WRITE.bits | OTHER_EXECUTE.bits,
1835 #[doc = "Permissions for user owned files, equivalent to 0644 on"]
1836 #[doc = "unix-like systems."]
1837 const USER_FILE = USER_READ.bits | USER_WRITE.bits | GROUP_READ.bits | OTHER_READ.bits,
1839 #[doc = "Permissions for user owned directories, equivalent to 0755 on"]
1840 #[doc = "unix-like systems."]
1841 const USER_DIR = USER_RWX.bits | GROUP_READ.bits | GROUP_EXECUTE.bits |
1842 OTHER_READ.bits | OTHER_EXECUTE.bits,
1844 #[doc = "Permissions for user owned executables, equivalent to 0755"]
1845 #[doc = "on unix-like systems."]
1846 const USER_EXEC = USER_DIR.bits,
1848 #[doc = "All possible permissions enabled."]
1849 const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
1852 #[allow(non_upper_case_globals)]
1853 #[deprecated = "use USER_READ instead"]
1854 const UserRead = USER_READ.bits,
1855 #[allow(non_upper_case_globals)]
1856 #[deprecated = "use USER_WRITE instead"]
1857 const UserWrite = USER_WRITE.bits,
1858 #[allow(non_upper_case_globals)]
1859 #[deprecated = "use USER_EXECUTE instead"]
1860 const UserExecute = USER_EXECUTE.bits,
1861 #[allow(non_upper_case_globals)]
1862 #[deprecated = "use GROUP_READ instead"]
1863 const GroupRead = GROUP_READ.bits,
1864 #[allow(non_upper_case_globals)]
1865 #[deprecated = "use GROUP_WRITE instead"]
1866 const GroupWrite = GROUP_WRITE.bits,
1867 #[allow(non_upper_case_globals)]
1868 #[deprecated = "use GROUP_EXECUTE instead"]
1869 const GroupExecute = GROUP_EXECUTE.bits,
1870 #[allow(non_upper_case_globals)]
1871 #[deprecated = "use OTHER_READ instead"]
1872 const OtherRead = OTHER_READ.bits,
1873 #[allow(non_upper_case_globals)]
1874 #[deprecated = "use OTHER_WRITE instead"]
1875 const OtherWrite = OTHER_WRITE.bits,
1876 #[allow(non_upper_case_globals)]
1877 #[deprecated = "use OTHER_EXECUTE instead"]
1878 const OtherExecute = OTHER_EXECUTE.bits,
1880 #[allow(non_upper_case_globals)]
1881 #[deprecated = "use USER_RWX instead"]
1882 const UserRWX = USER_RWX.bits,
1883 #[allow(non_upper_case_globals)]
1884 #[deprecated = "use GROUP_RWX instead"]
1885 const GroupRWX = GROUP_RWX.bits,
1886 #[allow(non_upper_case_globals)]
1887 #[deprecated = "use OTHER_RWX instead"]
1888 const OtherRWX = OTHER_RWX.bits,
1890 #[doc = "Deprecated: use `USER_FILE` instead."]
1891 #[allow(non_upper_case_globals)]
1892 #[deprecated = "use USER_FILE instead"]
1893 const UserFile = USER_FILE.bits,
1895 #[doc = "Deprecated: use `USER_DIR` instead."]
1896 #[allow(non_upper_case_globals)]
1897 #[deprecated = "use USER_DIR instead"]
1898 const UserDir = USER_DIR.bits,
1899 #[doc = "Deprecated: use `USER_EXEC` instead."]
1900 #[allow(non_upper_case_globals)]
1901 #[deprecated = "use USER_EXEC instead"]
1902 const UserExec = USER_EXEC.bits,
1904 #[doc = "Deprecated: use `ALL_PERMISSIONS` instead"]
1905 #[allow(non_upper_case_globals)]
1906 #[deprecated = "use ALL_PERMISSIONS instead"]
1907 const AllPermissions = ALL_PERMISSIONS.bits,
1913 impl Default for FilePermission {
1916 fn default() -> FilePermission { FilePermission::empty() }
1919 impl fmt::Show for FilePermission {
1920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1921 write!(f, "{:04o}", self.bits)
1927 use self::BadReaderBehavior::*;
1928 use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
1929 use prelude::v1::{Ok, Vec, Buffer, SliceExt};
1932 #[deriving(Clone, PartialEq, Show)]
1933 enum BadReaderBehavior {
1938 struct BadReader<T> {
1940 behavior: Vec<BadReaderBehavior>,
1943 impl<T: Reader> BadReader<T> {
1944 fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1945 BadReader { behavior: behavior, r: r }
1949 impl<T: Reader> Reader for BadReader<T> {
1950 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1951 let BadReader { ref mut behavior, ref mut r } = *self;
1953 if behavior.is_empty() {
1954 // fall back on good
1957 match behavior.as_mut_slice()[0] {
1958 GoodBehavior(0) => (),
1959 GoodBehavior(ref mut x) => {
1963 BadBehavior(0) => (),
1964 BadBehavior(ref mut x) => {
1975 fn test_read_at_least() {
1976 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1977 vec![GoodBehavior(uint::MAX)]);
1978 let buf = &mut [0u8; 5];
1979 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1980 assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1981 assert!(r.read_at_least(0, buf).is_ok());
1983 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1984 vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
1985 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1987 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1988 vec![BadBehavior(1), GoodBehavior(1),
1989 BadBehavior(50), GoodBehavior(uint::MAX)]);
1990 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1991 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1993 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1994 vec![BadBehavior(uint::MAX)]);
1995 assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1997 let mut r = MemReader::new(b"hello, world!".to_vec());
1998 assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1999 assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
2003 fn test_push_at_least() {
2004 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
2005 vec![GoodBehavior(uint::MAX)]);
2006 let mut buf = Vec::new();
2007 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
2008 assert!(r.push_at_least(0, 5, &mut buf).is_ok());
2010 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
2011 vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
2012 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
2014 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
2015 vec![BadBehavior(1), GoodBehavior(1),
2016 BadBehavior(50), GoodBehavior(uint::MAX)]);
2017 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
2018 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
2020 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
2021 vec![BadBehavior(uint::MAX)]);
2022 assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
2024 let mut r = MemReader::new(b"hello, world!".to_vec());
2025 assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
2032 assert_eq!(format!("{}", USER_READ), "0400");
2033 assert_eq!(format!("{}", USER_FILE), "0644");
2034 assert_eq!(format!("{}", USER_EXEC), "0755");
2035 assert_eq!(format!("{}", USER_RWX), "0700");
2036 assert_eq!(format!("{}", GROUP_RWX), "0070");
2037 assert_eq!(format!("{}", OTHER_RWX), "0007");
2038 assert_eq!(format!("{}", ALL_PERMISSIONS), "0777");
2039 assert_eq!(format!("{}", USER_READ | USER_WRITE | OTHER_WRITE), "0602");
2042 fn _ensure_buffer_is_object_safe<T: Buffer>(x: &T) -> &Buffer {