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::pipe::PipeStream;
267 pub use self::process::{Process, Command};
268 pub use self::tempfile::TempDir;
270 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
271 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
273 pub use self::comm_adapters::{ChanReader, ChanWriter};
290 /// The default buffer size for various I/O operations
291 // libuv recommends 64k buffers to maximize throughput
292 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
293 const DEFAULT_BUF_SIZE: uint = 1024 * 64;
295 /// A convenient typedef of the return value of any I/O action.
296 pub type IoResult<T> = Result<T, IoError>;
298 /// The type passed to I/O condition handlers to indicate error
302 /// Is something like this sufficient? It's kind of archaic
303 #[derive(PartialEq, Eq, Clone)]
305 /// An enumeration which can be matched against for determining the flavor
307 pub kind: IoErrorKind,
308 /// A human-readable description about the error
309 pub desc: &'static str,
310 /// Detailed information about this error, not always available
311 pub detail: Option<String>
315 /// Convert an `errno` value into an `IoError`.
317 /// If `detail` is `true`, the `detail` field of the `IoError`
318 /// struct is filled with an allocated string describing the error
319 /// in more detail, retrieved from the operating system.
320 pub fn from_errno(errno: uint, detail: bool) -> IoError {
321 let mut err = sys::decode_error(errno as i32);
322 if detail && err.kind == OtherIoError {
323 err.detail = Some(os::error_string(errno).chars()
324 .map(|c| c.to_lowercase()).collect())
329 /// Retrieve the last error to occur as a (detailed) IoError.
331 /// This uses the OS `errno`, and so there should not be any task
332 /// descheduling or migration (other than that performed by the
333 /// operating system) between the call(s) for which errors are
334 /// being checked and the call of this function.
335 pub fn last_error() -> IoError {
336 IoError::from_errno(os::errno() as uint, true)
340 impl fmt::Show for IoError {
341 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
343 IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
344 write!(fmt, "{}", detail),
345 IoError { detail: None, desc, .. } =>
346 write!(fmt, "{}", desc),
347 IoError { detail: Some(ref detail), desc, .. } =>
348 write!(fmt, "{} ({})", desc, detail)
353 impl Error for IoError {
354 fn description(&self) -> &str {
358 fn detail(&self) -> Option<String> {
363 impl FromError<IoError> for Box<Error> {
364 fn from_error(err: IoError) -> Box<Error> {
369 /// A list specifying general categories of I/O error.
370 #[derive(Copy, PartialEq, Eq, Clone, Show)]
371 pub enum IoErrorKind {
372 /// Any I/O error not part of this list.
374 /// The operation could not complete because end of file was reached.
376 /// The file was not found.
378 /// The file permissions disallowed access to this file.
380 /// A network connection failed for some reason not specified in this list.
382 /// The network operation failed because the network connection was closed.
384 /// The connection was refused by the remote server.
386 /// The connection was reset by the remote server.
388 /// The connection was aborted (terminated) by the remote server.
390 /// The network operation failed because it was not connected yet.
392 /// The operation failed because a pipe was closed.
394 /// A file already existed with that name.
396 /// No file exists at that location.
398 /// The path did not specify the type of file that this operation required. For example,
399 /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
400 MismatchedFileTypeForOperation,
401 /// The operation temporarily failed (for example, because a signal was received), and retrying
404 /// No I/O functionality is available for this task.
406 /// A parameter was incorrect in a way that caused an I/O error not part of this list.
408 /// The I/O operation's timeout expired, causing it to be canceled.
410 /// This write operation failed to write all of its data.
412 /// Normally the write() method on a Writer guarantees that all of its data
413 /// has been written, but some operations may be terminated after only
414 /// partially writing some data. An example of this is a timed out write
415 /// which successfully wrote a known number of bytes, but bailed out after
418 /// The payload contained as part of this variant is the number of bytes
419 /// which are known to have been successfully written.
421 /// The Reader returned 0 bytes from `read()` too many times.
425 /// A trait that lets you add a `detail` to an IoError easily
426 trait UpdateIoError<T> {
427 /// Returns an IoError with updated description and detail
428 fn update_err<D>(self, desc: &'static str, detail: D) -> Self where
429 D: FnOnce(&IoError) -> String;
431 /// Returns an IoError with updated detail
432 fn update_detail<D>(self, detail: D) -> Self where
433 D: FnOnce(&IoError) -> String;
435 /// Returns an IoError with update description
436 fn update_desc(self, desc: &'static str) -> Self;
439 impl<T> UpdateIoError<T> for IoResult<T> {
440 fn update_err<D>(self, desc: &'static str, detail: D) -> IoResult<T> where
441 D: FnOnce(&IoError) -> String,
443 self.map_err(move |mut e| {
444 let detail = detail(&e);
446 e.detail = Some(detail);
451 fn update_detail<D>(self, detail: D) -> IoResult<T> where
452 D: FnOnce(&IoError) -> String,
454 self.map_err(move |mut e| { e.detail = Some(detail(&e)); e })
457 fn update_desc(self, desc: &'static str) -> IoResult<T> {
458 self.map_err(|mut e| { e.desc = desc; e })
462 static NO_PROGRESS_LIMIT: uint = 1000;
464 /// A trait for objects which are byte-oriented streams. Readers are defined by
465 /// one method, `read`. This function will block until data is available,
466 /// filling in the provided buffer with any data read.
468 /// Readers are intended to be composable with one another. Many objects
469 /// throughout the I/O and related libraries take and provide types which
470 /// implement the `Reader` trait.
473 // Only method which need to get implemented for this trait
475 /// Read bytes, up to the length of `buf` and place them in `buf`.
476 /// Returns the number of bytes read. The number of bytes read may
477 /// be less than the number requested, even 0. Returns `Err` on EOF.
481 /// If an error occurs during this I/O operation, then it is returned as
482 /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
483 /// inspected for in the error's `kind` field. Also note that reading 0
484 /// bytes is not considered an error in all circumstances
486 /// # Implementation Note
488 /// When implementing this method on a new Reader, you are strongly encouraged
489 /// not to return 0 if you can avoid it.
490 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
492 // Convenient helper methods based on the above methods
494 /// Reads at least `min` bytes and places them in `buf`.
495 /// Returns the number of bytes read.
497 /// This will continue to call `read` until at least `min` bytes have been
498 /// read. If `read` returns 0 too many times, `NoProgress` will be
503 /// If an error occurs at any point, that error is returned, and no further
505 fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
508 detail: Some(String::from_str("the buffer is too short")),
509 ..standard_error(InvalidInput)
516 match self.read(buf.slice_from_mut(read)) {
519 if zeroes >= NO_PROGRESS_LIMIT {
520 return Err(standard_error(NoProgress));
527 err@Err(_) => return err
534 /// Reads a single byte. Returns `Err` on EOF.
535 fn read_byte(&mut self) -> IoResult<u8> {
537 try!(self.read_at_least(1, &mut buf));
541 /// Reads up to `len` bytes and appends them to a vector.
542 /// Returns the number of bytes read. The number of bytes read may be
543 /// less than the number requested, even 0. Returns Err on EOF.
547 /// If an error occurs during this I/O operation, then it is returned
548 /// as `Err(IoError)`. See `read()` for more details.
549 fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
550 let start_len = buf.len();
554 let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
557 unsafe { buf.set_len(start_len + n) };
561 /// Reads at least `min` bytes, but no more than `len`, and appends them to
563 /// Returns the number of bytes read.
565 /// This will continue to call `read` until at least `min` bytes have been
566 /// read. If `read` returns 0 too many times, `NoProgress` will be
571 /// If an error occurs at any point, that error is returned, and no further
573 fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
576 detail: Some(String::from_str("the buffer is too short")),
577 ..standard_error(InvalidInput)
581 let start_len = buf.len();
584 // we can't just use self.read_at_least(min, slice) because we need to push
585 // successful reads onto the vector before any returned errors.
590 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
591 try!(self.read_at_least(1, s))
593 unsafe { buf.set_len(start_len + read) };
598 /// Reads exactly `len` bytes and gives you back a new vector of length
603 /// Fails with the same conditions as `read`. Additionally returns error
604 /// on EOF. Note that if an error is returned, then some number of bytes may
605 /// have already been consumed from the underlying reader, and they are lost
606 /// (not returned as part of the error). If this is unacceptable, then it is
607 /// recommended to use the `push_at_least` or `read` methods.
608 fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
609 let mut buf = Vec::with_capacity(len);
610 match self.push_at_least(len, len, &mut buf) {
616 /// Reads all remaining bytes from the stream.
620 /// Returns any non-EOF error immediately. Previously read bytes are
621 /// discarded when an error is returned.
623 /// When EOF is encountered, all bytes read up to that point are returned.
624 fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
625 let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
627 match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
629 Err(ref e) if e.kind == EndOfFile => break,
630 Err(e) => return Err(e)
636 /// Reads all of the remaining bytes of this stream, interpreting them as a
637 /// UTF-8 encoded stream. The corresponding string is returned.
641 /// This function returns all of the same errors as `read_to_end` with an
642 /// additional error if the reader's contents are not a valid sequence of
644 fn read_to_string(&mut self) -> IoResult<String> {
645 self.read_to_end().and_then(|s| {
646 match String::from_utf8(s) {
648 Err(_) => Err(standard_error(InvalidInput)),
653 // Byte conversion helpers
655 /// Reads `n` little-endian unsigned integer bytes.
657 /// `n` must be between 1 and 8, inclusive.
658 fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
659 assert!(nbytes > 0 && nbytes <= 8);
665 val += (try!(self.read_u8()) as u64) << pos;
672 /// Reads `n` little-endian signed integer bytes.
674 /// `n` must be between 1 and 8, inclusive.
675 fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
676 self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
679 /// Reads `n` big-endian unsigned integer bytes.
681 /// `n` must be between 1 and 8, inclusive.
682 fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
683 assert!(nbytes > 0 && nbytes <= 8);
689 val += (try!(self.read_u8()) as u64) << i * 8;
694 /// Reads `n` big-endian signed integer bytes.
696 /// `n` must be between 1 and 8, inclusive.
697 fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
698 self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
701 /// Reads a little-endian unsigned integer.
703 /// The number of bytes returned is system-dependent.
704 fn read_le_uint(&mut self) -> IoResult<uint> {
705 self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
708 /// Reads a little-endian integer.
710 /// The number of bytes returned is system-dependent.
711 fn read_le_int(&mut self) -> IoResult<int> {
712 self.read_le_int_n(int::BYTES).map(|i| i as int)
715 /// Reads a big-endian unsigned integer.
717 /// The number of bytes returned is system-dependent.
718 fn read_be_uint(&mut self) -> IoResult<uint> {
719 self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
722 /// Reads a big-endian integer.
724 /// The number of bytes returned is system-dependent.
725 fn read_be_int(&mut self) -> IoResult<int> {
726 self.read_be_int_n(int::BYTES).map(|i| i as int)
729 /// Reads a big-endian `u64`.
731 /// `u64`s are 8 bytes long.
732 fn read_be_u64(&mut self) -> IoResult<u64> {
733 self.read_be_uint_n(8)
736 /// Reads a big-endian `u32`.
738 /// `u32`s are 4 bytes long.
739 fn read_be_u32(&mut self) -> IoResult<u32> {
740 self.read_be_uint_n(4).map(|i| i as u32)
743 /// Reads a big-endian `u16`.
745 /// `u16`s are 2 bytes long.
746 fn read_be_u16(&mut self) -> IoResult<u16> {
747 self.read_be_uint_n(2).map(|i| i as u16)
750 /// Reads a big-endian `i64`.
752 /// `i64`s are 8 bytes long.
753 fn read_be_i64(&mut self) -> IoResult<i64> {
754 self.read_be_int_n(8)
757 /// Reads a big-endian `i32`.
759 /// `i32`s are 4 bytes long.
760 fn read_be_i32(&mut self) -> IoResult<i32> {
761 self.read_be_int_n(4).map(|i| i as i32)
764 /// Reads a big-endian `i16`.
766 /// `i16`s are 2 bytes long.
767 fn read_be_i16(&mut self) -> IoResult<i16> {
768 self.read_be_int_n(2).map(|i| i as i16)
771 /// Reads a big-endian `f64`.
773 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
774 fn read_be_f64(&mut self) -> IoResult<f64> {
775 self.read_be_u64().map(|i| unsafe {
776 transmute::<u64, f64>(i)
780 /// Reads a big-endian `f32`.
782 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
783 fn read_be_f32(&mut self) -> IoResult<f32> {
784 self.read_be_u32().map(|i| unsafe {
785 transmute::<u32, f32>(i)
789 /// Reads a little-endian `u64`.
791 /// `u64`s are 8 bytes long.
792 fn read_le_u64(&mut self) -> IoResult<u64> {
793 self.read_le_uint_n(8)
796 /// Reads a little-endian `u32`.
798 /// `u32`s are 4 bytes long.
799 fn read_le_u32(&mut self) -> IoResult<u32> {
800 self.read_le_uint_n(4).map(|i| i as u32)
803 /// Reads a little-endian `u16`.
805 /// `u16`s are 2 bytes long.
806 fn read_le_u16(&mut self) -> IoResult<u16> {
807 self.read_le_uint_n(2).map(|i| i as u16)
810 /// Reads a little-endian `i64`.
812 /// `i64`s are 8 bytes long.
813 fn read_le_i64(&mut self) -> IoResult<i64> {
814 self.read_le_int_n(8)
817 /// Reads a little-endian `i32`.
819 /// `i32`s are 4 bytes long.
820 fn read_le_i32(&mut self) -> IoResult<i32> {
821 self.read_le_int_n(4).map(|i| i as i32)
824 /// Reads a little-endian `i16`.
826 /// `i16`s are 2 bytes long.
827 fn read_le_i16(&mut self) -> IoResult<i16> {
828 self.read_le_int_n(2).map(|i| i as i16)
831 /// Reads a little-endian `f64`.
833 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
834 fn read_le_f64(&mut self) -> IoResult<f64> {
835 self.read_le_u64().map(|i| unsafe {
836 transmute::<u64, f64>(i)
840 /// Reads a little-endian `f32`.
842 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
843 fn read_le_f32(&mut self) -> IoResult<f32> {
844 self.read_le_u32().map(|i| unsafe {
845 transmute::<u32, f32>(i)
851 /// `u8`s are 1 byte.
852 fn read_u8(&mut self) -> IoResult<u8> {
858 /// `i8`s are 1 byte.
859 fn read_i8(&mut self) -> IoResult<i8> {
860 self.read_byte().map(|i| i as i8)
864 /// A reader which can be converted to a RefReader.
865 pub trait ByRefReader {
866 /// Creates a wrapper around a mutable reference to the reader.
868 /// This is useful to allow applying adaptors while still
869 /// retaining ownership of the original value.
870 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
873 impl<T: Reader> ByRefReader for T {
874 fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
875 RefReader { inner: self }
879 /// A reader which can be converted to bytes.
880 pub trait BytesReader {
881 /// Create an iterator that reads a single byte on
882 /// each iteration, until EOF.
886 /// Any error other than `EndOfFile` that is produced by the underlying Reader
887 /// is returned by the iterator and should be handled by the caller.
888 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self>;
891 impl<T: Reader> BytesReader for T {
892 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, T> {
893 extensions::Bytes::new(self)
897 impl<'a> Reader for Box<Reader+'a> {
898 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
899 let reader: &mut Reader = &mut **self;
904 impl<'a> Reader for &'a mut (Reader+'a) {
905 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (*self).read(buf) }
908 /// Returns a slice of `v` between `start` and `end`.
910 /// Similar to `slice()` except this function only bounds the slice on the
911 /// capacity of `v`, not the length.
915 /// Panics when `start` or `end` point outside the capacity of `v`, or when
917 // Private function here because we aren't sure if we want to expose this as
918 // API yet. If so, it should be a method on Vec.
919 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
923 assert!(start <= end);
924 assert!(end <= v.capacity());
926 data: v.as_ptr().offset(start as int),
931 /// A `RefReader` is a struct implementing `Reader` which contains a reference
932 /// to another reader. This is often useful when composing streams.
938 /// # fn process_input<R: Reader>(r: R) {}
941 /// use std::io::ByRefReader;
942 /// use std::io::util::LimitReader;
944 /// let mut stream = io::stdin();
946 /// // Only allow the function to process at most one kilobyte of input
948 /// let stream = LimitReader::new(stream.by_ref(), 1024);
949 /// process_input(stream);
952 /// // 'stream' is still available for use here
956 pub struct RefReader<'a, R:'a> {
957 /// The underlying reader which this is referencing
961 impl<'a, R: Reader> Reader for RefReader<'a, R> {
962 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
965 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
966 fn fill_buf(&mut self) -> IoResult<&[u8]> { self.inner.fill_buf() }
967 fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
970 fn extend_sign(val: u64, nbytes: uint) -> i64 {
971 let shift = (8 - nbytes) * 8;
972 (val << shift) as i64 >> shift
975 /// A trait for objects which are byte-oriented streams. Writers are defined by
976 /// one method, `write`. This function will block until the provided buffer of
977 /// bytes has been entirely written, and it will return any failures which occur.
979 /// Another commonly overridden method is the `flush` method for writers such as
980 /// buffered writers.
982 /// Writers are intended to be composable with one another. Many objects
983 /// throughout the I/O and related libraries take and provide types which
984 /// implement the `Writer` trait.
986 /// Write the entirety of a given buffer
990 /// If an error happens during the I/O operation, the error is returned as
991 /// `Err`. Note that it is considered an error if the entire buffer could
992 /// not be written, and if an error is returned then it is unknown how much
993 /// data (if any) was actually written.
994 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
996 /// Flush this output stream, ensuring that all intermediately buffered
997 /// contents reach their destination.
999 /// This is by default a no-op and implementers of the `Writer` trait should
1000 /// decide whether their stream needs to be buffered or not.
1001 fn flush(&mut self) -> IoResult<()> { Ok(()) }
1003 /// Writes a formatted string into this writer, returning any error
1006 /// This method is primarily used to interface with the `format_args!`
1007 /// macro, but it is rare that this should explicitly be called. The
1008 /// `write!` macro should be favored to invoke this method instead.
1012 /// This function will return any I/O error reported while formatting.
1013 fn write_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
1014 // Create a shim which translates a Writer to a fmt::Writer and saves
1015 // off I/O errors. instead of discarding them
1016 struct Adaptor<'a, Sized? T:'a> {
1018 error: IoResult<()>,
1021 impl<'a, Sized? T: Writer> fmt::Writer for Adaptor<'a, T> {
1022 fn write_str(&mut self, s: &str) -> fmt::Result {
1023 match self.inner.write(s.as_bytes()) {
1026 self.error = Err(e);
1033 let mut output = Adaptor { inner: self, error: Ok(()) };
1034 match fmt::write(&mut output, fmt) {
1036 Err(..) => output.error
1041 /// Write a rust string into this sink.
1043 /// The bytes written will be the UTF-8 encoded version of the input string.
1044 /// If other encodings are desired, it is recommended to compose this stream
1045 /// with another performing the conversion, or to use `write` with a
1046 /// converted byte-array instead.
1048 fn write_str(&mut self, s: &str) -> IoResult<()> {
1049 self.write(s.as_bytes())
1052 /// Writes a string into this sink, and then writes a literal newline (`\n`)
1053 /// byte afterwards. Note that the writing of the newline is *not* atomic in
1054 /// the sense that the call to `write` is invoked twice (once with the
1055 /// string and once with a newline character).
1057 /// If other encodings or line ending flavors are desired, it is recommended
1058 /// that the `write` method is used specifically instead.
1060 fn write_line(&mut self, s: &str) -> IoResult<()> {
1061 self.write_str(s).and_then(|()| self.write(&[b'\n']))
1064 /// Write a single char, encoded as UTF-8.
1066 fn write_char(&mut self, c: char) -> IoResult<()> {
1067 let mut buf = [0u8; 4];
1068 let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
1069 self.write(buf[..n])
1072 /// Write the result of passing n through `int::to_str_bytes`.
1074 fn write_int(&mut self, n: int) -> IoResult<()> {
1075 write!(self, "{}", n)
1078 /// Write the result of passing n through `uint::to_str_bytes`.
1080 fn write_uint(&mut self, n: uint) -> IoResult<()> {
1081 write!(self, "{}", n)
1084 /// Write a little-endian uint (number of bytes depends on system).
1086 fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1087 extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
1090 /// Write a little-endian int (number of bytes depends on system).
1092 fn write_le_int(&mut self, n: int) -> IoResult<()> {
1093 extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
1096 /// Write a big-endian uint (number of bytes depends on system).
1098 fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1099 extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
1102 /// Write a big-endian int (number of bytes depends on system).
1104 fn write_be_int(&mut self, n: int) -> IoResult<()> {
1105 extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
1108 /// Write a big-endian u64 (8 bytes).
1110 fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1111 extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
1114 /// Write a big-endian u32 (4 bytes).
1116 fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1117 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1120 /// Write a big-endian u16 (2 bytes).
1122 fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1123 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1126 /// Write a big-endian i64 (8 bytes).
1128 fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1129 extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1132 /// Write a big-endian i32 (4 bytes).
1134 fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1135 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1138 /// Write a big-endian i16 (2 bytes).
1140 fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1141 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1144 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1146 fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1148 self.write_be_u64(transmute(f))
1152 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1154 fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1156 self.write_be_u32(transmute(f))
1160 /// Write a little-endian u64 (8 bytes).
1162 fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1163 extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
1166 /// Write a little-endian u32 (4 bytes).
1168 fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1169 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1172 /// Write a little-endian u16 (2 bytes).
1174 fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1175 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1178 /// Write a little-endian i64 (8 bytes).
1180 fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1181 extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1184 /// Write a little-endian i32 (4 bytes).
1186 fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1187 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1190 /// Write a little-endian i16 (2 bytes).
1192 fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1193 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1196 /// Write a little-endian IEEE754 double-precision floating-point
1199 fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1201 self.write_le_u64(transmute(f))
1205 /// Write a little-endian IEEE754 single-precision floating-point
1208 fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1210 self.write_le_u32(transmute(f))
1214 /// Write a u8 (1 byte).
1216 fn write_u8(&mut self, n: u8) -> IoResult<()> {
1220 /// Write an i8 (1 byte).
1222 fn write_i8(&mut self, n: i8) -> IoResult<()> {
1223 self.write(&[n as u8])
1227 /// A writer which can be converted to a RefWriter.
1228 pub trait ByRefWriter {
1229 /// Creates a wrapper around a mutable reference to the writer.
1231 /// This is useful to allow applying wrappers while still
1232 /// retaining ownership of the original value.
1234 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1237 impl<T: Writer> ByRefWriter for T {
1238 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1239 RefWriter { inner: self }
1243 impl<'a> Writer for Box<Writer+'a> {
1245 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
1246 (&mut **self).write(buf)
1250 fn flush(&mut self) -> IoResult<()> {
1251 (&mut **self).flush()
1255 impl<'a> Writer for &'a mut (Writer+'a) {
1257 fn write(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write(buf) }
1260 fn flush(&mut self) -> IoResult<()> { (**self).flush() }
1263 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1264 /// to another writer. This is often useful when composing streams.
1270 /// # fn process_input<R: Reader>(r: R) {}
1272 /// use std::io::util::TeeReader;
1273 /// use std::io::{stdin, ByRefWriter};
1275 /// let mut output = Vec::new();
1278 /// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1279 /// // handle to it in the outer scope
1280 /// let mut tee = TeeReader::new(stdin(), output.by_ref());
1281 /// process_input(tee);
1284 /// println!("input processed: {}", output);
1287 pub struct RefWriter<'a, W:'a> {
1288 /// The underlying writer which this is referencing
1292 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1294 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
1297 fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1301 /// A Stream is a readable and a writable object. Data written is typically
1302 /// received by the object which reads receive data from.
1303 pub trait Stream: Reader + Writer { }
1305 impl<T: Reader + Writer> Stream for T {}
1307 /// An iterator that reads a line on each iteration,
1308 /// until `.read_line()` encounters `EndOfFile`.
1310 /// # Notes about the Iteration Protocol
1312 /// The `Lines` may yield `None` and thus terminate
1313 /// an iteration, but continue to yield elements if iteration
1314 /// is attempted again.
1318 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1319 /// is returned by the iterator and should be handled by the caller.
1320 pub struct Lines<'r, T:'r> {
1324 impl<'r, T: Buffer> Iterator for Lines<'r, T> {
1325 type Item = IoResult<String>;
1327 fn next(&mut self) -> Option<IoResult<String>> {
1328 match self.buffer.read_line() {
1329 Ok(x) => Some(Ok(x)),
1330 Err(IoError { kind: EndOfFile, ..}) => None,
1331 Err(y) => Some(Err(y))
1336 /// An iterator that reads a utf8-encoded character on each iteration,
1337 /// until `.read_char()` encounters `EndOfFile`.
1339 /// # Notes about the Iteration Protocol
1341 /// The `Chars` may yield `None` and thus terminate
1342 /// an iteration, but continue to yield elements if iteration
1343 /// is attempted again.
1347 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1348 /// is returned by the iterator and should be handled by the caller.
1349 pub struct Chars<'r, T:'r> {
1353 impl<'r, T: Buffer> Iterator for Chars<'r, T> {
1354 type Item = IoResult<char>;
1356 fn next(&mut self) -> Option<IoResult<char>> {
1357 match self.buffer.read_char() {
1358 Ok(x) => Some(Ok(x)),
1359 Err(IoError { kind: EndOfFile, ..}) => None,
1360 Err(y) => Some(Err(y))
1365 /// A Buffer is a type of reader which has some form of internal buffering to
1366 /// allow certain kinds of reading operations to be more optimized than others.
1367 /// This type extends the `Reader` trait with a few methods that are not
1368 /// possible to reasonably implement with purely a read interface.
1369 pub trait Buffer: Reader {
1370 /// Fills the internal buffer of this object, returning the buffer contents.
1371 /// Note that none of the contents will be "read" in the sense that later
1372 /// calling `read` may return the same contents.
1374 /// The `consume` function must be called with the number of bytes that are
1375 /// consumed from this buffer returned to ensure that the bytes are never
1380 /// This function will return an I/O error if the underlying reader was
1381 /// read, but returned an error. Note that it is not an error to return a
1382 /// 0-length buffer.
1383 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1385 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1386 /// so they should no longer be returned in calls to `read`.
1387 fn consume(&mut self, amt: uint);
1389 /// Reads the next line of input, interpreted as a sequence of UTF-8
1390 /// encoded Unicode codepoints. If a newline is encountered, then the
1391 /// newline is contained in the returned string.
1396 /// use std::io::BufReader;
1398 /// let mut reader = BufReader::new(b"hello\nworld");
1399 /// assert_eq!("hello\n", &*reader.read_line().unwrap());
1404 /// This function has the same error semantics as `read_until`:
1406 /// * All non-EOF errors will be returned immediately
1407 /// * If an error is returned previously consumed bytes are lost
1408 /// * EOF is only returned if no bytes have been read
1409 /// * Reach EOF may mean that the delimiter is not present in the return
1412 /// Additionally, this function can fail if the line of input read is not a
1413 /// valid UTF-8 sequence of bytes.
1414 fn read_line(&mut self) -> IoResult<String> {
1415 self.read_until(b'\n').and_then(|line|
1416 match String::from_utf8(line) {
1418 Err(_) => Err(standard_error(InvalidInput)),
1423 /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1424 /// specified byte is encountered, reading ceases and the bytes up to and
1425 /// including the delimiter are returned.
1429 /// If any I/O error is encountered other than EOF, the error is immediately
1430 /// returned. Note that this may discard bytes which have already been read,
1431 /// and those bytes will *not* be returned. It is recommended to use other
1432 /// methods if this case is worrying.
1434 /// If EOF is encountered, then this function will return EOF if 0 bytes
1435 /// have been read, otherwise the pending byte buffer is returned. This
1436 /// is the reason that the byte buffer returned may not always contain the
1438 fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1439 let mut res = Vec::new();
1444 let available = match self.fill_buf() {
1446 Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1450 Err(e) => return Err(e)
1452 match available.iter().position(|&b| b == byte) {
1454 res.push_all(available[..i + 1]);
1459 res.push_all(available);
1460 used = available.len();
1470 /// Reads the next utf8-encoded character from the underlying stream.
1474 /// If an I/O error occurs, or EOF, then this function will return `Err`.
1475 /// This function will also return error if the stream does not contain a
1476 /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1477 fn read_char(&mut self) -> IoResult<char> {
1478 let first_byte = try!(self.read_byte());
1479 let width = unicode::str::utf8_char_width(first_byte);
1480 if width == 1 { return Ok(first_byte as char) }
1481 if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1482 let mut buf = [first_byte, 0, 0, 0];
1485 while start < width {
1486 match try!(self.read(buf.slice_mut(start, width))) {
1487 n if n == width - start => break,
1488 n if n < width - start => { start += n; }
1489 _ => return Err(standard_error(InvalidInput)),
1493 match str::from_utf8(buf[..width]).ok() {
1494 Some(s) => Ok(s.char_at(0)),
1495 None => Err(standard_error(InvalidInput))
1500 /// Extension methods for the Buffer trait which are included in the prelude.
1501 pub trait BufferPrelude {
1502 /// Create an iterator that reads a utf8-encoded character on each iteration
1507 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1508 /// is returned by the iterator and should be handled by the caller.
1509 fn chars<'r>(&'r mut self) -> Chars<'r, Self>;
1511 /// Create an iterator that reads a line on each iteration until EOF.
1515 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1516 /// is returned by the iterator and should be handled by the caller.
1517 fn lines<'r>(&'r mut self) -> Lines<'r, Self>;
1520 impl<T: Buffer> BufferPrelude for T {
1521 fn chars<'r>(&'r mut self) -> Chars<'r, T> {
1522 Chars { buffer: self }
1525 fn lines<'r>(&'r mut self) -> Lines<'r, T> {
1526 Lines { buffer: self }
1530 /// When seeking, the resulting cursor is offset from a base by the offset given
1531 /// to the `seek` function. The base used is specified by this enumeration.
1533 pub enum SeekStyle {
1534 /// Seek from the beginning of the stream
1536 /// Seek from the end of the stream
1538 /// Seek from the current position
1542 /// An object implementing `Seek` internally has some form of cursor which can
1543 /// be moved within a stream of bytes. The stream typically has a fixed size,
1544 /// allowing seeking relative to either end.
1546 /// Return position of file cursor in the stream
1547 fn tell(&self) -> IoResult<u64>;
1549 /// Seek to an offset in a stream
1551 /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1552 /// allowed, but seeking before position 0 is not allowed.
1556 /// * Seeking to a negative offset is considered an error
1557 /// * Seeking past the end of the stream does not modify the underlying
1558 /// stream, but the next write may cause the previous data to be filled in
1559 /// with a bit pattern.
1560 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1563 /// A listener is a value that can consume itself to start listening for
1566 /// Doing so produces some sort of Acceptor.
1567 pub trait Listener<T, A: Acceptor<T>> {
1568 /// Spin up the listener and start queuing incoming connections
1572 /// Returns `Err` if this listener could not be bound to listen for
1573 /// connections. In all cases, this listener is consumed.
1574 fn listen(self) -> IoResult<A>;
1577 /// An acceptor is a value that presents incoming connections
1578 pub trait Acceptor<T> {
1579 /// Wait for and accept an incoming connection
1583 /// Returns `Err` if an I/O error is encountered.
1584 fn accept(&mut self) -> IoResult<T>;
1586 /// Create an iterator over incoming connection attempts.
1588 /// Note that I/O errors will be yielded by the iterator itself.
1589 fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1590 IncomingConnections { inc: self }
1594 /// An infinite iterator over incoming connection attempts.
1595 /// Calling `next` will block the task until a connection is attempted.
1597 /// Since connection attempts can continue forever, this iterator always returns
1598 /// `Some`. The `Some` contains the `IoResult` representing whether the
1599 /// connection attempt was successful. A successful connection will be wrapped
1600 /// in `Ok`. A failed connection is represented as an `Err`.
1601 pub struct IncomingConnections<'a, Sized? A:'a> {
1605 impl<'a, T, Sized? A: Acceptor<T>> Iterator for IncomingConnections<'a, A> {
1606 type Item = IoResult<T>;
1608 fn next(&mut self) -> Option<IoResult<T>> {
1609 Some(self.inc.accept())
1613 /// Creates a standard error for a commonly used flavor of error. The `detail`
1614 /// field of the returned error will always be `None`.
1621 /// let eof = io::standard_error(io::EndOfFile);
1622 /// let einval = io::standard_error(io::InvalidInput);
1624 pub fn standard_error(kind: IoErrorKind) -> IoError {
1625 let desc = match kind {
1626 EndOfFile => "end of file",
1627 IoUnavailable => "I/O is unavailable",
1628 InvalidInput => "invalid input",
1629 OtherIoError => "unknown I/O error",
1630 FileNotFound => "file not found",
1631 PermissionDenied => "permission denied",
1632 ConnectionFailed => "connection failed",
1633 Closed => "stream is closed",
1634 ConnectionRefused => "connection refused",
1635 ConnectionReset => "connection reset",
1636 ConnectionAborted => "connection aborted",
1637 NotConnected => "not connected",
1638 BrokenPipe => "broken pipe",
1639 PathAlreadyExists => "file already exists",
1640 PathDoesntExist => "no such file",
1641 MismatchedFileTypeForOperation => "mismatched file type",
1642 ResourceUnavailable => "resource unavailable",
1643 TimedOut => "operation timed out",
1644 ShortWrite(..) => "short write",
1645 NoProgress => "no progress",
1654 /// A mode specifies how a file should be opened or created. These modes are
1655 /// passed to `File::open_mode` and are used to control where the file is
1656 /// positioned when it is initially opened.
1657 #[derive(Copy, Clone, PartialEq, Eq)]
1659 /// Opens a file positioned at the beginning.
1661 /// Opens a file positioned at EOF.
1663 /// Opens a file, truncating it if it already exists.
1667 /// Access permissions with which the file should be opened. `File`s
1668 /// opened with `Read` will return an error if written to.
1669 #[derive(Copy, Clone, PartialEq, Eq)]
1670 pub enum FileAccess {
1671 /// Read-only access, requests to write will result in an error
1673 /// Write-only access, requests to read will result in an error
1675 /// Read-write access, no requests are denied by default
1679 /// Different kinds of files which can be identified by a call to stat
1680 #[derive(Copy, PartialEq, Show, Hash, Clone)]
1682 /// This is a normal file, corresponding to `S_IFREG`
1685 /// This file is a directory, corresponding to `S_IFDIR`
1688 /// This file is a named pipe, corresponding to `S_IFIFO`
1691 /// This file is a block device, corresponding to `S_IFBLK`
1694 /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1697 /// The type of this file is not recognized as one of the other categories
1701 /// A structure used to describe metadata information about a file. This
1702 /// structure is created through the `stat` method on a `Path`.
1707 /// # use std::io::fs::PathExtensions;
1710 /// let info = match Path::new("foo.txt").stat() {
1711 /// Ok(stat) => stat,
1712 /// Err(e) => panic!("couldn't read foo.txt: {}", e),
1715 /// println!("byte size: {}", info.size);
1718 #[derive(Copy, Hash)]
1719 pub struct FileStat {
1720 /// The size of the file, in bytes
1722 /// The kind of file this path points to (directory, file, pipe, etc.)
1724 /// The file permissions currently on the file
1725 pub perm: FilePermission,
1727 // FIXME(#10301): These time fields are pretty useless without an actual
1728 // time representation, what are the milliseconds relative
1731 /// The time that the file was created at, in platform-dependent
1734 /// The time that this file was last modified, in platform-dependent
1737 /// The time that this file was last accessed, in platform-dependent
1741 /// Information returned by stat() which is not guaranteed to be
1742 /// platform-independent. This information may be useful on some platforms,
1743 /// but it may have different meanings or no meaning at all on other
1746 /// Usage of this field is discouraged, but if access is desired then the
1747 /// fields are located here.
1749 pub unstable: UnstableFileStat,
1752 /// This structure represents all of the possible information which can be
1753 /// returned from a `stat` syscall which is not contained in the `FileStat`
1754 /// structure. This information is not necessarily platform independent, and may
1755 /// have different meanings or no meaning at all on some platforms.
1757 #[derive(Copy, Hash)]
1758 pub struct UnstableFileStat {
1759 /// The ID of the device containing the file.
1761 /// The file serial number.
1765 /// The number of hard links to this file.
1767 /// The user ID of the file.
1769 /// The group ID of the file.
1771 /// The optimal block size for I/O.
1773 /// The blocks allocated for this file.
1775 /// User-defined flags for the file.
1777 /// The file generation number.
1782 #[doc = "A set of permissions for a file or directory is represented"]
1783 #[doc = "by a set of flags which are or'd together."]
1784 flags FilePermission: u32 {
1785 const USER_READ = 0o400,
1786 const USER_WRITE = 0o200,
1787 const USER_EXECUTE = 0o100,
1788 const GROUP_READ = 0o040,
1789 const GROUP_WRITE = 0o020,
1790 const GROUP_EXECUTE = 0o010,
1791 const OTHER_READ = 0o004,
1792 const OTHER_WRITE = 0o002,
1793 const OTHER_EXECUTE = 0o001,
1795 const USER_RWX = USER_READ.bits | USER_WRITE.bits | USER_EXECUTE.bits,
1796 const GROUP_RWX = GROUP_READ.bits | GROUP_WRITE.bits | GROUP_EXECUTE.bits,
1797 const OTHER_RWX = OTHER_READ.bits | OTHER_WRITE.bits | OTHER_EXECUTE.bits,
1799 #[doc = "Permissions for user owned files, equivalent to 0644 on"]
1800 #[doc = "unix-like systems."]
1801 const USER_FILE = USER_READ.bits | USER_WRITE.bits | GROUP_READ.bits | OTHER_READ.bits,
1803 #[doc = "Permissions for user owned directories, equivalent to 0755 on"]
1804 #[doc = "unix-like systems."]
1805 const USER_DIR = USER_RWX.bits | GROUP_READ.bits | GROUP_EXECUTE.bits |
1806 OTHER_READ.bits | OTHER_EXECUTE.bits,
1808 #[doc = "Permissions for user owned executables, equivalent to 0755"]
1809 #[doc = "on unix-like systems."]
1810 const USER_EXEC = USER_DIR.bits,
1812 #[doc = "All possible permissions enabled."]
1813 const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
1819 impl Default for FilePermission {
1822 fn default() -> FilePermission { FilePermission::empty() }
1825 impl fmt::Show for FilePermission {
1826 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1827 write!(f, "{:04o}", self.bits)
1833 use self::BadReaderBehavior::*;
1834 use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
1835 use prelude::v1::{Ok, Vec, Buffer, SliceExt};
1838 #[derive(Clone, PartialEq, Show)]
1839 enum BadReaderBehavior {
1844 struct BadReader<T> {
1846 behavior: Vec<BadReaderBehavior>,
1849 impl<T: Reader> BadReader<T> {
1850 fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1851 BadReader { behavior: behavior, r: r }
1855 impl<T: Reader> Reader for BadReader<T> {
1856 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1857 let BadReader { ref mut behavior, ref mut r } = *self;
1859 if behavior.is_empty() {
1860 // fall back on good
1863 match behavior.as_mut_slice()[0] {
1864 GoodBehavior(0) => (),
1865 GoodBehavior(ref mut x) => {
1869 BadBehavior(0) => (),
1870 BadBehavior(ref mut x) => {
1881 fn test_read_at_least() {
1882 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1883 vec![GoodBehavior(uint::MAX)]);
1884 let buf = &mut [0u8; 5];
1885 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1886 assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1887 assert!(r.read_at_least(0, buf).is_ok());
1889 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1890 vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
1891 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1893 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1894 vec![BadBehavior(1), GoodBehavior(1),
1895 BadBehavior(50), GoodBehavior(uint::MAX)]);
1896 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1897 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1899 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1900 vec![BadBehavior(uint::MAX)]);
1901 assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1903 let mut r = MemReader::new(b"hello, world!".to_vec());
1904 assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1905 assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1909 fn test_push_at_least() {
1910 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1911 vec![GoodBehavior(uint::MAX)]);
1912 let mut buf = Vec::new();
1913 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1914 assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1916 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1917 vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
1918 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1920 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1921 vec![BadBehavior(1), GoodBehavior(1),
1922 BadBehavior(50), GoodBehavior(uint::MAX)]);
1923 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1924 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1926 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1927 vec![BadBehavior(uint::MAX)]);
1928 assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1930 let mut r = MemReader::new(b"hello, world!".to_vec());
1931 assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
1938 assert_eq!(format!("{}", USER_READ), "0400");
1939 assert_eq!(format!("{}", USER_FILE), "0644");
1940 assert_eq!(format!("{}", USER_EXEC), "0755");
1941 assert_eq!(format!("{}", USER_RWX), "0700");
1942 assert_eq!(format!("{}", GROUP_RWX), "0070");
1943 assert_eq!(format!("{}", OTHER_RWX), "0007");
1944 assert_eq!(format!("{}", ALL_PERMISSIONS), "0777");
1945 assert_eq!(format!("{}", USER_READ | USER_WRITE | OTHER_WRITE), "0602");
1948 fn _ensure_buffer_is_object_safe<T: Buffer>(x: &T) -> &Buffer {