1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ignore-lexer-test FIXME #15883
13 // FIXME: cover these topics:
14 // path, reader, writer, stream, raii (close not needed),
15 // stdio, print!, println!, file access, process spawning,
19 //! I/O, including files, networking, timers, and processes
21 //! > **Warning**: This module is currently called `old_io` for a reason! The
22 //! > module is currently being redesigned in a number of RFCs. For more details
23 //! > follow the RFC repository in connection with [RFC 517][base] or follow
24 //! > some of these sub-RFCs
26 //! > * [String handling][osstr]
27 //! > * [Core I/O support][core]
28 //! > * [Deadlines][deadlines]
29 //! > * [std::env][env]
30 //! > * [std::process][process]
32 //! [base]: https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md
33 //! [osstr]: https://github.com/rust-lang/rfcs/pull/575
34 //! [core]: https://github.com/rust-lang/rfcs/pull/576
35 //! [deadlines]: https://github.com/rust-lang/rfcs/pull/577
36 //! [env]: https://github.com/rust-lang/rfcs/pull/578
37 //! [process]: https://github.com/rust-lang/rfcs/pull/579
39 //! `std::io` provides Rust's basic I/O types,
40 //! for reading and writing to files, TCP, UDP,
41 //! and other types of sockets and pipes,
42 //! manipulating the file system, spawning processes.
46 //! Some examples of obvious things you might want to do
48 //! * Read lines from stdin
51 //! use std::old_io as io;
53 //! let mut stdin = io::stdin();
54 //! for line in stdin.lock().lines() {
55 //! print!("{}", line.unwrap());
59 //! * Read a complete file
62 //! use std::old_io::File;
64 //! let contents = File::open(&Path::new("message.txt")).read_to_end();
67 //! * Write a line to a file
70 //! # #![allow(unused_must_use)]
71 //! use std::old_io::File;
73 //! let mut file = File::create(&Path::new("message.txt"));
74 //! file.write_all(b"hello, file!\n");
76 //! # ::std::old_io::fs::unlink(&Path::new("message.txt"));
79 //! * Iterate over the lines of a file
82 //! use std::old_io::BufferedReader;
83 //! use std::old_io::File;
85 //! let path = Path::new("message.txt");
86 //! let mut file = BufferedReader::new(File::open(&path));
87 //! for line in file.lines() {
88 //! print!("{}", line.unwrap());
92 //! * Pull the lines of a file into a vector of strings
95 //! use std::old_io::BufferedReader;
96 //! use std::old_io::File;
98 //! let path = Path::new("message.txt");
99 //! let mut file = BufferedReader::new(File::open(&path));
100 //! let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
103 //! * Make a simple TCP client connection and request
106 //! # #![allow(unused_must_use)]
107 //! use std::old_io::TcpStream;
109 //! # // connection doesn't fail if a server is running on 8080
110 //! # // locally, we still want to be type checking this code, so lets
111 //! # // just stop it running (#11576)
113 //! let mut socket = TcpStream::connect("127.0.0.1:8080").unwrap();
114 //! socket.write_all(b"GET / HTTP/1.0\n\n");
115 //! let response = socket.read_to_end();
119 //! * Make a simple TCP server
124 //! # #![allow(dead_code)]
125 //! use std::old_io::{TcpListener, TcpStream};
126 //! use std::old_io::{Acceptor, Listener};
129 //! let listener = TcpListener::bind("127.0.0.1:80");
131 //! // bind the listener to the specified address
132 //! let mut acceptor = listener.listen();
134 //! fn handle_client(mut stream: TcpStream) {
136 //! # &mut stream; // silence unused mutability/variable warning
138 //! // accept connections and process them, spawning a new tasks for each one
139 //! for stream in acceptor.incoming() {
141 //! Err(e) => { /* connection failed */ }
143 //! thread::spawn(move|| {
144 //! // connection succeeded
145 //! handle_client(stream)
151 //! // close the socket server
159 //! I/O is an area where nearly every operation can result in unexpected
160 //! errors. Errors should be painfully visible when they happen, and handling them
161 //! should be easy to work with. It should be convenient to handle specific I/O
162 //! errors, and it should also be convenient to not deal with I/O errors.
164 //! Rust's I/O employs a combination of techniques to reduce boilerplate
165 //! while still providing feedback about errors. The basic strategy:
167 //! * All I/O operations return `IoResult<T>` which is equivalent to
168 //! `Result<T, IoError>`. The `Result` type is defined in the `std::result`
170 //! * If the `Result` type goes unused, then the compiler will by default emit a
171 //! warning about the unused result. This is because `Result` has the
172 //! `#[must_use]` attribute.
173 //! * Common traits are implemented for `IoResult`, e.g.
174 //! `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
175 //! to be 'unwrapped' before use.
177 //! These features combine in the API to allow for expressions like
178 //! `File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n")`
179 //! without having to worry about whether "diary.txt" exists or whether
180 //! the write succeeds. As written, if either `new` or `write_line`
181 //! encounters an error then the result of the entire expression will
184 //! If you wanted to handle the error though you might write:
187 //! # #![allow(unused_must_use)]
188 //! use std::old_io::File;
190 //! match File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n") {
191 //! Ok(()) => (), // succeeded
192 //! Err(e) => println!("failed to write to my diary: {}", e),
195 //! # ::std::old_io::fs::unlink(&Path::new("diary.txt"));
198 //! So what actually happens if `create` encounters an error?
199 //! It's important to know that what `new` returns is not a `File`
200 //! but an `IoResult<File>`. If the file does not open, then `new` will simply
201 //! return `Err(..)`. Because there is an implementation of `Writer` (the trait
202 //! required ultimately required for types to implement `write_line`) there is no
203 //! need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
204 //! on it. If `new` returned an `Err(..)` then the followup call to `write_line`
205 //! will also return an error.
209 //! Explicit pattern matching on `IoResult`s can get quite verbose, especially
210 //! when performing many I/O operations. Some examples (like those above) are
211 //! alleviated with extra methods implemented on `IoResult`, but others have more
212 //! complex interdependencies among each I/O operation.
214 //! The `try!` macro from `std::macros` is provided as a method of early-return
215 //! inside `Result`-returning functions. It expands to an early-return on `Err`
216 //! and otherwise unwraps the contained `Ok` value.
218 //! If you wanted to read several `u32`s from a file and return their product:
221 //! use std::old_io::{File, IoResult};
223 //! fn file_product(p: &Path) -> IoResult<u32> {
224 //! let mut f = File::open(p);
225 //! let x1 = try!(f.read_le_u32());
226 //! let x2 = try!(f.read_le_u32());
231 //! match file_product(&Path::new("numbers.bin")) {
232 //! Ok(x) => println!("{}", x),
233 //! Err(e) => println!("Failed to read numbers!")
237 //! With `try!` in `file_product`, each `read_le_u32` need not be directly
238 //! concerned with error handling; instead its caller is responsible for
239 //! responding to errors that may occur while attempting to read the numbers.
241 #![unstable(feature = "old_io")]
242 #![deny(unused_must_use)]
243 #![allow(deprecated)] // seriously this is all deprecated
244 #![allow(unused_imports)]
245 #![deprecated(since = "1.0.0",
246 reasons = "APIs have been replaced with new I/O modules such as \
247 std::{io, fs, net, process}")]
249 pub use self::SeekStyle::*;
250 pub use self::FileMode::*;
251 pub use self::FileAccess::*;
252 pub use self::IoErrorKind::*;
255 use default::Default;
259 use iter::{Iterator, IteratorExt};
260 use marker::{PhantomFn, Sized};
264 use option::Option::{Some, None};
268 use result::Result::{Ok, Err};
279 pub use self::stdio::stdin;
280 pub use self::stdio::stdout;
281 pub use self::stdio::stderr;
282 pub use self::stdio::print;
283 pub use self::stdio::println;
285 pub use self::fs::File;
286 pub use self::timer::Timer;
287 pub use self::net::ip::IpAddr;
288 pub use self::net::tcp::TcpListener;
289 pub use self::net::tcp::TcpStream;
290 pub use self::pipe::PipeStream;
291 pub use self::process::{Process, Command};
292 pub use self::tempfile::TempDir;
294 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
295 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
297 pub use self::comm_adapters::{ChanReader, ChanWriter};
316 /// The default buffer size for various I/O operations
317 // libuv recommends 64k buffers to maximize throughput
318 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
319 const DEFAULT_BUF_SIZE: uint = 1024 * 64;
321 /// A convenient typedef of the return value of any I/O action.
322 pub type IoResult<T> = Result<T, IoError>;
324 /// The type passed to I/O condition handlers to indicate error
328 /// Is something like this sufficient? It's kind of archaic
329 #[derive(PartialEq, Eq, Clone, Debug)]
331 /// An enumeration which can be matched against for determining the flavor
333 pub kind: IoErrorKind,
334 /// A human-readable description about the error
335 pub desc: &'static str,
336 /// Detailed information about this error, not always available
337 pub detail: Option<String>
341 /// Convert an `errno` value into an `IoError`.
343 /// If `detail` is `true`, the `detail` field of the `IoError`
344 /// struct is filled with an allocated string describing the error
345 /// in more detail, retrieved from the operating system.
346 pub fn from_errno(errno: i32, detail: bool) -> IoError {
347 let mut err = sys::decode_error(errno as i32);
348 if detail && err.kind == OtherIoError {
349 err.detail = Some(os::error_string(errno).to_lowercase());
354 /// Retrieve the last error to occur as a (detailed) IoError.
356 /// This uses the OS `errno`, and so there should not be any task
357 /// descheduling or migration (other than that performed by the
358 /// operating system) between the call(s) for which errors are
359 /// being checked and the call of this function.
360 pub fn last_error() -> IoError {
361 IoError::from_errno(os::errno(), true)
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl fmt::Display for IoError {
367 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
369 IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
370 write!(fmt, "{}", detail),
371 IoError { detail: None, desc, .. } =>
372 write!(fmt, "{}", desc),
373 IoError { detail: Some(ref detail), desc, .. } =>
374 write!(fmt, "{} ({})", desc, detail)
379 impl Error for IoError {
380 fn description(&self) -> &str { self.desc }
383 /// A list specifying general categories of I/O error.
384 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
385 pub enum IoErrorKind {
386 /// Any I/O error not part of this list.
388 /// The operation could not complete because end of file was reached.
390 /// The file was not found.
392 /// The file permissions disallowed access to this file.
394 /// A network connection failed for some reason not specified in this list.
396 /// The network operation failed because the network connection was closed.
398 /// The connection was refused by the remote server.
400 /// The connection was reset by the remote server.
402 /// The connection was aborted (terminated) by the remote server.
404 /// The network operation failed because it was not connected yet.
406 /// The operation failed because a pipe was closed.
408 /// A file already existed with that name.
410 /// No file exists at that location.
412 /// The path did not specify the type of file that this operation required. For example,
413 /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
414 MismatchedFileTypeForOperation,
415 /// The operation temporarily failed (for example, because a signal was received), and retrying
418 /// No I/O functionality is available for this task.
420 /// A parameter was incorrect in a way that caused an I/O error not part of this list.
422 /// The I/O operation's timeout expired, causing it to be canceled.
424 /// This write operation failed to write all of its data.
426 /// Normally the write() method on a Writer guarantees that all of its data
427 /// has been written, but some operations may be terminated after only
428 /// partially writing some data. An example of this is a timed out write
429 /// which successfully wrote a known number of bytes, but bailed out after
432 /// The payload contained as part of this variant is the number of bytes
433 /// which are known to have been successfully written.
435 /// The Reader returned 0 bytes from `read()` too many times.
439 /// A trait that lets you add a `detail` to an IoError easily
440 trait UpdateIoError {
441 /// Returns an IoError with updated description and detail
442 fn update_err<D>(self, desc: &'static str, detail: D) -> Self where
443 D: FnOnce(&IoError) -> String;
445 /// Returns an IoError with updated detail
446 fn update_detail<D>(self, detail: D) -> Self where
447 D: FnOnce(&IoError) -> String;
449 /// Returns an IoError with update description
450 fn update_desc(self, desc: &'static str) -> Self;
453 impl<T> UpdateIoError for IoResult<T> {
454 fn update_err<D>(self, desc: &'static str, detail: D) -> IoResult<T> where
455 D: FnOnce(&IoError) -> String,
457 self.map_err(move |mut e| {
458 let detail = detail(&e);
460 e.detail = Some(detail);
465 fn update_detail<D>(self, detail: D) -> IoResult<T> where
466 D: FnOnce(&IoError) -> String,
468 self.map_err(move |mut e| { e.detail = Some(detail(&e)); e })
471 fn update_desc(self, desc: &'static str) -> IoResult<T> {
472 self.map_err(|mut e| { e.desc = desc; e })
476 static NO_PROGRESS_LIMIT: uint = 1000;
478 /// A trait for objects which are byte-oriented streams. Readers are defined by
479 /// one method, `read`. This function will block until data is available,
480 /// filling in the provided buffer with any data read.
482 /// Readers are intended to be composable with one another. Many objects
483 /// throughout the I/O and related libraries take and provide types which
484 /// implement the `Reader` trait.
487 // Only method which need to get implemented for this trait
489 /// Read bytes, up to the length of `buf` and place them in `buf`.
490 /// Returns the number of bytes read. The number of bytes read may
491 /// be less than the number requested, even 0. Returns `Err` on EOF.
495 /// If an error occurs during this I/O operation, then it is returned as
496 /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
497 /// inspected for in the error's `kind` field. Also note that reading 0
498 /// bytes is not considered an error in all circumstances
500 /// # Implementation Note
502 /// When implementing this method on a new Reader, you are strongly encouraged
503 /// not to return 0 if you can avoid it.
504 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
506 // Convenient helper methods based on the above methods
508 /// Reads at least `min` bytes and places them in `buf`.
509 /// Returns the number of bytes read.
511 /// This will continue to call `read` until at least `min` bytes have been
512 /// read. If `read` returns 0 too many times, `NoProgress` will be
517 /// If an error occurs at any point, that error is returned, and no further
519 fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
522 detail: Some(String::from_str("the buffer is too short")),
523 ..standard_error(InvalidInput)
530 match self.read(&mut buf[read..]) {
533 if zeroes >= NO_PROGRESS_LIMIT {
534 return Err(standard_error(NoProgress));
541 err@Err(_) => return err
548 /// Reads a single byte. Returns `Err` on EOF.
549 fn read_byte(&mut self) -> IoResult<u8> {
551 try!(self.read_at_least(1, &mut buf));
555 /// Reads up to `len` bytes and appends them to a vector.
556 /// Returns the number of bytes read. The number of bytes read may be
557 /// less than the number requested, even 0. Returns Err on EOF.
561 /// If an error occurs during this I/O operation, then it is returned
562 /// as `Err(IoError)`. See `read()` for more details.
563 fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
564 let start_len = buf.len();
568 let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
571 unsafe { buf.set_len(start_len + n) };
575 /// Reads at least `min` bytes, but no more than `len`, and appends them to
577 /// Returns the number of bytes read.
579 /// This will continue to call `read` until at least `min` bytes have been
580 /// read. If `read` returns 0 too many times, `NoProgress` will be
585 /// If an error occurs at any point, that error is returned, and no further
587 fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
590 detail: Some(String::from_str("the buffer is too short")),
591 ..standard_error(InvalidInput)
595 let start_len = buf.len();
598 // we can't just use self.read_at_least(min, slice) because we need to push
599 // successful reads onto the vector before any returned errors.
604 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
605 try!(self.read_at_least(1, s))
607 unsafe { buf.set_len(start_len + read) };
612 /// Reads exactly `len` bytes and gives you back a new vector of length
617 /// Fails with the same conditions as `read`. Additionally returns error
618 /// on EOF. Note that if an error is returned, then some number of bytes may
619 /// have already been consumed from the underlying reader, and they are lost
620 /// (not returned as part of the error). If this is unacceptable, then it is
621 /// recommended to use the `push_at_least` or `read` methods.
622 fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
623 let mut buf = Vec::with_capacity(len);
624 match self.push_at_least(len, len, &mut buf) {
630 /// Reads all remaining bytes from the stream.
634 /// Returns any non-EOF error immediately. Previously read bytes are
635 /// discarded when an error is returned.
637 /// When EOF is encountered, all bytes read up to that point are returned.
638 fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
639 let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
641 match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
643 Err(ref e) if e.kind == EndOfFile => break,
644 Err(e) => return Err(e)
650 /// Reads all of the remaining bytes of this stream, interpreting them as a
651 /// UTF-8 encoded stream. The corresponding string is returned.
655 /// This function returns all of the same errors as `read_to_end` with an
656 /// additional error if the reader's contents are not a valid sequence of
658 fn read_to_string(&mut self) -> IoResult<String> {
659 self.read_to_end().and_then(|s| {
660 match String::from_utf8(s) {
662 Err(_) => Err(standard_error(InvalidInput)),
667 // Byte conversion helpers
669 /// Reads `n` little-endian unsigned integer bytes.
671 /// `n` must be between 1 and 8, inclusive.
672 fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
673 assert!(nbytes > 0 && nbytes <= 8);
679 val += (try!(self.read_u8()) as u64) << pos;
686 /// Reads `n` little-endian signed integer bytes.
688 /// `n` must be between 1 and 8, inclusive.
689 fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
690 self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
693 /// Reads `n` big-endian unsigned integer bytes.
695 /// `n` must be between 1 and 8, inclusive.
696 fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
697 assert!(nbytes > 0 && nbytes <= 8);
703 val += (try!(self.read_u8()) as u64) << i * 8;
708 /// Reads `n` big-endian signed integer bytes.
710 /// `n` must be between 1 and 8, inclusive.
711 fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
712 self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
715 /// Reads a little-endian unsigned integer.
717 /// The number of bytes returned is system-dependent.
718 fn read_le_uint(&mut self) -> IoResult<uint> {
719 self.read_le_uint_n(usize::BYTES as usize).map(|i| i as uint)
722 /// Reads a little-endian integer.
724 /// The number of bytes returned is system-dependent.
725 fn read_le_int(&mut self) -> IoResult<int> {
726 self.read_le_int_n(isize::BYTES as usize).map(|i| i as int)
729 /// Reads a big-endian unsigned integer.
731 /// The number of bytes returned is system-dependent.
732 fn read_be_uint(&mut self) -> IoResult<uint> {
733 self.read_be_uint_n(usize::BYTES as usize).map(|i| i as uint)
736 /// Reads a big-endian integer.
738 /// The number of bytes returned is system-dependent.
739 fn read_be_int(&mut self) -> IoResult<int> {
740 self.read_be_int_n(isize::BYTES as usize).map(|i| i as int)
743 /// Reads a big-endian `u64`.
745 /// `u64`s are 8 bytes long.
746 fn read_be_u64(&mut self) -> IoResult<u64> {
747 self.read_be_uint_n(8)
750 /// Reads a big-endian `u32`.
752 /// `u32`s are 4 bytes long.
753 fn read_be_u32(&mut self) -> IoResult<u32> {
754 self.read_be_uint_n(4).map(|i| i as u32)
757 /// Reads a big-endian `u16`.
759 /// `u16`s are 2 bytes long.
760 fn read_be_u16(&mut self) -> IoResult<u16> {
761 self.read_be_uint_n(2).map(|i| i as u16)
764 /// Reads a big-endian `i64`.
766 /// `i64`s are 8 bytes long.
767 fn read_be_i64(&mut self) -> IoResult<i64> {
768 self.read_be_int_n(8)
771 /// Reads a big-endian `i32`.
773 /// `i32`s are 4 bytes long.
774 fn read_be_i32(&mut self) -> IoResult<i32> {
775 self.read_be_int_n(4).map(|i| i as i32)
778 /// Reads a big-endian `i16`.
780 /// `i16`s are 2 bytes long.
781 fn read_be_i16(&mut self) -> IoResult<i16> {
782 self.read_be_int_n(2).map(|i| i as i16)
785 /// Reads a big-endian `f64`.
787 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
788 fn read_be_f64(&mut self) -> IoResult<f64> {
789 self.read_be_u64().map(|i| unsafe {
790 transmute::<u64, f64>(i)
794 /// Reads a big-endian `f32`.
796 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
797 fn read_be_f32(&mut self) -> IoResult<f32> {
798 self.read_be_u32().map(|i| unsafe {
799 transmute::<u32, f32>(i)
803 /// Reads a little-endian `u64`.
805 /// `u64`s are 8 bytes long.
806 fn read_le_u64(&mut self) -> IoResult<u64> {
807 self.read_le_uint_n(8)
810 /// Reads a little-endian `u32`.
812 /// `u32`s are 4 bytes long.
813 fn read_le_u32(&mut self) -> IoResult<u32> {
814 self.read_le_uint_n(4).map(|i| i as u32)
817 /// Reads a little-endian `u16`.
819 /// `u16`s are 2 bytes long.
820 fn read_le_u16(&mut self) -> IoResult<u16> {
821 self.read_le_uint_n(2).map(|i| i as u16)
824 /// Reads a little-endian `i64`.
826 /// `i64`s are 8 bytes long.
827 fn read_le_i64(&mut self) -> IoResult<i64> {
828 self.read_le_int_n(8)
831 /// Reads a little-endian `i32`.
833 /// `i32`s are 4 bytes long.
834 fn read_le_i32(&mut self) -> IoResult<i32> {
835 self.read_le_int_n(4).map(|i| i as i32)
838 /// Reads a little-endian `i16`.
840 /// `i16`s are 2 bytes long.
841 fn read_le_i16(&mut self) -> IoResult<i16> {
842 self.read_le_int_n(2).map(|i| i as i16)
845 /// Reads a little-endian `f64`.
847 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
848 fn read_le_f64(&mut self) -> IoResult<f64> {
849 self.read_le_u64().map(|i| unsafe {
850 transmute::<u64, f64>(i)
854 /// Reads a little-endian `f32`.
856 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
857 fn read_le_f32(&mut self) -> IoResult<f32> {
858 self.read_le_u32().map(|i| unsafe {
859 transmute::<u32, f32>(i)
865 /// `u8`s are 1 byte.
866 fn read_u8(&mut self) -> IoResult<u8> {
872 /// `i8`s are 1 byte.
873 fn read_i8(&mut self) -> IoResult<i8> {
874 self.read_byte().map(|i| i as i8)
878 /// A reader which can be converted to a RefReader.
879 pub trait ByRefReader {
880 /// Creates a wrapper around a mutable reference to the reader.
882 /// This is useful to allow applying adaptors while still
883 /// retaining ownership of the original value.
884 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
887 impl<T: Reader> ByRefReader for T {
888 fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
889 RefReader { inner: self }
893 /// A reader which can be converted to bytes.
894 pub trait BytesReader {
895 /// Create an iterator that reads a single byte on
896 /// each iteration, until EOF.
900 /// Any error other than `EndOfFile` that is produced by the underlying Reader
901 /// is returned by the iterator and should be handled by the caller.
902 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self>;
905 impl<T: Reader> BytesReader for T {
906 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, T> {
907 extensions::Bytes::new(self)
911 impl<'a> Reader for Box<Reader+'a> {
912 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
913 let reader: &mut Reader = &mut **self;
918 impl<'a> Reader for &'a mut (Reader+'a) {
919 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (*self).read(buf) }
922 /// Returns a slice of `v` between `start` and `end`.
924 /// Similar to `slice()` except this function only bounds the slice on the
925 /// capacity of `v`, not the length.
929 /// Panics when `start` or `end` point outside the capacity of `v`, or when
931 // Private function here because we aren't sure if we want to expose this as
932 // API yet. If so, it should be a method on Vec.
933 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
937 assert!(start <= end);
938 assert!(end <= v.capacity());
939 slice::from_raw_parts_mut(
940 v.as_mut_ptr().offset(start as int),
945 /// A `RefReader` is a struct implementing `Reader` which contains a reference
946 /// to another reader. This is often useful when composing streams.
951 /// use std::old_io as io;
952 /// use std::old_io::ByRefReader;
953 /// use std::old_io::util::LimitReader;
955 /// fn process_input<R: Reader>(r: R) {}
957 /// let mut stream = io::stdin();
959 /// // Only allow the function to process at most one kilobyte of input
961 /// let stream = LimitReader::new(stream.by_ref(), 1024);
962 /// process_input(stream);
965 /// // 'stream' is still available for use here
967 pub struct RefReader<'a, R:'a> {
968 /// The underlying reader which this is referencing
972 impl<'a, R: Reader> Reader for RefReader<'a, R> {
973 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
976 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
977 fn fill_buf(&mut self) -> IoResult<&[u8]> { self.inner.fill_buf() }
978 fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
981 fn extend_sign(val: u64, nbytes: uint) -> i64 {
982 let shift = (8 - nbytes) * 8;
983 (val << shift) as i64 >> shift
986 /// A trait for objects which are byte-oriented streams. Writers are defined by
987 /// one method, `write`. This function will block until the provided buffer of
988 /// bytes has been entirely written, and it will return any failures which occur.
990 /// Another commonly overridden method is the `flush` method for writers such as
991 /// buffered writers.
993 /// Writers are intended to be composable with one another. Many objects
994 /// throughout the I/O and related libraries take and provide types which
995 /// implement the `Writer` trait.
997 /// Write the entirety of a given buffer
1001 /// If an error happens during the I/O operation, the error is returned as
1002 /// `Err`. Note that it is considered an error if the entire buffer could
1003 /// not be written, and if an error is returned then it is unknown how much
1004 /// data (if any) was actually written.
1005 fn write_all(&mut self, buf: &[u8]) -> IoResult<()>;
1007 /// Deprecated, this method was renamed to `write_all`
1008 #[unstable(feature = "io")]
1009 #[deprecated(since = "1.0.0", reason = "renamed to `write_all`")]
1010 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write_all(buf) }
1012 /// Flush this output stream, ensuring that all intermediately buffered
1013 /// contents reach their destination.
1015 /// This is by default a no-op and implementers of the `Writer` trait should
1016 /// decide whether their stream needs to be buffered or not.
1017 fn flush(&mut self) -> IoResult<()> { Ok(()) }
1019 /// Writes a formatted string into this writer, returning any error
1022 /// This method is primarily used to interface with the `format_args!`
1023 /// macro, but it is rare that this should explicitly be called. The
1024 /// `write!` macro should be favored to invoke this method instead.
1028 /// This function will return any I/O error reported while formatting.
1029 fn write_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
1030 // Create a shim which translates a Writer to a fmt::Write and saves
1031 // off I/O errors. instead of discarding them
1032 struct Adaptor<'a, T: ?Sized +'a> {
1034 error: IoResult<()>,
1037 impl<'a, T: ?Sized + Writer> fmt::Write for Adaptor<'a, T> {
1038 fn write_str(&mut self, s: &str) -> fmt::Result {
1039 match self.inner.write_all(s.as_bytes()) {
1042 self.error = Err(e);
1049 let mut output = Adaptor { inner: self, error: Ok(()) };
1050 match fmt::write(&mut output, fmt) {
1052 Err(..) => output.error
1057 /// Write a rust string into this sink.
1059 /// The bytes written will be the UTF-8 encoded version of the input string.
1060 /// If other encodings are desired, it is recommended to compose this stream
1061 /// with another performing the conversion, or to use `write` with a
1062 /// converted byte-array instead.
1064 fn write_str(&mut self, s: &str) -> IoResult<()> {
1065 self.write_all(s.as_bytes())
1068 /// Writes a string into this sink, and then writes a literal newline (`\n`)
1069 /// byte afterwards. Note that the writing of the newline is *not* atomic in
1070 /// the sense that the call to `write` is invoked twice (once with the
1071 /// string and once with a newline character).
1073 /// If other encodings or line ending flavors are desired, it is recommended
1074 /// that the `write` method is used specifically instead.
1076 fn write_line(&mut self, s: &str) -> IoResult<()> {
1077 self.write_str(s).and_then(|()| self.write_all(&[b'\n']))
1080 /// Write a single char, encoded as UTF-8.
1082 fn write_char(&mut self, c: char) -> IoResult<()> {
1083 let mut buf = [0; 4];
1084 let n = c.encode_utf8(&mut buf).unwrap_or(0);
1085 self.write_all(&buf[..n])
1088 /// Write the result of passing n through `int::to_str_bytes`.
1090 fn write_int(&mut self, n: int) -> IoResult<()> {
1091 write!(self, "{}", n)
1094 /// Write the result of passing n through `uint::to_str_bytes`.
1096 fn write_uint(&mut self, n: uint) -> IoResult<()> {
1097 write!(self, "{}", n)
1100 /// Write a little-endian uint (number of bytes depends on system).
1102 fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1103 extensions::u64_to_le_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
1106 /// Write a little-endian int (number of bytes depends on system).
1108 fn write_le_int(&mut self, n: int) -> IoResult<()> {
1109 extensions::u64_to_le_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
1112 /// Write a big-endian uint (number of bytes depends on system).
1114 fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1115 extensions::u64_to_be_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
1118 /// Write a big-endian int (number of bytes depends on system).
1120 fn write_be_int(&mut self, n: int) -> IoResult<()> {
1121 extensions::u64_to_be_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
1124 /// Write a big-endian u64 (8 bytes).
1126 fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1127 extensions::u64_to_be_bytes(n, 8, |v| self.write_all(v))
1130 /// Write a big-endian u32 (4 bytes).
1132 fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1133 extensions::u64_to_be_bytes(n as u64, 4, |v| self.write_all(v))
1136 /// Write a big-endian u16 (2 bytes).
1138 fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1139 extensions::u64_to_be_bytes(n as u64, 2, |v| self.write_all(v))
1142 /// Write a big-endian i64 (8 bytes).
1144 fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1145 extensions::u64_to_be_bytes(n as u64, 8, |v| self.write_all(v))
1148 /// Write a big-endian i32 (4 bytes).
1150 fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1151 extensions::u64_to_be_bytes(n as u64, 4, |v| self.write_all(v))
1154 /// Write a big-endian i16 (2 bytes).
1156 fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1157 extensions::u64_to_be_bytes(n as u64, 2, |v| self.write_all(v))
1160 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1162 fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1164 self.write_be_u64(transmute(f))
1168 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1170 fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1172 self.write_be_u32(transmute(f))
1176 /// Write a little-endian u64 (8 bytes).
1178 fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1179 extensions::u64_to_le_bytes(n, 8, |v| self.write_all(v))
1182 /// Write a little-endian u32 (4 bytes).
1184 fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1185 extensions::u64_to_le_bytes(n as u64, 4, |v| self.write_all(v))
1188 /// Write a little-endian u16 (2 bytes).
1190 fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1191 extensions::u64_to_le_bytes(n as u64, 2, |v| self.write_all(v))
1194 /// Write a little-endian i64 (8 bytes).
1196 fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1197 extensions::u64_to_le_bytes(n as u64, 8, |v| self.write_all(v))
1200 /// Write a little-endian i32 (4 bytes).
1202 fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1203 extensions::u64_to_le_bytes(n as u64, 4, |v| self.write_all(v))
1206 /// Write a little-endian i16 (2 bytes).
1208 fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1209 extensions::u64_to_le_bytes(n as u64, 2, |v| self.write_all(v))
1212 /// Write a little-endian IEEE754 double-precision floating-point
1215 fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1217 self.write_le_u64(transmute(f))
1221 /// Write a little-endian IEEE754 single-precision floating-point
1224 fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1226 self.write_le_u32(transmute(f))
1230 /// Write a u8 (1 byte).
1232 fn write_u8(&mut self, n: u8) -> IoResult<()> {
1233 self.write_all(&[n])
1236 /// Write an i8 (1 byte).
1238 fn write_i8(&mut self, n: i8) -> IoResult<()> {
1239 self.write_all(&[n as u8])
1243 /// A writer which can be converted to a RefWriter.
1244 pub trait ByRefWriter {
1245 /// Creates a wrapper around a mutable reference to the writer.
1247 /// This is useful to allow applying wrappers while still
1248 /// retaining ownership of the original value.
1250 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1253 impl<T: Writer> ByRefWriter for T {
1254 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1255 RefWriter { inner: self }
1259 impl<'a> Writer for Box<Writer+'a> {
1261 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
1262 (&mut **self).write_all(buf)
1266 fn flush(&mut self) -> IoResult<()> {
1267 (&mut **self).flush()
1271 impl<'a> Writer for &'a mut (Writer+'a) {
1273 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write_all(buf) }
1276 fn flush(&mut self) -> IoResult<()> { (**self).flush() }
1279 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1280 /// to another writer. This is often useful when composing streams.
1285 /// use std::old_io::util::TeeReader;
1286 /// use std::old_io::{stdin, ByRefWriter};
1288 /// fn process_input<R: Reader>(r: R) {}
1290 /// let mut output = Vec::new();
1293 /// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1294 /// // handle to it in the outer scope
1295 /// let mut tee = TeeReader::new(stdin(), output.by_ref());
1296 /// process_input(tee);
1299 /// println!("input processed: {:?}", output);
1301 pub struct RefWriter<'a, W:'a> {
1302 /// The underlying writer which this is referencing
1306 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1308 fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write_all(buf) }
1311 fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1315 /// A Stream is a readable and a writable object. Data written is typically
1316 /// received by the object which reads receive data from.
1317 pub trait Stream: Reader + Writer { }
1319 impl<T: Reader + Writer> Stream for T {}
1321 /// An iterator that reads a line on each iteration,
1322 /// until `.read_line()` encounters `EndOfFile`.
1324 /// # Notes about the Iteration Protocol
1326 /// The `Lines` may yield `None` and thus terminate
1327 /// an iteration, but continue to yield elements if iteration
1328 /// is attempted again.
1332 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1333 /// is returned by the iterator and should be handled by the caller.
1334 pub struct Lines<'r, T:'r> {
1338 impl<'r, T: Buffer> Iterator for Lines<'r, T> {
1339 type Item = IoResult<String>;
1341 fn next(&mut self) -> Option<IoResult<String>> {
1342 match self.buffer.read_line() {
1343 Ok(x) => Some(Ok(x)),
1344 Err(IoError { kind: EndOfFile, ..}) => None,
1345 Err(y) => Some(Err(y))
1350 /// An iterator that reads a utf8-encoded character on each iteration,
1351 /// until `.read_char()` encounters `EndOfFile`.
1353 /// # Notes about the Iteration Protocol
1355 /// The `Chars` may yield `None` and thus terminate
1356 /// an iteration, but continue to yield elements if iteration
1357 /// is attempted again.
1361 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1362 /// is returned by the iterator and should be handled by the caller.
1363 pub struct Chars<'r, T:'r> {
1367 impl<'r, T: Buffer> Iterator for Chars<'r, T> {
1368 type Item = IoResult<char>;
1370 fn next(&mut self) -> Option<IoResult<char>> {
1371 match self.buffer.read_char() {
1372 Ok(x) => Some(Ok(x)),
1373 Err(IoError { kind: EndOfFile, ..}) => None,
1374 Err(y) => Some(Err(y))
1379 /// A Buffer is a type of reader which has some form of internal buffering to
1380 /// allow certain kinds of reading operations to be more optimized than others.
1381 /// This type extends the `Reader` trait with a few methods that are not
1382 /// possible to reasonably implement with purely a read interface.
1383 pub trait Buffer: Reader {
1384 /// Fills the internal buffer of this object, returning the buffer contents.
1385 /// Note that none of the contents will be "read" in the sense that later
1386 /// calling `read` may return the same contents.
1388 /// The `consume` function must be called with the number of bytes that are
1389 /// consumed from this buffer returned to ensure that the bytes are never
1394 /// This function will return an I/O error if the underlying reader was
1395 /// read, but returned an error. Note that it is not an error to return a
1396 /// 0-length buffer.
1397 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1399 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1400 /// so they should no longer be returned in calls to `read`.
1401 fn consume(&mut self, amt: uint);
1403 /// Reads the next line of input, interpreted as a sequence of UTF-8
1404 /// encoded Unicode codepoints. If a newline is encountered, then the
1405 /// newline is contained in the returned string.
1410 /// use std::old_io::BufReader;
1412 /// let mut reader = BufReader::new(b"hello\nworld");
1413 /// assert_eq!("hello\n", &*reader.read_line().unwrap());
1418 /// This function has the same error semantics as `read_until`:
1420 /// * All non-EOF errors will be returned immediately
1421 /// * If an error is returned previously consumed bytes are lost
1422 /// * EOF is only returned if no bytes have been read
1423 /// * Reach EOF may mean that the delimiter is not present in the return
1426 /// Additionally, this function can fail if the line of input read is not a
1427 /// valid UTF-8 sequence of bytes.
1428 fn read_line(&mut self) -> IoResult<String> {
1429 self.read_until(b'\n').and_then(|line|
1430 match String::from_utf8(line) {
1432 Err(_) => Err(standard_error(InvalidInput)),
1437 /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1438 /// specified byte is encountered, reading ceases and the bytes up to and
1439 /// including the delimiter are returned.
1443 /// If any I/O error is encountered other than EOF, the error is immediately
1444 /// returned. Note that this may discard bytes which have already been read,
1445 /// and those bytes will *not* be returned. It is recommended to use other
1446 /// methods if this case is worrying.
1448 /// If EOF is encountered, then this function will return EOF if 0 bytes
1449 /// have been read, otherwise the pending byte buffer is returned. This
1450 /// is the reason that the byte buffer returned may not always contain the
1452 fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1453 let mut res = Vec::new();
1456 let (done, used) = {
1457 let available = match self.fill_buf() {
1459 Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1462 Err(e) => return Err(e)
1464 match available.iter().position(|&b| b == byte) {
1466 res.push_all(&available[..i + 1]);
1470 res.push_all(available);
1471 (false, available.len())
1482 /// Reads the next utf8-encoded character from the underlying stream.
1486 /// If an I/O error occurs, or EOF, then this function will return `Err`.
1487 /// This function will also return error if the stream does not contain a
1488 /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1489 fn read_char(&mut self) -> IoResult<char> {
1490 let first_byte = try!(self.read_byte());
1491 let width = unicode::str::utf8_char_width(first_byte);
1492 if width == 1 { return Ok(first_byte as char) }
1493 if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1494 let mut buf = [first_byte, 0, 0, 0];
1497 while start < width {
1498 match try!(self.read(&mut buf[start .. width])) {
1499 n if n == width - start => break,
1500 n if n < width - start => { start += n; }
1501 _ => return Err(standard_error(InvalidInput)),
1505 match str::from_utf8(&buf[..width]).ok() {
1506 Some(s) => Ok(s.char_at(0)),
1507 None => Err(standard_error(InvalidInput))
1512 /// Extension methods for the Buffer trait which are included in the prelude.
1513 pub trait BufferPrelude {
1514 /// Create an iterator that reads a utf8-encoded character on each iteration
1519 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1520 /// is returned by the iterator and should be handled by the caller.
1521 fn chars<'r>(&'r mut self) -> Chars<'r, Self>;
1523 /// Create an iterator that reads a line on each iteration until EOF.
1527 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1528 /// is returned by the iterator and should be handled by the caller.
1529 fn lines<'r>(&'r mut self) -> Lines<'r, Self>;
1532 impl<T: Buffer> BufferPrelude for T {
1533 fn chars<'r>(&'r mut self) -> Chars<'r, T> {
1534 Chars { buffer: self }
1537 fn lines<'r>(&'r mut self) -> Lines<'r, T> {
1538 Lines { buffer: self }
1542 /// When seeking, the resulting cursor is offset from a base by the offset given
1543 /// to the `seek` function. The base used is specified by this enumeration.
1545 pub enum SeekStyle {
1546 /// Seek from the beginning of the stream
1548 /// Seek from the end of the stream
1550 /// Seek from the current position
1554 /// An object implementing `Seek` internally has some form of cursor which can
1555 /// be moved within a stream of bytes. The stream typically has a fixed size,
1556 /// allowing seeking relative to either end.
1558 /// Return position of file cursor in the stream
1559 fn tell(&self) -> IoResult<u64>;
1561 /// Seek to an offset in a stream
1563 /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1564 /// allowed, but seeking before position 0 is not allowed.
1568 /// * Seeking to a negative offset is considered an error
1569 /// * Seeking past the end of the stream does not modify the underlying
1570 /// stream, but the next write may cause the previous data to be filled in
1571 /// with a bit pattern.
1572 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1575 /// A listener is a value that can consume itself to start listening for
1578 /// Doing so produces some sort of Acceptor.
1579 pub trait Listener<T, A: Acceptor<T>>
1580 : PhantomFn<T,T> // FIXME should be an assoc type anyhow
1582 /// Spin up the listener and start queuing incoming connections
1586 /// Returns `Err` if this listener could not be bound to listen for
1587 /// connections. In all cases, this listener is consumed.
1588 fn listen(self) -> IoResult<A>;
1591 /// An acceptor is a value that presents incoming connections
1592 pub trait Acceptor<T> {
1593 /// Wait for and accept an incoming connection
1597 /// Returns `Err` if an I/O error is encountered.
1598 fn accept(&mut self) -> IoResult<T>;
1600 /// Create an iterator over incoming connection attempts.
1602 /// Note that I/O errors will be yielded by the iterator itself.
1603 fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1604 IncomingConnections { inc: self }
1608 /// An infinite iterator over incoming connection attempts.
1609 /// Calling `next` will block the task until a connection is attempted.
1611 /// Since connection attempts can continue forever, this iterator always returns
1612 /// `Some`. The `Some` contains the `IoResult` representing whether the
1613 /// connection attempt was successful. A successful connection will be wrapped
1614 /// in `Ok`. A failed connection is represented as an `Err`.
1615 pub struct IncomingConnections<'a, A: ?Sized +'a> {
1620 impl<'a, T, A: ?Sized + Acceptor<T>> Iterator for IncomingConnections<'a, A> {
1621 type Item = IoResult<T>;
1623 fn next(&mut self) -> Option<IoResult<T>> {
1624 Some(self.inc.accept())
1628 /// Creates a standard error for a commonly used flavor of error. The `detail`
1629 /// field of the returned error will always be `None`.
1634 /// use std::old_io as io;
1636 /// let eof = io::standard_error(io::EndOfFile);
1637 /// let einval = io::standard_error(io::InvalidInput);
1639 pub fn standard_error(kind: IoErrorKind) -> IoError {
1640 let desc = match kind {
1641 EndOfFile => "end of file",
1642 IoUnavailable => "I/O is unavailable",
1643 InvalidInput => "invalid input",
1644 OtherIoError => "unknown I/O error",
1645 FileNotFound => "file not found",
1646 PermissionDenied => "permission denied",
1647 ConnectionFailed => "connection failed",
1648 Closed => "stream is closed",
1649 ConnectionRefused => "connection refused",
1650 ConnectionReset => "connection reset",
1651 ConnectionAborted => "connection aborted",
1652 NotConnected => "not connected",
1653 BrokenPipe => "broken pipe",
1654 PathAlreadyExists => "file already exists",
1655 PathDoesntExist => "no such file",
1656 MismatchedFileTypeForOperation => "mismatched file type",
1657 ResourceUnavailable => "resource unavailable",
1658 TimedOut => "operation timed out",
1659 ShortWrite(..) => "short write",
1660 NoProgress => "no progress",
1669 /// A mode specifies how a file should be opened or created. These modes are
1670 /// passed to `File::open_mode` and are used to control where the file is
1671 /// positioned when it is initially opened.
1672 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1674 /// Opens a file positioned at the beginning.
1676 /// Opens a file positioned at EOF.
1678 /// Opens a file, truncating it if it already exists.
1682 /// Access permissions with which the file should be opened. `File`s
1683 /// opened with `Read` will return an error if written to.
1684 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1685 pub enum FileAccess {
1686 /// Read-only access, requests to write will result in an error
1688 /// Write-only access, requests to read will result in an error
1690 /// Read-write access, no requests are denied by default
1694 /// Different kinds of files which can be identified by a call to stat
1695 #[derive(Copy, PartialEq, Debug, Hash, Clone)]
1697 /// This is a normal file, corresponding to `S_IFREG`
1700 /// This file is a directory, corresponding to `S_IFDIR`
1703 /// This file is a named pipe, corresponding to `S_IFIFO`
1706 /// This file is a block device, corresponding to `S_IFBLK`
1709 /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1712 /// The type of this file is not recognized as one of the other categories
1716 /// A structure used to describe metadata information about a file. This
1717 /// structure is created through the `stat` method on a `Path`.
1723 /// use std::old_io::fs::PathExtensions;
1725 /// let info = match Path::new("foo.txt").stat() {
1726 /// Ok(stat) => stat,
1727 /// Err(e) => panic!("couldn't read foo.txt: {}", e),
1730 /// println!("byte size: {}", info.size);
1732 #[derive(Copy, Hash)]
1733 pub struct FileStat {
1734 /// The size of the file, in bytes
1736 /// The kind of file this path points to (directory, file, pipe, etc.)
1738 /// The file permissions currently on the file
1739 pub perm: FilePermission,
1741 // FIXME(#10301): These time fields are pretty useless without an actual
1742 // time representation, what are the milliseconds relative
1745 /// The time that the file was created at, in platform-dependent
1748 /// The time that this file was last modified, in platform-dependent
1751 /// The time that this file was last accessed, in platform-dependent
1755 /// Information returned by stat() which is not guaranteed to be
1756 /// platform-independent. This information may be useful on some platforms,
1757 /// but it may have different meanings or no meaning at all on other
1760 /// Usage of this field is discouraged, but if access is desired then the
1761 /// fields are located here.
1762 #[unstable(feature = "io")]
1763 pub unstable: UnstableFileStat,
1766 /// This structure represents all of the possible information which can be
1767 /// returned from a `stat` syscall which is not contained in the `FileStat`
1768 /// structure. This information is not necessarily platform independent, and may
1769 /// have different meanings or no meaning at all on some platforms.
1770 #[unstable(feature = "io")]
1771 #[derive(Copy, Hash)]
1772 pub struct UnstableFileStat {
1773 /// The ID of the device containing the file.
1775 /// The file serial number.
1779 /// The number of hard links to this file.
1781 /// The user ID of the file.
1783 /// The group ID of the file.
1785 /// The optimal block size for I/O.
1787 /// The blocks allocated for this file.
1789 /// User-defined flags for the file.
1791 /// The file generation number.
1797 /// A set of permissions for a file or directory is represented by a set of
1798 /// flags which are or'd together.
1800 flags FilePermission: u32 {
1801 const USER_READ = 0o400,
1802 const USER_WRITE = 0o200,
1803 const USER_EXECUTE = 0o100,
1804 const GROUP_READ = 0o040,
1805 const GROUP_WRITE = 0o020,
1806 const GROUP_EXECUTE = 0o010,
1807 const OTHER_READ = 0o004,
1808 const OTHER_WRITE = 0o002,
1809 const OTHER_EXECUTE = 0o001,
1811 const USER_RWX = USER_READ.bits | USER_WRITE.bits | USER_EXECUTE.bits,
1812 const GROUP_RWX = GROUP_READ.bits | GROUP_WRITE.bits | GROUP_EXECUTE.bits,
1813 const OTHER_RWX = OTHER_READ.bits | OTHER_WRITE.bits | OTHER_EXECUTE.bits,
1815 /// Permissions for user owned files, equivalent to 0644 on unix-like
1817 const USER_FILE = USER_READ.bits | USER_WRITE.bits | GROUP_READ.bits | OTHER_READ.bits,
1819 /// Permissions for user owned directories, equivalent to 0755 on
1820 /// unix-like systems.
1821 const USER_DIR = USER_RWX.bits | GROUP_READ.bits | GROUP_EXECUTE.bits |
1822 OTHER_READ.bits | OTHER_EXECUTE.bits,
1824 /// Permissions for user owned executables, equivalent to 0755
1825 /// on unix-like systems.
1826 const USER_EXEC = USER_DIR.bits,
1828 /// All possible permissions enabled.
1829 const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 impl Default for FilePermission {
1836 #[stable(feature = "rust1", since = "1.0.0")]
1838 fn default() -> FilePermission { FilePermission::empty() }
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl fmt::Display for FilePermission {
1843 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1844 write!(f, "{:04o}", self.bits)
1850 use self::BadReaderBehavior::*;
1851 use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
1852 use prelude::v1::{Ok, Vec, Buffer, SliceExt};
1855 #[derive(Clone, PartialEq, Debug)]
1856 enum BadReaderBehavior {
1861 struct BadReader<T> {
1863 behavior: Vec<BadReaderBehavior>,
1866 impl<T: Reader> BadReader<T> {
1867 fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1868 BadReader { behavior: behavior, r: r }
1872 impl<T: Reader> Reader for BadReader<T> {
1873 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1874 let BadReader { ref mut behavior, ref mut r } = *self;
1876 if behavior.is_empty() {
1877 // fall back on good
1880 match (&mut **behavior)[0] {
1881 GoodBehavior(0) => (),
1882 GoodBehavior(ref mut x) => {
1886 BadBehavior(0) => (),
1887 BadBehavior(ref mut x) => {
1898 fn test_read_at_least() {
1899 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1900 vec![GoodBehavior(usize::MAX)]);
1901 let buf = &mut [0; 5];
1902 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1903 assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1904 assert!(r.read_at_least(0, buf).is_ok());
1906 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1907 vec![BadBehavior(50), GoodBehavior(usize::MAX)]);
1908 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1910 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1911 vec![BadBehavior(1), GoodBehavior(1),
1912 BadBehavior(50), GoodBehavior(usize::MAX)]);
1913 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1914 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1916 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1917 vec![BadBehavior(usize::MAX)]);
1918 assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1920 let mut r = MemReader::new(b"hello, world!".to_vec());
1921 assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1922 assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1926 fn test_push_at_least() {
1927 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1928 vec![GoodBehavior(usize::MAX)]);
1929 let mut buf = Vec::new();
1930 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1931 assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1933 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1934 vec![BadBehavior(50), GoodBehavior(usize::MAX)]);
1935 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1937 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1938 vec![BadBehavior(1), GoodBehavior(1),
1939 BadBehavior(50), GoodBehavior(usize::MAX)]);
1940 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1941 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1943 let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1944 vec![BadBehavior(usize::MAX)]);
1945 assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1947 let mut r = MemReader::new(b"hello, world!".to_vec());
1948 assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
1955 assert_eq!(format!("{}", USER_READ), "0400");
1956 assert_eq!(format!("{}", USER_FILE), "0644");
1957 assert_eq!(format!("{}", USER_EXEC), "0755");
1958 assert_eq!(format!("{}", USER_RWX), "0700");
1959 assert_eq!(format!("{}", GROUP_RWX), "0070");
1960 assert_eq!(format!("{}", OTHER_RWX), "0007");
1961 assert_eq!(format!("{}", ALL_PERMISSIONS), "0777");
1962 assert_eq!(format!("{}", USER_READ | USER_WRITE | OTHER_WRITE), "0602");
1965 fn _ensure_buffer_is_object_safe<T: Buffer>(x: &T) -> &Buffer {