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 and signal handling.
28 Some examples of obvious things you might want to do
30 * Read lines from stdin
35 for line in io::stdin().lines() {
36 print!("{}", line.unwrap());
40 * Read a complete 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)]
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;
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;
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};
109 let listener = TcpListener::bind("127.0.0.1", 80);
111 // bind the listener to the specified address
112 let mut acceptor = listener.listen();
114 fn handle_client(mut stream: TcpStream) {
116 # &mut stream; // silence unused mutability/variable warning
118 // accept connections and process them, spawning a new tasks for each one
119 for stream in acceptor.incoming() {
121 Err(e) => { /* connection failed */ }
122 Ok(stream) => spawn(proc() {
123 // connection succeeded
124 handle_client(stream)
129 // close the socket server
137 I/O is an area where nearly every operation can result in unexpected
138 errors. Errors should be painfully visible when they happen, and handling them
139 should be easy to work with. It should be convenient to handle specific I/O
140 errors, and it should also be convenient to not deal with I/O errors.
142 Rust's I/O employs a combination of techniques to reduce boilerplate
143 while still providing feedback about errors. The basic strategy:
145 * All I/O operations return `IoResult<T>` which is equivalent to
146 `Result<T, IoError>`. The `Result` type is defined in the `std::result`
148 * If the `Result` type goes unused, then the compiler will by default emit a
149 warning about the unused result. This is because `Result` has the
150 `#[must_use]` attribute.
151 * Common traits are implemented for `IoResult`, e.g.
152 `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
153 to be 'unwrapped' before use.
155 These features combine in the API to allow for expressions like
156 `File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")`
157 without having to worry about whether "diary.txt" exists or whether
158 the write succeeds. As written, if either `new` or `write_line`
159 encounters an error then the result of the entire expression will
162 If you wanted to handle the error though you might write:
165 # #![allow(unused_must_use)]
168 match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") {
169 Ok(()) => (), // succeeded
170 Err(e) => println!("failed to write to my diary: {}", e),
173 # ::std::io::fs::unlink(&Path::new("diary.txt"));
176 So what actually happens if `create` encounters an error?
177 It's important to know that what `new` returns is not a `File`
178 but an `IoResult<File>`. If the file does not open, then `new` will simply
179 return `Err(..)`. Because there is an implementation of `Writer` (the trait
180 required ultimately required for types to implement `write_line`) there is no
181 need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
182 on it. If `new` returned an `Err(..)` then the followup call to `write_line`
183 will also return an error.
187 Explicit pattern matching on `IoResult`s can get quite verbose, especially
188 when performing many I/O operations. Some examples (like those above) are
189 alleviated with extra methods implemented on `IoResult`, but others have more
190 complex interdependencies among each I/O operation.
192 The `try!` macro from `std::macros` is provided as a method of early-return
193 inside `Result`-returning functions. It expands to an early-return on `Err`
194 and otherwise unwraps the contained `Ok` value.
196 If you wanted to read several `u32`s from a file and return their product:
199 use std::io::{File, IoResult};
201 fn file_product(p: &Path) -> IoResult<u32> {
202 let mut f = File::open(p);
203 let x1 = try!(f.read_le_u32());
204 let x2 = try!(f.read_le_u32());
209 match file_product(&Path::new("numbers.bin")) {
210 Ok(x) => println!("{}", x),
211 Err(e) => println!("Failed to read numbers!")
215 With `try!` in `file_product`, each `read_le_u32` need not be directly
216 concerned with error handling; instead its caller is responsible for
217 responding to errors that may occur while attempting to read the numbers.
222 #![deny(unused_must_use)]
225 use collections::Collection;
231 use ops::{BitOr, BitAnd, Sub, Not};
232 use option::{Option, Some, None};
235 use result::{Ok, Err, Result};
237 use slice::{Vector, MutableVector, ImmutableVector};
238 use str::{Str, StrSlice};
242 use unicode::char::UnicodeChar;
246 pub use self::stdio::stdin;
247 pub use self::stdio::stdout;
248 pub use self::stdio::stderr;
249 pub use self::stdio::print;
250 pub use self::stdio::println;
252 pub use self::fs::File;
253 pub use self::timer::Timer;
254 pub use self::net::ip::IpAddr;
255 pub use self::net::tcp::TcpListener;
256 pub use self::net::tcp::TcpStream;
257 pub use self::net::udp::UdpStream;
258 pub use self::pipe::PipeStream;
259 pub use self::process::{Process, Command};
260 pub use self::tempfile::TempDir;
262 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
263 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
265 pub use self::comm_adapters::{ChanReader, ChanWriter};
267 // this comes first to get the iotest! macro
285 /// The default buffer size for various I/O operations
286 // libuv recommends 64k buffers to maximize throughput
287 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
288 static DEFAULT_BUF_SIZE: uint = 1024 * 64;
290 /// A convenient typedef of the return value of any I/O action.
291 pub type IoResult<T> = Result<T, IoError>;
293 /// The type passed to I/O condition handlers to indicate error
297 /// Is something like this sufficient? It's kind of archaic
298 #[deriving(PartialEq, Eq, Clone)]
300 /// An enumeration which can be matched against for determining the flavor
302 pub kind: IoErrorKind,
303 /// A human-readable description about the error
304 pub desc: &'static str,
305 /// Detailed information about this error, not always available
306 pub detail: Option<String>
310 /// Convert an `errno` value into an `IoError`.
312 /// If `detail` is `true`, the `detail` field of the `IoError`
313 /// struct is filled with an allocated string describing the error
314 /// in more detail, retrieved from the operating system.
315 pub fn from_errno(errno: uint, detail: bool) -> IoError {
318 fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
320 libc::EOF => (EndOfFile, "end of file"),
321 libc::ERROR_NO_DATA => (BrokenPipe, "the pipe is being closed"),
322 libc::ERROR_FILE_NOT_FOUND => (FileNotFound, "file not found"),
323 libc::ERROR_INVALID_NAME => (InvalidInput, "invalid file name"),
324 libc::WSAECONNREFUSED => (ConnectionRefused, "connection refused"),
325 libc::WSAECONNRESET => (ConnectionReset, "connection reset"),
326 libc::ERROR_ACCESS_DENIED | libc::WSAEACCES =>
327 (PermissionDenied, "permission denied"),
328 libc::WSAEWOULDBLOCK => {
329 (ResourceUnavailable, "resource temporarily unavailable")
331 libc::WSAENOTCONN => (NotConnected, "not connected"),
332 libc::WSAECONNABORTED => (ConnectionAborted, "connection aborted"),
333 libc::WSAEADDRNOTAVAIL => (ConnectionRefused, "address not available"),
334 libc::WSAEADDRINUSE => (ConnectionRefused, "address in use"),
335 libc::ERROR_BROKEN_PIPE => (EndOfFile, "the pipe has ended"),
336 libc::ERROR_OPERATION_ABORTED =>
337 (TimedOut, "operation timed out"),
338 libc::WSAEINVAL => (InvalidInput, "invalid argument"),
339 libc::ERROR_CALL_NOT_IMPLEMENTED =>
340 (IoUnavailable, "function not implemented"),
341 libc::ERROR_INVALID_HANDLE =>
342 (MismatchedFileTypeForOperation,
343 "invalid handle provided to function"),
344 libc::ERROR_NOTHING_TO_TERMINATE =>
345 (InvalidInput, "no process to kill"),
347 // libuv maps this error code to EISDIR. we do too. if it is found
348 // to be incorrect, we can add in some more machinery to only
349 // return this message when ERROR_INVALID_FUNCTION after certain
351 libc::ERROR_INVALID_FUNCTION => (InvalidInput,
352 "illegal operation on a directory"),
354 _ => (OtherIoError, "unknown error")
359 fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
360 // FIXME: this should probably be a bit more descriptive...
362 libc::EOF => (EndOfFile, "end of file"),
363 libc::ECONNREFUSED => (ConnectionRefused, "connection refused"),
364 libc::ECONNRESET => (ConnectionReset, "connection reset"),
365 libc::EPERM | libc::EACCES =>
366 (PermissionDenied, "permission denied"),
367 libc::EPIPE => (BrokenPipe, "broken pipe"),
368 libc::ENOTCONN => (NotConnected, "not connected"),
369 libc::ECONNABORTED => (ConnectionAborted, "connection aborted"),
370 libc::EADDRNOTAVAIL => (ConnectionRefused, "address not available"),
371 libc::EADDRINUSE => (ConnectionRefused, "address in use"),
372 libc::ENOENT => (FileNotFound, "no such file or directory"),
373 libc::EISDIR => (InvalidInput, "illegal operation on a directory"),
374 libc::ENOSYS => (IoUnavailable, "function not implemented"),
375 libc::EINVAL => (InvalidInput, "invalid argument"),
377 (MismatchedFileTypeForOperation,
378 "file descriptor is not a TTY"),
379 libc::ETIMEDOUT => (TimedOut, "operation timed out"),
380 libc::ECANCELED => (TimedOut, "operation aborted"),
382 // These two constants can have the same value on some systems,
383 // but different values on others, so we can't use a match
385 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
386 (ResourceUnavailable, "resource temporarily unavailable"),
388 _ => (OtherIoError, "unknown error")
392 let (kind, desc) = get_err(errno as i32);
396 detail: if detail && kind == OtherIoError {
397 Some(os::error_string(errno).as_slice().chars().map(|c| c.to_lowercase()).collect())
404 /// Retrieve the last error to occur as a (detailed) IoError.
406 /// This uses the OS `errno`, and so there should not be any task
407 /// descheduling or migration (other than that performed by the
408 /// operating system) between the call(s) for which errors are
409 /// being checked and the call of this function.
410 pub fn last_error() -> IoError {
411 IoError::from_errno(os::errno() as uint, true)
414 fn from_rtio_error(err: rtio::IoError) -> IoError {
415 let rtio::IoError { code, extra, detail } = err;
416 let mut ioerr = IoError::from_errno(code, false);
417 ioerr.detail = detail;
418 ioerr.kind = match ioerr.kind {
419 TimedOut if extra > 0 => ShortWrite(extra),
426 impl fmt::Show for IoError {
427 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
429 IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
430 write!(fmt, "{}", detail),
431 IoError { detail: None, desc, .. } =>
432 write!(fmt, "{}", desc),
433 IoError { detail: Some(ref detail), desc, .. } =>
434 write!(fmt, "{} ({})", desc, detail)
439 /// A list specifying general categories of I/O error.
440 #[deriving(PartialEq, Eq, Clone, Show)]
441 pub enum IoErrorKind {
442 /// Any I/O error not part of this list.
444 /// The operation could not complete because end of file was reached.
446 /// The file was not found.
448 /// The file permissions disallowed access to this file.
450 /// A network connection failed for some reason not specified in this list.
452 /// The network operation failed because the network connection was closed.
454 /// The connection was refused by the remote server.
456 /// The connection was reset by the remote server.
458 /// The connection was aborted (terminated) by the remote server.
460 /// The network operation failed because it was not connected yet.
462 /// The operation failed because a pipe was closed.
464 /// A file already existed with that name.
466 /// No file exists at that location.
468 /// The path did not specify the type of file that this operation required. For example,
469 /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
470 MismatchedFileTypeForOperation,
471 /// The operation temporarily failed (for example, because a signal was received), and retrying
474 /// No I/O functionality is available for this task.
476 /// A parameter was incorrect in a way that caused an I/O error not part of this list.
478 /// The I/O operation's timeout expired, causing it to be canceled.
480 /// This write operation failed to write all of its data.
482 /// Normally the write() method on a Writer guarantees that all of its data
483 /// has been written, but some operations may be terminated after only
484 /// partially writing some data. An example of this is a timed out write
485 /// which successfully wrote a known number of bytes, but bailed out after
488 /// The payload contained as part of this variant is the number of bytes
489 /// which are known to have been successfully written.
491 /// The Reader returned 0 bytes from `read()` too many times.
495 /// A trait that lets you add a `detail` to an IoError easily
496 trait UpdateIoError<T> {
497 /// Returns an IoError with updated description and detail
498 fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> Self;
500 /// Returns an IoError with updated detail
501 fn update_detail(self, detail: |&IoError| -> String) -> Self;
503 /// Returns an IoError with update description
504 fn update_desc(self, desc: &'static str) -> Self;
507 impl<T> UpdateIoError<T> for IoResult<T> {
508 fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> IoResult<T> {
509 self.map_err(|mut e| {
510 let detail = detail(&e);
512 e.detail = Some(detail);
517 fn update_detail(self, detail: |&IoError| -> String) -> IoResult<T> {
518 self.map_err(|mut e| { e.detail = Some(detail(&e)); e })
521 fn update_desc(self, desc: &'static str) -> IoResult<T> {
522 self.map_err(|mut e| { e.desc = desc; e })
526 static NO_PROGRESS_LIMIT: uint = 1000;
528 /// A trait for objects which are byte-oriented streams. Readers are defined by
529 /// one method, `read`. This function will block until data is available,
530 /// filling in the provided buffer with any data read.
532 /// Readers are intended to be composable with one another. Many objects
533 /// throughout the I/O and related libraries take and provide types which
534 /// implement the `Reader` trait.
537 // Only method which need to get implemented for this trait
539 /// Read bytes, up to the length of `buf` and place them in `buf`.
540 /// Returns the number of bytes read. The number of bytes read may
541 /// be less than the number requested, even 0. Returns `Err` on EOF.
545 /// If an error occurs during this I/O operation, then it is returned as
546 /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
547 /// inspected for in the error's `kind` field. Also note that reading 0
548 /// bytes is not considered an error in all circumstances
550 /// # Implementation Note
552 /// When implementing this method on a new Reader, you are strongly encouraged
553 /// not to return 0 if you can avoid it.
554 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
556 // Convenient helper methods based on the above methods
558 /// Reads at least `min` bytes and places them in `buf`.
559 /// Returns the number of bytes read.
561 /// This will continue to call `read` until at least `min` bytes have been
562 /// read. If `read` returns 0 too many times, `NoProgress` will be
567 /// If an error occurs at any point, that error is returned, and no further
569 fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
572 detail: Some(String::from_str("the buffer is too short")),
573 ..standard_error(InvalidInput)
580 match self.read(buf.mut_slice_from(read)) {
583 if zeroes >= NO_PROGRESS_LIMIT {
584 return Err(standard_error(NoProgress));
591 err@Err(_) => return err
598 /// Reads a single byte. Returns `Err` on EOF.
599 fn read_byte(&mut self) -> IoResult<u8> {
601 try!(self.read_at_least(1, buf));
605 /// Reads up to `len` bytes and appends them to a vector.
606 /// Returns the number of bytes read. The number of bytes read may be
607 /// less than the number requested, even 0. Returns Err on EOF.
611 /// If an error occurs during this I/O operation, then it is returned
612 /// as `Err(IoError)`. See `read()` for more details.
613 fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
614 let start_len = buf.len();
615 buf.reserve_additional(len);
618 let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
621 unsafe { buf.set_len(start_len + n) };
625 /// Reads at least `min` bytes, but no more than `len`, and appends them to
627 /// Returns the number of bytes read.
629 /// This will continue to call `read` until at least `min` bytes have been
630 /// read. If `read` returns 0 too many times, `NoProgress` will be
635 /// If an error occurs at any point, that error is returned, and no further
637 fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
640 detail: Some(String::from_str("the buffer is too short")),
641 ..standard_error(InvalidInput)
645 let start_len = buf.len();
646 buf.reserve_additional(len);
648 // we can't just use self.read_at_least(min, slice) because we need to push
649 // successful reads onto the vector before any returned errors.
654 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
655 try!(self.read_at_least(1, s))
657 unsafe { buf.set_len(start_len + read) };
662 /// Reads exactly `len` bytes and gives you back a new vector of length
667 /// Fails with the same conditions as `read`. Additionally returns error
668 /// on EOF. Note that if an error is returned, then some number of bytes may
669 /// have already been consumed from the underlying reader, and they are lost
670 /// (not returned as part of the error). If this is unacceptable, then it is
671 /// recommended to use the `push_at_least` or `read` methods.
672 fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
673 let mut buf = Vec::with_capacity(len);
674 match self.push_at_least(len, len, &mut buf) {
680 /// Reads all remaining bytes from the stream.
684 /// Returns any non-EOF error immediately. Previously read bytes are
685 /// discarded when an error is returned.
687 /// When EOF is encountered, all bytes read up to that point are returned.
688 fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
689 let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
691 match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
693 Err(ref e) if e.kind == EndOfFile => break,
694 Err(e) => return Err(e)
700 /// Reads all of the remaining bytes of this stream, interpreting them as a
701 /// UTF-8 encoded stream. The corresponding string is returned.
705 /// This function returns all of the same errors as `read_to_end` with an
706 /// additional error if the reader's contents are not a valid sequence of
708 fn read_to_string(&mut self) -> IoResult<String> {
709 self.read_to_end().and_then(|s| {
710 match String::from_utf8(s) {
712 Err(_) => Err(standard_error(InvalidInput)),
717 /// Create an iterator that reads a single byte on
718 /// each iteration, until EOF.
722 /// Any error other than `EndOfFile` that is produced by the underlying Reader
723 /// is returned by the iterator and should be handled by the caller.
724 fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self> {
725 extensions::Bytes::new(self)
728 // Byte conversion helpers
730 /// Reads `n` little-endian unsigned integer bytes.
732 /// `n` must be between 1 and 8, inclusive.
733 fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
734 assert!(nbytes > 0 && nbytes <= 8);
740 val += (try!(self.read_u8()) as u64) << pos;
747 /// Reads `n` little-endian signed integer bytes.
749 /// `n` must be between 1 and 8, inclusive.
750 fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
751 self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
754 /// Reads `n` big-endian unsigned integer bytes.
756 /// `n` must be between 1 and 8, inclusive.
757 fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
758 assert!(nbytes > 0 && nbytes <= 8);
764 val += (try!(self.read_u8()) as u64) << i * 8;
769 /// Reads `n` big-endian signed integer bytes.
771 /// `n` must be between 1 and 8, inclusive.
772 fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
773 self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
776 /// Reads a little-endian unsigned integer.
778 /// The number of bytes returned is system-dependent.
779 fn read_le_uint(&mut self) -> IoResult<uint> {
780 self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
783 /// Reads a little-endian integer.
785 /// The number of bytes returned is system-dependent.
786 fn read_le_int(&mut self) -> IoResult<int> {
787 self.read_le_int_n(int::BYTES).map(|i| i as int)
790 /// Reads a big-endian unsigned integer.
792 /// The number of bytes returned is system-dependent.
793 fn read_be_uint(&mut self) -> IoResult<uint> {
794 self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
797 /// Reads a big-endian integer.
799 /// The number of bytes returned is system-dependent.
800 fn read_be_int(&mut self) -> IoResult<int> {
801 self.read_be_int_n(int::BYTES).map(|i| i as int)
804 /// Reads a big-endian `u64`.
806 /// `u64`s are 8 bytes long.
807 fn read_be_u64(&mut self) -> IoResult<u64> {
808 self.read_be_uint_n(8)
811 /// Reads a big-endian `u32`.
813 /// `u32`s are 4 bytes long.
814 fn read_be_u32(&mut self) -> IoResult<u32> {
815 self.read_be_uint_n(4).map(|i| i as u32)
818 /// Reads a big-endian `u16`.
820 /// `u16`s are 2 bytes long.
821 fn read_be_u16(&mut self) -> IoResult<u16> {
822 self.read_be_uint_n(2).map(|i| i as u16)
825 /// Reads a big-endian `i64`.
827 /// `i64`s are 8 bytes long.
828 fn read_be_i64(&mut self) -> IoResult<i64> {
829 self.read_be_int_n(8)
832 /// Reads a big-endian `i32`.
834 /// `i32`s are 4 bytes long.
835 fn read_be_i32(&mut self) -> IoResult<i32> {
836 self.read_be_int_n(4).map(|i| i as i32)
839 /// Reads a big-endian `i16`.
841 /// `i16`s are 2 bytes long.
842 fn read_be_i16(&mut self) -> IoResult<i16> {
843 self.read_be_int_n(2).map(|i| i as i16)
846 /// Reads a big-endian `f64`.
848 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
849 fn read_be_f64(&mut self) -> IoResult<f64> {
850 self.read_be_u64().map(|i| unsafe {
851 transmute::<u64, f64>(i)
855 /// Reads a big-endian `f32`.
857 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
858 fn read_be_f32(&mut self) -> IoResult<f32> {
859 self.read_be_u32().map(|i| unsafe {
860 transmute::<u32, f32>(i)
864 /// Reads a little-endian `u64`.
866 /// `u64`s are 8 bytes long.
867 fn read_le_u64(&mut self) -> IoResult<u64> {
868 self.read_le_uint_n(8)
871 /// Reads a little-endian `u32`.
873 /// `u32`s are 4 bytes long.
874 fn read_le_u32(&mut self) -> IoResult<u32> {
875 self.read_le_uint_n(4).map(|i| i as u32)
878 /// Reads a little-endian `u16`.
880 /// `u16`s are 2 bytes long.
881 fn read_le_u16(&mut self) -> IoResult<u16> {
882 self.read_le_uint_n(2).map(|i| i as u16)
885 /// Reads a little-endian `i64`.
887 /// `i64`s are 8 bytes long.
888 fn read_le_i64(&mut self) -> IoResult<i64> {
889 self.read_le_int_n(8)
892 /// Reads a little-endian `i32`.
894 /// `i32`s are 4 bytes long.
895 fn read_le_i32(&mut self) -> IoResult<i32> {
896 self.read_le_int_n(4).map(|i| i as i32)
899 /// Reads a little-endian `i16`.
901 /// `i16`s are 2 bytes long.
902 fn read_le_i16(&mut self) -> IoResult<i16> {
903 self.read_le_int_n(2).map(|i| i as i16)
906 /// Reads a little-endian `f64`.
908 /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
909 fn read_le_f64(&mut self) -> IoResult<f64> {
910 self.read_le_u64().map(|i| unsafe {
911 transmute::<u64, f64>(i)
915 /// Reads a little-endian `f32`.
917 /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
918 fn read_le_f32(&mut self) -> IoResult<f32> {
919 self.read_le_u32().map(|i| unsafe {
920 transmute::<u32, f32>(i)
926 /// `u8`s are 1 byte.
927 fn read_u8(&mut self) -> IoResult<u8> {
933 /// `i8`s are 1 byte.
934 fn read_i8(&mut self) -> IoResult<i8> {
935 self.read_byte().map(|i| i as i8)
938 /// Creates a wrapper around a mutable reference to the reader.
940 /// This is useful to allow applying adaptors while still
941 /// retaining ownership of the original value.
942 fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self> {
943 RefReader { inner: self }
947 impl Reader for Box<Reader> {
948 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
951 impl<'a> Reader for &'a mut Reader {
952 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
955 /// Returns a slice of `v` between `start` and `end`.
957 /// Similar to `slice()` except this function only bounds the slice on the
958 /// capacity of `v`, not the length.
962 /// Fails when `start` or `end` point outside the capacity of `v`, or when
964 // Private function here because we aren't sure if we want to expose this as
965 // API yet. If so, it should be a method on Vec.
966 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
970 assert!(start <= end);
971 assert!(end <= v.capacity());
973 data: v.as_ptr().offset(start as int),
978 /// A `RefReader` is a struct implementing `Reader` which contains a reference
979 /// to another reader. This is often useful when composing streams.
985 /// # fn process_input<R: Reader>(r: R) {}
988 /// use std::io::util::LimitReader;
990 /// let mut stream = io::stdin();
992 /// // Only allow the function to process at most one kilobyte of input
994 /// let stream = LimitReader::new(stream.by_ref(), 1024);
995 /// process_input(stream);
998 /// // 'stream' is still available for use here
1002 pub struct RefReader<'a, R> {
1003 /// The underlying reader which this is referencing
1007 impl<'a, R: Reader> Reader for RefReader<'a, R> {
1008 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
1011 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
1012 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { self.inner.fill_buf() }
1013 fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
1016 fn extend_sign(val: u64, nbytes: uint) -> i64 {
1017 let shift = (8 - nbytes) * 8;
1018 (val << shift) as i64 >> shift
1021 /// A trait for objects which are byte-oriented streams. Writers are defined by
1022 /// one method, `write`. This function will block until the provided buffer of
1023 /// bytes has been entirely written, and it will return any failures which occur.
1025 /// Another commonly overridden method is the `flush` method for writers such as
1026 /// buffered writers.
1028 /// Writers are intended to be composable with one another. Many objects
1029 /// throughout the I/O and related libraries take and provide types which
1030 /// implement the `Writer` trait.
1032 /// Write the entirety of a given buffer
1036 /// If an error happens during the I/O operation, the error is returned as
1037 /// `Err`. Note that it is considered an error if the entire buffer could
1038 /// not be written, and if an error is returned then it is unknown how much
1039 /// data (if any) was actually written.
1040 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
1042 /// Flush this output stream, ensuring that all intermediately buffered
1043 /// contents reach their destination.
1045 /// This is by default a no-op and implementers of the `Writer` trait should
1046 /// decide whether their stream needs to be buffered or not.
1047 fn flush(&mut self) -> IoResult<()> { Ok(()) }
1049 /// Writes a formatted string into this writer, returning any error
1052 /// This method is primarily used to interface with the `format_args!`
1053 /// macro, but it is rare that this should explicitly be called. The
1054 /// `write!` macro should be favored to invoke this method instead.
1058 /// This function will return any I/O error reported while formatting.
1059 fn write_fmt(&mut self, fmt: &fmt::Arguments) -> IoResult<()> {
1060 // Create a shim which translates a Writer to a FormatWriter and saves
1061 // off I/O errors. instead of discarding them
1062 struct Adaptor<'a, T> {
1064 error: IoResult<()>,
1066 impl<'a, T: Writer> fmt::FormatWriter for Adaptor<'a, T> {
1067 fn write(&mut self, bytes: &[u8]) -> fmt::Result {
1068 match self.inner.write(bytes) {
1071 self.error = Err(e);
1072 Err(fmt::WriteError)
1078 let mut output = Adaptor { inner: self, error: Ok(()) };
1079 match fmt::write(&mut output, fmt) {
1081 Err(..) => output.error
1085 /// Write a rust string into this sink.
1087 /// The bytes written will be the UTF-8 encoded version of the input string.
1088 /// If other encodings are desired, it is recommended to compose this stream
1089 /// with another performing the conversion, or to use `write` with a
1090 /// converted byte-array instead.
1092 fn write_str(&mut self, s: &str) -> IoResult<()> {
1093 self.write(s.as_bytes())
1096 /// Writes a string into this sink, and then writes a literal newline (`\n`)
1097 /// byte afterwards. Note that the writing of the newline is *not* atomic in
1098 /// the sense that the call to `write` is invoked twice (once with the
1099 /// string and once with a newline character).
1101 /// If other encodings or line ending flavors are desired, it is recommended
1102 /// that the `write` method is used specifically instead.
1104 fn write_line(&mut self, s: &str) -> IoResult<()> {
1105 self.write_str(s).and_then(|()| self.write(['\n' as u8]))
1108 /// Write a single char, encoded as UTF-8.
1110 fn write_char(&mut self, c: char) -> IoResult<()> {
1111 let mut buf = [0u8, ..4];
1112 let n = c.encode_utf8(buf.as_mut_slice());
1113 self.write(buf.slice_to(n))
1116 /// Write the result of passing n through `int::to_str_bytes`.
1118 fn write_int(&mut self, n: int) -> IoResult<()> {
1119 write!(self, "{:d}", n)
1122 /// Write the result of passing n through `uint::to_str_bytes`.
1124 fn write_uint(&mut self, n: uint) -> IoResult<()> {
1125 write!(self, "{:u}", n)
1128 /// Write a little-endian uint (number of bytes depends on system).
1130 fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1131 extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
1134 /// Write a little-endian int (number of bytes depends on system).
1136 fn write_le_int(&mut self, n: int) -> IoResult<()> {
1137 extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
1140 /// Write a big-endian uint (number of bytes depends on system).
1142 fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1143 extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
1146 /// Write a big-endian int (number of bytes depends on system).
1148 fn write_be_int(&mut self, n: int) -> IoResult<()> {
1149 extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
1152 /// Write a big-endian u64 (8 bytes).
1154 fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1155 extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
1158 /// Write a big-endian u32 (4 bytes).
1160 fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1161 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1164 /// Write a big-endian u16 (2 bytes).
1166 fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1167 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1170 /// Write a big-endian i64 (8 bytes).
1172 fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1173 extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1176 /// Write a big-endian i32 (4 bytes).
1178 fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1179 extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1182 /// Write a big-endian i16 (2 bytes).
1184 fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1185 extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1188 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1190 fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1192 self.write_be_u64(transmute(f))
1196 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1198 fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1200 self.write_be_u32(transmute(f))
1204 /// Write a little-endian u64 (8 bytes).
1206 fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1207 extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
1210 /// Write a little-endian u32 (4 bytes).
1212 fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1213 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1216 /// Write a little-endian u16 (2 bytes).
1218 fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1219 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1222 /// Write a little-endian i64 (8 bytes).
1224 fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1225 extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1228 /// Write a little-endian i32 (4 bytes).
1230 fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1231 extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1234 /// Write a little-endian i16 (2 bytes).
1236 fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1237 extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1240 /// Write a little-endian IEEE754 double-precision floating-point
1243 fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1245 self.write_le_u64(transmute(f))
1249 /// Write a little-endian IEEE754 single-precision floating-point
1252 fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1254 self.write_le_u32(transmute(f))
1258 /// Write a u8 (1 byte).
1260 fn write_u8(&mut self, n: u8) -> IoResult<()> {
1264 /// Write an i8 (1 byte).
1266 fn write_i8(&mut self, n: i8) -> IoResult<()> {
1267 self.write([n as u8])
1270 /// Creates a wrapper around a mutable reference to the writer.
1272 /// This is useful to allow applying wrappers while still
1273 /// retaining ownership of the original value.
1275 fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self> {
1276 RefWriter { inner: self }
1280 impl Writer for Box<Writer> {
1282 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
1285 fn flush(&mut self) -> IoResult<()> { self.flush() }
1288 impl<'a> Writer for &'a mut Writer {
1290 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
1293 fn flush(&mut self) -> IoResult<()> { self.flush() }
1296 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1297 /// to another writer. This is often useful when composing streams.
1303 /// # fn process_input<R: Reader>(r: R) {}
1305 /// use std::io::util::TeeReader;
1306 /// use std::io::{stdin, MemWriter};
1308 /// let mut output = MemWriter::new();
1311 /// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1312 /// // handle to it in the outer scope
1313 /// let mut tee = TeeReader::new(stdin(), output.by_ref());
1314 /// process_input(tee);
1317 /// println!("input processed: {}", output.unwrap());
1320 pub struct RefWriter<'a, W> {
1321 /// The underlying writer which this is referencing
1325 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1327 fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
1330 fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1334 /// A Stream is a readable and a writable object. Data written is typically
1335 /// received by the object which reads receive data from.
1336 pub trait Stream: Reader + Writer { }
1338 impl<T: Reader + Writer> Stream for T {}
1340 /// An iterator that reads a line on each iteration,
1341 /// until `.read_line()` encounters `EndOfFile`.
1343 /// # Notes about the Iteration Protocol
1345 /// The `Lines` may yield `None` and thus terminate
1346 /// an iteration, but continue to yield elements if iteration
1347 /// is attempted again.
1351 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1352 /// is returned by the iterator and should be handled by the caller.
1353 pub struct Lines<'r, T> {
1357 impl<'r, T: Buffer> Iterator<IoResult<String>> for Lines<'r, T> {
1358 fn next(&mut self) -> Option<IoResult<String>> {
1359 match self.buffer.read_line() {
1360 Ok(x) => Some(Ok(x)),
1361 Err(IoError { kind: EndOfFile, ..}) => None,
1362 Err(y) => Some(Err(y))
1367 /// An iterator that reads a utf8-encoded character on each iteration,
1368 /// until `.read_char()` encounters `EndOfFile`.
1370 /// # Notes about the Iteration Protocol
1372 /// The `Chars` may yield `None` and thus terminate
1373 /// an iteration, but continue to yield elements if iteration
1374 /// is attempted again.
1378 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1379 /// is returned by the iterator and should be handled by the caller.
1380 pub struct Chars<'r, T> {
1384 impl<'r, T: Buffer> Iterator<IoResult<char>> for Chars<'r, T> {
1385 fn next(&mut self) -> Option<IoResult<char>> {
1386 match self.buffer.read_char() {
1387 Ok(x) => Some(Ok(x)),
1388 Err(IoError { kind: EndOfFile, ..}) => None,
1389 Err(y) => Some(Err(y))
1394 /// A Buffer is a type of reader which has some form of internal buffering to
1395 /// allow certain kinds of reading operations to be more optimized than others.
1396 /// This type extends the `Reader` trait with a few methods that are not
1397 /// possible to reasonably implement with purely a read interface.
1398 pub trait Buffer: Reader {
1399 /// Fills the internal buffer of this object, returning the buffer contents.
1400 /// Note that none of the contents will be "read" in the sense that later
1401 /// calling `read` may return the same contents.
1403 /// The `consume` function must be called with the number of bytes that are
1404 /// consumed from this buffer returned to ensure that the bytes are never
1409 /// This function will return an I/O error if the underlying reader was
1410 /// read, but returned an error. Note that it is not an error to return a
1411 /// 0-length buffer.
1412 fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1414 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1415 /// so they should no longer be returned in calls to `read`.
1416 fn consume(&mut self, amt: uint);
1418 /// Reads the next line of input, interpreted as a sequence of UTF-8
1419 /// encoded unicode codepoints. If a newline is encountered, then the
1420 /// newline is contained in the returned string.
1427 /// let mut reader = io::stdin();
1428 /// let input = reader.read_line().ok().unwrap_or("nothing".to_string());
1433 /// This function has the same error semantics as `read_until`:
1435 /// * All non-EOF errors will be returned immediately
1436 /// * If an error is returned previously consumed bytes are lost
1437 /// * EOF is only returned if no bytes have been read
1438 /// * Reach EOF may mean that the delimiter is not present in the return
1441 /// Additionally, this function can fail if the line of input read is not a
1442 /// valid UTF-8 sequence of bytes.
1443 fn read_line(&mut self) -> IoResult<String> {
1444 self.read_until('\n' as u8).and_then(|line|
1445 match String::from_utf8(line) {
1447 Err(_) => Err(standard_error(InvalidInput)),
1452 /// Create an iterator that reads a line on each iteration until EOF.
1456 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1457 /// is returned by the iterator and should be handled by the caller.
1458 fn lines<'r>(&'r mut self) -> Lines<'r, Self> {
1459 Lines { buffer: self }
1462 /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1463 /// specified byte is encountered, reading ceases and the bytes up to and
1464 /// including the delimiter are returned.
1468 /// If any I/O error is encountered other than EOF, the error is immediately
1469 /// returned. Note that this may discard bytes which have already been read,
1470 /// and those bytes will *not* be returned. It is recommended to use other
1471 /// methods if this case is worrying.
1473 /// If EOF is encountered, then this function will return EOF if 0 bytes
1474 /// have been read, otherwise the pending byte buffer is returned. This
1475 /// is the reason that the byte buffer returned may not always contain the
1477 fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1478 let mut res = Vec::new();
1483 let available = match self.fill_buf() {
1485 Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1489 Err(e) => return Err(e)
1491 match available.iter().position(|&b| b == byte) {
1493 res.push_all(available.slice_to(i + 1));
1498 res.push_all(available);
1499 used = available.len();
1509 /// Reads the next utf8-encoded character from the underlying stream.
1513 /// If an I/O error occurs, or EOF, then this function will return `Err`.
1514 /// This function will also return error if the stream does not contain a
1515 /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1516 fn read_char(&mut self) -> IoResult<char> {
1517 let first_byte = try!(self.read_byte());
1518 let width = str::utf8_char_width(first_byte);
1519 if width == 1 { return Ok(first_byte as char) }
1520 if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1521 let mut buf = [first_byte, 0, 0, 0];
1524 while start < width {
1525 match try!(self.read(buf.mut_slice(start, width))) {
1526 n if n == width - start => break,
1527 n if n < width - start => { start += n; }
1528 _ => return Err(standard_error(InvalidInput)),
1532 match str::from_utf8(buf.slice_to(width)) {
1533 Some(s) => Ok(s.char_at(0)),
1534 None => Err(standard_error(InvalidInput))
1538 /// Create an iterator that reads a utf8-encoded character on each iteration
1543 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1544 /// is returned by the iterator and should be handled by the caller.
1545 fn chars<'r>(&'r mut self) -> Chars<'r, Self> {
1546 Chars { buffer: self }
1550 /// When seeking, the resulting cursor is offset from a base by the offset given
1551 /// to the `seek` function. The base used is specified by this enumeration.
1552 pub enum SeekStyle {
1553 /// Seek from the beginning of the stream
1555 /// Seek from the end of the stream
1557 /// Seek from the current position
1561 /// An object implementing `Seek` internally has some form of cursor which can
1562 /// be moved within a stream of bytes. The stream typically has a fixed size,
1563 /// allowing seeking relative to either end.
1565 /// Return position of file cursor in the stream
1566 fn tell(&self) -> IoResult<u64>;
1568 /// Seek to an offset in a stream
1570 /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1571 /// allowed, but seeking before position 0 is not allowed.
1575 /// * Seeking to a negative offset is considered an error
1576 /// * Seeking past the end of the stream does not modify the underlying
1577 /// stream, but the next write may cause the previous data to be filled in
1578 /// with a bit pattern.
1579 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1582 /// A listener is a value that can consume itself to start listening for
1585 /// Doing so produces some sort of Acceptor.
1586 pub trait Listener<T, A: Acceptor<T>> {
1587 /// Spin up the listener and start queuing incoming connections
1591 /// Returns `Err` if this listener could not be bound to listen for
1592 /// connections. In all cases, this listener is consumed.
1593 fn listen(self) -> IoResult<A>;
1596 /// An acceptor is a value that presents incoming connections
1597 pub trait Acceptor<T> {
1598 /// Wait for and accept an incoming connection
1602 /// Returns `Err` if an I/O error is encountered.
1603 fn accept(&mut self) -> IoResult<T>;
1605 /// Create an iterator over incoming connection attempts.
1607 /// Note that I/O errors will be yielded by the iterator itself.
1608 fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1609 IncomingConnections { inc: self }
1613 /// An infinite iterator over incoming connection attempts.
1614 /// Calling `next` will block the task until a connection is attempted.
1616 /// Since connection attempts can continue forever, this iterator always returns
1617 /// `Some`. The `Some` contains the `IoResult` representing whether the
1618 /// connection attempt was successful. A successful connection will be wrapped
1619 /// in `Ok`. A failed connection is represented as an `Err`.
1620 pub struct IncomingConnections<'a, A> {
1624 impl<'a, T, A: Acceptor<T>> Iterator<IoResult<T>> for IncomingConnections<'a, A> {
1625 fn next(&mut self) -> Option<IoResult<T>> {
1626 Some(self.inc.accept())
1630 /// Creates a standard error for a commonly used flavor of error. The `detail`
1631 /// field of the returned error will always be `None`.
1638 /// let eof = io::standard_error(io::EndOfFile);
1639 /// let einval = io::standard_error(io::InvalidInput);
1641 pub fn standard_error(kind: IoErrorKind) -> IoError {
1642 let desc = match kind {
1643 EndOfFile => "end of file",
1644 IoUnavailable => "I/O is unavailable",
1645 InvalidInput => "invalid input",
1646 OtherIoError => "unknown I/O error",
1647 FileNotFound => "file not found",
1648 PermissionDenied => "permission denied",
1649 ConnectionFailed => "connection failed",
1650 Closed => "stream is closed",
1651 ConnectionRefused => "connection refused",
1652 ConnectionReset => "connection reset",
1653 ConnectionAborted => "connection aborted",
1654 NotConnected => "not connected",
1655 BrokenPipe => "broken pipe",
1656 PathAlreadyExists => "file already exists",
1657 PathDoesntExist => "no such file",
1658 MismatchedFileTypeForOperation => "mismatched file type",
1659 ResourceUnavailable => "resource unavailable",
1660 TimedOut => "operation timed out",
1661 ShortWrite(..) => "short write",
1662 NoProgress => "no progress",
1671 /// A mode specifies how a file should be opened or created. These modes are
1672 /// passed to `File::open_mode` and are used to control where the file is
1673 /// positioned when it is initially opened.
1675 /// Opens a file positioned at the beginning.
1677 /// Opens a file positioned at EOF.
1679 /// Opens a file, truncating it if it already exists.
1683 /// Access permissions with which the file should be opened. `File`s
1684 /// opened with `Read` will return an error if written to.
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 #[deriving(PartialEq, Show, Hash)]
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`.
1724 /// let info = match Path::new("foo.txt").stat() {
1725 /// Ok(stat) => stat,
1726 /// Err(e) => fail!("couldn't read foo.txt: {}", e),
1729 /// println!("byte size: {}", info.size);
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.
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.
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.
1796 #[doc="A set of permissions for a file or directory is represented
1797 by a set of flags which are or'd together."]
1800 flags FilePermission: u32 {
1801 static UserRead = 0o400,
1802 static UserWrite = 0o200,
1803 static UserExecute = 0o100,
1804 static GroupRead = 0o040,
1805 static GroupWrite = 0o020,
1806 static GroupExecute = 0o010,
1807 static OtherRead = 0o004,
1808 static OtherWrite = 0o002,
1809 static OtherExecute = 0o001,
1811 static UserRWX = UserRead.bits | UserWrite.bits | UserExecute.bits,
1812 static GroupRWX = GroupRead.bits | GroupWrite.bits | GroupExecute.bits,
1813 static OtherRWX = OtherRead.bits | OtherWrite.bits | OtherExecute.bits,
1815 #[doc="Permissions for user owned files, equivalent to 0644 on
1816 unix-like systems."]
1817 static UserFile = UserRead.bits | UserWrite.bits | GroupRead.bits | OtherRead.bits,
1819 #[doc="Permissions for user owned directories, equivalent to 0755 on
1820 unix-like systems."]
1821 static UserDir = UserRWX.bits | GroupRead.bits | GroupExecute.bits |
1822 OtherRead.bits | OtherExecute.bits,
1824 #[doc="Permissions for user owned executables, equivalent to 0755
1825 on unix-like systems."]
1826 static UserExec = UserDir.bits,
1828 #[doc="All possible permissions enabled."]
1829 static AllPermissions = UserRWX.bits | GroupRWX.bits | OtherRWX.bits
1835 use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput};
1839 #[deriving(Clone, PartialEq, Show)]
1840 enum BadReaderBehavior {
1845 struct BadReader<T> {
1847 behavior: Vec<BadReaderBehavior>,
1850 impl<T: Reader> BadReader<T> {
1851 fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1852 BadReader { behavior: behavior, r: r }
1856 impl<T: Reader> Reader for BadReader<T> {
1857 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1858 let BadReader { ref mut behavior, ref mut r } = *self;
1860 if behavior.is_empty() {
1861 // fall back on good
1864 match behavior.as_mut_slice()[0] {
1865 GoodBehavior(0) => (),
1866 GoodBehavior(ref mut x) => {
1870 BadBehavior(0) => (),
1871 BadBehavior(ref mut x) => {
1882 fn test_read_at_least() {
1883 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1884 Vec::from_slice([GoodBehavior(uint::MAX)]));
1885 let mut buf = [0u8, ..5];
1886 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1887 assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1888 assert!(r.read_at_least(0, buf).is_ok());
1890 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1891 Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
1892 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1894 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1895 Vec::from_slice([BadBehavior(1), GoodBehavior(1),
1896 BadBehavior(50), GoodBehavior(uint::MAX)]));
1897 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1898 assert!(r.read_at_least(1, buf).unwrap() >= 1);
1900 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1901 Vec::from_slice([BadBehavior(uint::MAX)]));
1902 assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1904 let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
1905 assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1906 assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1910 fn test_push_at_least() {
1911 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1912 Vec::from_slice([GoodBehavior(uint::MAX)]));
1913 let mut buf = Vec::new();
1914 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1915 assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1917 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1918 Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
1919 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1921 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1922 Vec::from_slice([BadBehavior(1), GoodBehavior(1),
1923 BadBehavior(50), GoodBehavior(uint::MAX)]));
1924 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1925 assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1927 let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1928 Vec::from_slice([BadBehavior(uint::MAX)]));
1929 assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1931 let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
1932 assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);