]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
auto merge of #17002 : tari/rust/std-mut-ref-slice, r=alexcrichton
[rust.git] / src / libstd / io / mod.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15883
12
13 // FIXME: cover these topics:
14 //        path, reader, writer, stream, raii (close not needed),
15 //        stdio, print!, println!, file access, process spawning,
16 //        error handling
17
18
19 /*! I/O, including files, networking, timers, and processes
20
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.
25
26 # Examples
27
28 Some examples of obvious things you might want to do
29
30 * Read lines from stdin
31
32     ```rust
33     use std::io;
34
35     for line in io::stdin().lines() {
36         print!("{}", line.unwrap());
37     }
38     ```
39
40 * Read a complete file
41
42     ```rust
43     use std::io::File;
44
45     let contents = File::open(&Path::new("message.txt")).read_to_end();
46     ```
47
48 * Write a line to a file
49
50     ```rust
51     # #![allow(unused_must_use)]
52     use std::io::File;
53
54     let mut file = File::create(&Path::new("message.txt"));
55     file.write(b"hello, file!\n");
56     # drop(file);
57     # ::std::io::fs::unlink(&Path::new("message.txt"));
58     ```
59
60 * Iterate over the lines of a file
61
62     ```rust,no_run
63     use std::io::BufferedReader;
64     use std::io::File;
65
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());
70     }
71     ```
72
73 * Pull the lines of a file into a vector of strings
74
75     ```rust,no_run
76     use std::io::BufferedReader;
77     use std::io::File;
78
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();
82     ```
83
84 * Make a simple TCP client connection and request
85
86     ```rust
87     # #![allow(unused_must_use)]
88     use std::io::TcpStream;
89
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)
93     # if false {
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();
97     # }
98     ```
99
100 * Make a simple TCP server
101
102     ```rust
103     # fn main() { }
104     # fn foo() {
105     # #![allow(dead_code)]
106     use std::io::{TcpListener, TcpStream};
107     use std::io::{Acceptor, Listener};
108
109     let listener = TcpListener::bind("127.0.0.1", 80);
110
111     // bind the listener to the specified address
112     let mut acceptor = listener.listen();
113
114     fn handle_client(mut stream: TcpStream) {
115         // ...
116     # &mut stream; // silence unused mutability/variable warning
117     }
118     // accept connections and process them, spawning a new tasks for each one
119     for stream in acceptor.incoming() {
120         match stream {
121             Err(e) => { /* connection failed */ }
122             Ok(stream) => spawn(proc() {
123                 // connection succeeded
124                 handle_client(stream)
125             })
126         }
127     }
128
129     // close the socket server
130     drop(acceptor);
131     # }
132     ```
133
134
135 # Error Handling
136
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.
141
142 Rust's I/O employs a combination of techniques to reduce boilerplate
143 while still providing feedback about errors. The basic strategy:
144
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`
147   module.
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.
154
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
160 be an error.
161
162 If you wanted to handle the error though you might write:
163
164 ```rust
165 # #![allow(unused_must_use)]
166 use std::io::File;
167
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),
171 }
172
173 # ::std::io::fs::unlink(&Path::new("diary.txt"));
174 ```
175
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.
184
185 ## `try!`
186
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.
191
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.
195
196 If you wanted to read several `u32`s from a file and return their product:
197
198 ```rust
199 use std::io::{File, IoResult};
200
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());
205
206     Ok(x1 * x2)
207 }
208
209 match file_product(&Path::new("numbers.bin")) {
210     Ok(x) => println!("{}", x),
211     Err(e) => println!("Failed to read numbers!")
212 }
213 ```
214
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.
218
219 */
220
221 #![experimental]
222 #![deny(unused_must_use)]
223
224 use char::Char;
225 use collections::Collection;
226 use default::Default;
227 use fmt;
228 use int;
229 use iter::Iterator;
230 use libc;
231 use mem::transmute;
232 use ops::{BitOr, BitAnd, Sub, Not};
233 use option::{Option, Some, None};
234 use os;
235 use boxed::Box;
236 use result::{Ok, Err, Result};
237 use rt::rtio;
238 use slice::{Slice, MutableSlice, ImmutableSlice};
239 use str::{Str, StrSlice};
240 use str;
241 use string::String;
242 use uint;
243 use unicode::char::UnicodeChar;
244 use vec::Vec;
245
246 // Reexports
247 pub use self::stdio::stdin;
248 pub use self::stdio::stdout;
249 pub use self::stdio::stderr;
250 pub use self::stdio::print;
251 pub use self::stdio::println;
252
253 pub use self::fs::File;
254 pub use self::timer::Timer;
255 pub use self::net::ip::IpAddr;
256 pub use self::net::tcp::TcpListener;
257 pub use self::net::tcp::TcpStream;
258 pub use self::net::udp::UdpStream;
259 pub use self::pipe::PipeStream;
260 pub use self::process::{Process, Command};
261 pub use self::tempfile::TempDir;
262
263 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
264 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
265                          LineBufferedWriter};
266 pub use self::comm_adapters::{ChanReader, ChanWriter};
267
268 // this comes first to get the iotest! macro
269 pub mod test;
270
271 mod buffered;
272 mod comm_adapters;
273 mod mem;
274 mod result;
275 mod tempfile;
276 pub mod extensions;
277 pub mod fs;
278 pub mod net;
279 pub mod pipe;
280 pub mod process;
281 pub mod signal;
282 pub mod stdio;
283 pub mod timer;
284 pub mod util;
285
286 /// The default buffer size for various I/O operations
287 // libuv recommends 64k buffers to maximize throughput
288 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
289 static DEFAULT_BUF_SIZE: uint = 1024 * 64;
290
291 /// A convenient typedef of the return value of any I/O action.
292 pub type IoResult<T> = Result<T, IoError>;
293
294 /// The type passed to I/O condition handlers to indicate error
295 ///
296 /// # FIXME
297 ///
298 /// Is something like this sufficient? It's kind of archaic
299 #[deriving(PartialEq, Eq, Clone)]
300 pub struct IoError {
301     /// An enumeration which can be matched against for determining the flavor
302     /// of error.
303     pub kind: IoErrorKind,
304     /// A human-readable description about the error
305     pub desc: &'static str,
306     /// Detailed information about this error, not always available
307     pub detail: Option<String>
308 }
309
310 impl IoError {
311     /// Convert an `errno` value into an `IoError`.
312     ///
313     /// If `detail` is `true`, the `detail` field of the `IoError`
314     /// struct is filled with an allocated string describing the error
315     /// in more detail, retrieved from the operating system.
316     pub fn from_errno(errno: uint, detail: bool) -> IoError {
317
318         #[cfg(windows)]
319         fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
320             match errno {
321                 libc::EOF => (EndOfFile, "end of file"),
322                 libc::ERROR_NO_DATA => (BrokenPipe, "the pipe is being closed"),
323                 libc::ERROR_FILE_NOT_FOUND => (FileNotFound, "file not found"),
324                 libc::ERROR_INVALID_NAME => (InvalidInput, "invalid file name"),
325                 libc::WSAECONNREFUSED => (ConnectionRefused, "connection refused"),
326                 libc::WSAECONNRESET => (ConnectionReset, "connection reset"),
327                 libc::ERROR_ACCESS_DENIED | libc::WSAEACCES =>
328                     (PermissionDenied, "permission denied"),
329                 libc::WSAEWOULDBLOCK => {
330                     (ResourceUnavailable, "resource temporarily unavailable")
331                 }
332                 libc::WSAENOTCONN => (NotConnected, "not connected"),
333                 libc::WSAECONNABORTED => (ConnectionAborted, "connection aborted"),
334                 libc::WSAEADDRNOTAVAIL => (ConnectionRefused, "address not available"),
335                 libc::WSAEADDRINUSE => (ConnectionRefused, "address in use"),
336                 libc::ERROR_BROKEN_PIPE => (EndOfFile, "the pipe has ended"),
337                 libc::ERROR_OPERATION_ABORTED =>
338                     (TimedOut, "operation timed out"),
339                 libc::WSAEINVAL => (InvalidInput, "invalid argument"),
340                 libc::ERROR_CALL_NOT_IMPLEMENTED =>
341                     (IoUnavailable, "function not implemented"),
342                 libc::ERROR_INVALID_HANDLE =>
343                     (MismatchedFileTypeForOperation,
344                      "invalid handle provided to function"),
345                 libc::ERROR_NOTHING_TO_TERMINATE =>
346                     (InvalidInput, "no process to kill"),
347
348                 // libuv maps this error code to EISDIR. we do too. if it is found
349                 // to be incorrect, we can add in some more machinery to only
350                 // return this message when ERROR_INVALID_FUNCTION after certain
351                 // Windows calls.
352                 libc::ERROR_INVALID_FUNCTION => (InvalidInput,
353                                                  "illegal operation on a directory"),
354
355                 _ => (OtherIoError, "unknown error")
356             }
357         }
358
359         #[cfg(not(windows))]
360         fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
361             // FIXME: this should probably be a bit more descriptive...
362             match errno {
363                 libc::EOF => (EndOfFile, "end of file"),
364                 libc::ECONNREFUSED => (ConnectionRefused, "connection refused"),
365                 libc::ECONNRESET => (ConnectionReset, "connection reset"),
366                 libc::EPERM | libc::EACCES =>
367                     (PermissionDenied, "permission denied"),
368                 libc::EPIPE => (BrokenPipe, "broken pipe"),
369                 libc::ENOTCONN => (NotConnected, "not connected"),
370                 libc::ECONNABORTED => (ConnectionAborted, "connection aborted"),
371                 libc::EADDRNOTAVAIL => (ConnectionRefused, "address not available"),
372                 libc::EADDRINUSE => (ConnectionRefused, "address in use"),
373                 libc::ENOENT => (FileNotFound, "no such file or directory"),
374                 libc::EISDIR => (InvalidInput, "illegal operation on a directory"),
375                 libc::ENOSYS => (IoUnavailable, "function not implemented"),
376                 libc::EINVAL => (InvalidInput, "invalid argument"),
377                 libc::ENOTTY =>
378                     (MismatchedFileTypeForOperation,
379                      "file descriptor is not a TTY"),
380                 libc::ETIMEDOUT => (TimedOut, "operation timed out"),
381                 libc::ECANCELED => (TimedOut, "operation aborted"),
382
383                 // These two constants can have the same value on some systems,
384                 // but different values on others, so we can't use a match
385                 // clause
386                 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
387                     (ResourceUnavailable, "resource temporarily unavailable"),
388
389                 _ => (OtherIoError, "unknown error")
390             }
391         }
392
393         let (kind, desc) = get_err(errno as i32);
394         IoError {
395             kind: kind,
396             desc: desc,
397             detail: if detail && kind == OtherIoError {
398                 Some(os::error_string(errno).as_slice().chars().map(|c| c.to_lowercase()).collect())
399             } else {
400                 None
401             },
402         }
403     }
404
405     /// Retrieve the last error to occur as a (detailed) IoError.
406     ///
407     /// This uses the OS `errno`, and so there should not be any task
408     /// descheduling or migration (other than that performed by the
409     /// operating system) between the call(s) for which errors are
410     /// being checked and the call of this function.
411     pub fn last_error() -> IoError {
412         IoError::from_errno(os::errno() as uint, true)
413     }
414
415     fn from_rtio_error(err: rtio::IoError) -> IoError {
416         let rtio::IoError { code, extra, detail } = err;
417         let mut ioerr = IoError::from_errno(code, false);
418         ioerr.detail = detail;
419         ioerr.kind = match ioerr.kind {
420             TimedOut if extra > 0 => ShortWrite(extra),
421             k => k,
422         };
423         return ioerr;
424     }
425 }
426
427 impl fmt::Show for IoError {
428     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
429         match *self {
430             IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
431                 write!(fmt, "{}", detail),
432             IoError { detail: None, desc, .. } =>
433                 write!(fmt, "{}", desc),
434             IoError { detail: Some(ref detail), desc, .. } =>
435                 write!(fmt, "{} ({})", desc, detail)
436         }
437     }
438 }
439
440 /// A list specifying general categories of I/O error.
441 #[deriving(PartialEq, Eq, Clone, Show)]
442 pub enum IoErrorKind {
443     /// Any I/O error not part of this list.
444     OtherIoError,
445     /// The operation could not complete because end of file was reached.
446     EndOfFile,
447     /// The file was not found.
448     FileNotFound,
449     /// The file permissions disallowed access to this file.
450     PermissionDenied,
451     /// A network connection failed for some reason not specified in this list.
452     ConnectionFailed,
453     /// The network operation failed because the network connection was closed.
454     Closed,
455     /// The connection was refused by the remote server.
456     ConnectionRefused,
457     /// The connection was reset by the remote server.
458     ConnectionReset,
459     /// The connection was aborted (terminated) by the remote server.
460     ConnectionAborted,
461     /// The network operation failed because it was not connected yet.
462     NotConnected,
463     /// The operation failed because a pipe was closed.
464     BrokenPipe,
465     /// A file already existed with that name.
466     PathAlreadyExists,
467     /// No file exists at that location.
468     PathDoesntExist,
469     /// The path did not specify the type of file that this operation required. For example,
470     /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
471     MismatchedFileTypeForOperation,
472     /// The operation temporarily failed (for example, because a signal was received), and retrying
473     /// may succeed.
474     ResourceUnavailable,
475     /// No I/O functionality is available for this task.
476     IoUnavailable,
477     /// A parameter was incorrect in a way that caused an I/O error not part of this list.
478     InvalidInput,
479     /// The I/O operation's timeout expired, causing it to be canceled.
480     TimedOut,
481     /// This write operation failed to write all of its data.
482     ///
483     /// Normally the write() method on a Writer guarantees that all of its data
484     /// has been written, but some operations may be terminated after only
485     /// partially writing some data. An example of this is a timed out write
486     /// which successfully wrote a known number of bytes, but bailed out after
487     /// doing so.
488     ///
489     /// The payload contained as part of this variant is the number of bytes
490     /// which are known to have been successfully written.
491     ShortWrite(uint),
492     /// The Reader returned 0 bytes from `read()` too many times.
493     NoProgress,
494 }
495
496 /// A trait that lets you add a `detail` to an IoError easily
497 trait UpdateIoError<T> {
498     /// Returns an IoError with updated description and detail
499     fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> Self;
500
501     /// Returns an IoError with updated detail
502     fn update_detail(self, detail: |&IoError| -> String) -> Self;
503
504     /// Returns an IoError with update description
505     fn update_desc(self, desc: &'static str) -> Self;
506 }
507
508 impl<T> UpdateIoError<T> for IoResult<T> {
509     fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> IoResult<T> {
510         self.map_err(|mut e| {
511             let detail = detail(&e);
512             e.desc = desc;
513             e.detail = Some(detail);
514             e
515         })
516     }
517
518     fn update_detail(self, detail: |&IoError| -> String) -> IoResult<T> {
519         self.map_err(|mut e| { e.detail = Some(detail(&e)); e })
520     }
521
522     fn update_desc(self, desc: &'static str) -> IoResult<T> {
523         self.map_err(|mut e| { e.desc = desc; e })
524     }
525 }
526
527 static NO_PROGRESS_LIMIT: uint = 1000;
528
529 /// A trait for objects which are byte-oriented streams. Readers are defined by
530 /// one method, `read`. This function will block until data is available,
531 /// filling in the provided buffer with any data read.
532 ///
533 /// Readers are intended to be composable with one another. Many objects
534 /// throughout the I/O and related libraries take and provide types which
535 /// implement the `Reader` trait.
536 pub trait Reader {
537
538     // Only method which need to get implemented for this trait
539
540     /// Read bytes, up to the length of `buf` and place them in `buf`.
541     /// Returns the number of bytes read. The number of bytes read may
542     /// be less than the number requested, even 0. Returns `Err` on EOF.
543     ///
544     /// # Error
545     ///
546     /// If an error occurs during this I/O operation, then it is returned as
547     /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
548     /// inspected for in the error's `kind` field. Also note that reading 0
549     /// bytes is not considered an error in all circumstances
550     ///
551     /// # Implementation Note
552     ///
553     /// When implementing this method on a new Reader, you are strongly encouraged
554     /// not to return 0 if you can avoid it.
555     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
556
557     // Convenient helper methods based on the above methods
558
559     /// Reads at least `min` bytes and places them in `buf`.
560     /// Returns the number of bytes read.
561     ///
562     /// This will continue to call `read` until at least `min` bytes have been
563     /// read. If `read` returns 0 too many times, `NoProgress` will be
564     /// returned.
565     ///
566     /// # Error
567     ///
568     /// If an error occurs at any point, that error is returned, and no further
569     /// bytes are read.
570     fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
571         if min > buf.len() {
572             return Err(IoError {
573                 detail: Some(String::from_str("the buffer is too short")),
574                 ..standard_error(InvalidInput)
575             });
576         }
577         let mut read = 0;
578         while read < min {
579             let mut zeroes = 0;
580             loop {
581                 match self.read(buf.mut_slice_from(read)) {
582                     Ok(0) => {
583                         zeroes += 1;
584                         if zeroes >= NO_PROGRESS_LIMIT {
585                             return Err(standard_error(NoProgress));
586                         }
587                     }
588                     Ok(n) => {
589                         read += n;
590                         break;
591                     }
592                     err@Err(_) => return err
593                 }
594             }
595         }
596         Ok(read)
597     }
598
599     /// Reads a single byte. Returns `Err` on EOF.
600     fn read_byte(&mut self) -> IoResult<u8> {
601         let mut buf = [0];
602         try!(self.read_at_least(1, buf));
603         Ok(buf[0])
604     }
605
606     /// Reads up to `len` bytes and appends them to a vector.
607     /// Returns the number of bytes read. The number of bytes read may be
608     /// less than the number requested, even 0. Returns Err on EOF.
609     ///
610     /// # Error
611     ///
612     /// If an error occurs during this I/O operation, then it is returned
613     /// as `Err(IoError)`. See `read()` for more details.
614     fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
615         let start_len = buf.len();
616         buf.reserve_additional(len);
617
618         let n = {
619             let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
620             try!(self.read(s))
621         };
622         unsafe { buf.set_len(start_len + n) };
623         Ok(n)
624     }
625
626     /// Reads at least `min` bytes, but no more than `len`, and appends them to
627     /// a vector.
628     /// Returns the number of bytes read.
629     ///
630     /// This will continue to call `read` until at least `min` bytes have been
631     /// read. If `read` returns 0 too many times, `NoProgress` will be
632     /// returned.
633     ///
634     /// # Error
635     ///
636     /// If an error occurs at any point, that error is returned, and no further
637     /// bytes are read.
638     fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
639         if min > len {
640             return Err(IoError {
641                 detail: Some(String::from_str("the buffer is too short")),
642                 ..standard_error(InvalidInput)
643             });
644         }
645
646         let start_len = buf.len();
647         buf.reserve_additional(len);
648
649         // we can't just use self.read_at_least(min, slice) because we need to push
650         // successful reads onto the vector before any returned errors.
651
652         let mut read = 0;
653         while read < min {
654             read += {
655                 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
656                 try!(self.read_at_least(1, s))
657             };
658             unsafe { buf.set_len(start_len + read) };
659         }
660         Ok(read)
661     }
662
663     /// Reads exactly `len` bytes and gives you back a new vector of length
664     /// `len`
665     ///
666     /// # Error
667     ///
668     /// Fails with the same conditions as `read`. Additionally returns error
669     /// on EOF. Note that if an error is returned, then some number of bytes may
670     /// have already been consumed from the underlying reader, and they are lost
671     /// (not returned as part of the error). If this is unacceptable, then it is
672     /// recommended to use the `push_at_least` or `read` methods.
673     fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
674         let mut buf = Vec::with_capacity(len);
675         match self.push_at_least(len, len, &mut buf) {
676             Ok(_) => Ok(buf),
677             Err(e) => Err(e),
678         }
679     }
680
681     /// Reads all remaining bytes from the stream.
682     ///
683     /// # Error
684     ///
685     /// Returns any non-EOF error immediately. Previously read bytes are
686     /// discarded when an error is returned.
687     ///
688     /// When EOF is encountered, all bytes read up to that point are returned.
689     fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
690         let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
691         loop {
692             match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
693                 Ok(_) => {}
694                 Err(ref e) if e.kind == EndOfFile => break,
695                 Err(e) => return Err(e)
696             }
697         }
698         return Ok(buf);
699     }
700
701     /// Reads all of the remaining bytes of this stream, interpreting them as a
702     /// UTF-8 encoded stream. The corresponding string is returned.
703     ///
704     /// # Error
705     ///
706     /// This function returns all of the same errors as `read_to_end` with an
707     /// additional error if the reader's contents are not a valid sequence of
708     /// UTF-8 bytes.
709     fn read_to_string(&mut self) -> IoResult<String> {
710         self.read_to_end().and_then(|s| {
711             match String::from_utf8(s) {
712                 Ok(s)  => Ok(s),
713                 Err(_) => Err(standard_error(InvalidInput)),
714             }
715         })
716     }
717
718     /// Create an iterator that reads a single byte on
719     /// each iteration, until EOF.
720     ///
721     /// # Error
722     ///
723     /// Any error other than `EndOfFile` that is produced by the underlying Reader
724     /// is returned by the iterator and should be handled by the caller.
725     fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self> {
726         extensions::Bytes::new(self)
727     }
728
729     // Byte conversion helpers
730
731     /// Reads `n` little-endian unsigned integer bytes.
732     ///
733     /// `n` must be between 1 and 8, inclusive.
734     fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
735         assert!(nbytes > 0 && nbytes <= 8);
736
737         let mut val = 0u64;
738         let mut pos = 0;
739         let mut i = nbytes;
740         while i > 0 {
741             val += (try!(self.read_u8()) as u64) << pos;
742             pos += 8;
743             i -= 1;
744         }
745         Ok(val)
746     }
747
748     /// Reads `n` little-endian signed integer bytes.
749     ///
750     /// `n` must be between 1 and 8, inclusive.
751     fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
752         self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
753     }
754
755     /// Reads `n` big-endian unsigned integer bytes.
756     ///
757     /// `n` must be between 1 and 8, inclusive.
758     fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
759         assert!(nbytes > 0 && nbytes <= 8);
760
761         let mut val = 0u64;
762         let mut i = nbytes;
763         while i > 0 {
764             i -= 1;
765             val += (try!(self.read_u8()) as u64) << i * 8;
766         }
767         Ok(val)
768     }
769
770     /// Reads `n` big-endian signed integer bytes.
771     ///
772     /// `n` must be between 1 and 8, inclusive.
773     fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
774         self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
775     }
776
777     /// Reads a little-endian unsigned integer.
778     ///
779     /// The number of bytes returned is system-dependent.
780     fn read_le_uint(&mut self) -> IoResult<uint> {
781         self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
782     }
783
784     /// Reads a little-endian integer.
785     ///
786     /// The number of bytes returned is system-dependent.
787     fn read_le_int(&mut self) -> IoResult<int> {
788         self.read_le_int_n(int::BYTES).map(|i| i as int)
789     }
790
791     /// Reads a big-endian unsigned integer.
792     ///
793     /// The number of bytes returned is system-dependent.
794     fn read_be_uint(&mut self) -> IoResult<uint> {
795         self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
796     }
797
798     /// Reads a big-endian integer.
799     ///
800     /// The number of bytes returned is system-dependent.
801     fn read_be_int(&mut self) -> IoResult<int> {
802         self.read_be_int_n(int::BYTES).map(|i| i as int)
803     }
804
805     /// Reads a big-endian `u64`.
806     ///
807     /// `u64`s are 8 bytes long.
808     fn read_be_u64(&mut self) -> IoResult<u64> {
809         self.read_be_uint_n(8)
810     }
811
812     /// Reads a big-endian `u32`.
813     ///
814     /// `u32`s are 4 bytes long.
815     fn read_be_u32(&mut self) -> IoResult<u32> {
816         self.read_be_uint_n(4).map(|i| i as u32)
817     }
818
819     /// Reads a big-endian `u16`.
820     ///
821     /// `u16`s are 2 bytes long.
822     fn read_be_u16(&mut self) -> IoResult<u16> {
823         self.read_be_uint_n(2).map(|i| i as u16)
824     }
825
826     /// Reads a big-endian `i64`.
827     ///
828     /// `i64`s are 8 bytes long.
829     fn read_be_i64(&mut self) -> IoResult<i64> {
830         self.read_be_int_n(8)
831     }
832
833     /// Reads a big-endian `i32`.
834     ///
835     /// `i32`s are 4 bytes long.
836     fn read_be_i32(&mut self) -> IoResult<i32> {
837         self.read_be_int_n(4).map(|i| i as i32)
838     }
839
840     /// Reads a big-endian `i16`.
841     ///
842     /// `i16`s are 2 bytes long.
843     fn read_be_i16(&mut self) -> IoResult<i16> {
844         self.read_be_int_n(2).map(|i| i as i16)
845     }
846
847     /// Reads a big-endian `f64`.
848     ///
849     /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
850     fn read_be_f64(&mut self) -> IoResult<f64> {
851         self.read_be_u64().map(|i| unsafe {
852             transmute::<u64, f64>(i)
853         })
854     }
855
856     /// Reads a big-endian `f32`.
857     ///
858     /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
859     fn read_be_f32(&mut self) -> IoResult<f32> {
860         self.read_be_u32().map(|i| unsafe {
861             transmute::<u32, f32>(i)
862         })
863     }
864
865     /// Reads a little-endian `u64`.
866     ///
867     /// `u64`s are 8 bytes long.
868     fn read_le_u64(&mut self) -> IoResult<u64> {
869         self.read_le_uint_n(8)
870     }
871
872     /// Reads a little-endian `u32`.
873     ///
874     /// `u32`s are 4 bytes long.
875     fn read_le_u32(&mut self) -> IoResult<u32> {
876         self.read_le_uint_n(4).map(|i| i as u32)
877     }
878
879     /// Reads a little-endian `u16`.
880     ///
881     /// `u16`s are 2 bytes long.
882     fn read_le_u16(&mut self) -> IoResult<u16> {
883         self.read_le_uint_n(2).map(|i| i as u16)
884     }
885
886     /// Reads a little-endian `i64`.
887     ///
888     /// `i64`s are 8 bytes long.
889     fn read_le_i64(&mut self) -> IoResult<i64> {
890         self.read_le_int_n(8)
891     }
892
893     /// Reads a little-endian `i32`.
894     ///
895     /// `i32`s are 4 bytes long.
896     fn read_le_i32(&mut self) -> IoResult<i32> {
897         self.read_le_int_n(4).map(|i| i as i32)
898     }
899
900     /// Reads a little-endian `i16`.
901     ///
902     /// `i16`s are 2 bytes long.
903     fn read_le_i16(&mut self) -> IoResult<i16> {
904         self.read_le_int_n(2).map(|i| i as i16)
905     }
906
907     /// Reads a little-endian `f64`.
908     ///
909     /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
910     fn read_le_f64(&mut self) -> IoResult<f64> {
911         self.read_le_u64().map(|i| unsafe {
912             transmute::<u64, f64>(i)
913         })
914     }
915
916     /// Reads a little-endian `f32`.
917     ///
918     /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
919     fn read_le_f32(&mut self) -> IoResult<f32> {
920         self.read_le_u32().map(|i| unsafe {
921             transmute::<u32, f32>(i)
922         })
923     }
924
925     /// Read a u8.
926     ///
927     /// `u8`s are 1 byte.
928     fn read_u8(&mut self) -> IoResult<u8> {
929         self.read_byte()
930     }
931
932     /// Read an i8.
933     ///
934     /// `i8`s are 1 byte.
935     fn read_i8(&mut self) -> IoResult<i8> {
936         self.read_byte().map(|i| i as i8)
937     }
938
939     /// Creates a wrapper around a mutable reference to the reader.
940     ///
941     /// This is useful to allow applying adaptors while still
942     /// retaining ownership of the original value.
943     fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self> {
944         RefReader { inner: self }
945     }
946 }
947
948 #[cfg(stage0)]
949 impl Reader for Box<Reader+'static> {
950     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
951 }
952
953 #[cfg(not(stage0))]
954 impl<'a> Reader for Box<Reader+'a> {
955     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
956 }
957
958 impl<'a> Reader for &'a mut Reader+'a {
959     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
960 }
961
962 /// Returns a slice of `v` between `start` and `end`.
963 ///
964 /// Similar to `slice()` except this function only bounds the slice on the
965 /// capacity of `v`, not the length.
966 ///
967 /// # Failure
968 ///
969 /// Fails when `start` or `end` point outside the capacity of `v`, or when
970 /// `start` > `end`.
971 // Private function here because we aren't sure if we want to expose this as
972 // API yet. If so, it should be a method on Vec.
973 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
974     use raw::Slice;
975     use ptr::RawPtr;
976
977     assert!(start <= end);
978     assert!(end <= v.capacity());
979     transmute(Slice {
980         data: v.as_ptr().offset(start as int),
981         len: end - start
982     })
983 }
984
985 /// A `RefReader` is a struct implementing `Reader` which contains a reference
986 /// to another reader. This is often useful when composing streams.
987 ///
988 /// # Example
989 ///
990 /// ```
991 /// # fn main() {}
992 /// # fn process_input<R: Reader>(r: R) {}
993 /// # fn foo() {
994 /// use std::io;
995 /// use std::io::util::LimitReader;
996 ///
997 /// let mut stream = io::stdin();
998 ///
999 /// // Only allow the function to process at most one kilobyte of input
1000 /// {
1001 ///     let stream = LimitReader::new(stream.by_ref(), 1024);
1002 ///     process_input(stream);
1003 /// }
1004 ///
1005 /// // 'stream' is still available for use here
1006 ///
1007 /// # }
1008 /// ```
1009 pub struct RefReader<'a, R:'a> {
1010     /// The underlying reader which this is referencing
1011     inner: &'a mut R
1012 }
1013
1014 impl<'a, R: Reader> Reader for RefReader<'a, R> {
1015     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
1016 }
1017
1018 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
1019     fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { self.inner.fill_buf() }
1020     fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
1021 }
1022
1023 fn extend_sign(val: u64, nbytes: uint) -> i64 {
1024     let shift = (8 - nbytes) * 8;
1025     (val << shift) as i64 >> shift
1026 }
1027
1028 /// A trait for objects which are byte-oriented streams. Writers are defined by
1029 /// one method, `write`. This function will block until the provided buffer of
1030 /// bytes has been entirely written, and it will return any failures which occur.
1031 ///
1032 /// Another commonly overridden method is the `flush` method for writers such as
1033 /// buffered writers.
1034 ///
1035 /// Writers are intended to be composable with one another. Many objects
1036 /// throughout the I/O and related libraries take and provide types which
1037 /// implement the `Writer` trait.
1038 pub trait Writer {
1039     /// Write the entirety of a given buffer
1040     ///
1041     /// # Errors
1042     ///
1043     /// If an error happens during the I/O operation, the error is returned as
1044     /// `Err`. Note that it is considered an error if the entire buffer could
1045     /// not be written, and if an error is returned then it is unknown how much
1046     /// data (if any) was actually written.
1047     fn write(&mut self, buf: &[u8]) -> IoResult<()>;
1048
1049     /// Flush this output stream, ensuring that all intermediately buffered
1050     /// contents reach their destination.
1051     ///
1052     /// This is by default a no-op and implementers of the `Writer` trait should
1053     /// decide whether their stream needs to be buffered or not.
1054     fn flush(&mut self) -> IoResult<()> { Ok(()) }
1055
1056     /// Writes a formatted string into this writer, returning any error
1057     /// encountered.
1058     ///
1059     /// This method is primarily used to interface with the `format_args!`
1060     /// macro, but it is rare that this should explicitly be called. The
1061     /// `write!` macro should be favored to invoke this method instead.
1062     ///
1063     /// # Errors
1064     ///
1065     /// This function will return any I/O error reported while formatting.
1066     fn write_fmt(&mut self, fmt: &fmt::Arguments) -> IoResult<()> {
1067         // Create a shim which translates a Writer to a FormatWriter and saves
1068         // off I/O errors. instead of discarding them
1069         struct Adaptor<'a, T:'a> {
1070             inner: &'a mut T,
1071             error: IoResult<()>,
1072         }
1073
1074         impl<'a, T: Writer> fmt::FormatWriter for Adaptor<'a, T> {
1075             fn write(&mut self, bytes: &[u8]) -> fmt::Result {
1076                 match self.inner.write(bytes) {
1077                     Ok(()) => Ok(()),
1078                     Err(e) => {
1079                         self.error = Err(e);
1080                         Err(fmt::WriteError)
1081                     }
1082                 }
1083             }
1084         }
1085
1086         let mut output = Adaptor { inner: self, error: Ok(()) };
1087         match fmt::write(&mut output, fmt) {
1088             Ok(()) => Ok(()),
1089             Err(..) => output.error
1090         }
1091     }
1092
1093     /// Write a rust string into this sink.
1094     ///
1095     /// The bytes written will be the UTF-8 encoded version of the input string.
1096     /// If other encodings are desired, it is recommended to compose this stream
1097     /// with another performing the conversion, or to use `write` with a
1098     /// converted byte-array instead.
1099     #[inline]
1100     fn write_str(&mut self, s: &str) -> IoResult<()> {
1101         self.write(s.as_bytes())
1102     }
1103
1104     /// Writes a string into this sink, and then writes a literal newline (`\n`)
1105     /// byte afterwards. Note that the writing of the newline is *not* atomic in
1106     /// the sense that the call to `write` is invoked twice (once with the
1107     /// string and once with a newline character).
1108     ///
1109     /// If other encodings or line ending flavors are desired, it is recommended
1110     /// that the `write` method is used specifically instead.
1111     #[inline]
1112     fn write_line(&mut self, s: &str) -> IoResult<()> {
1113         self.write_str(s).and_then(|()| self.write([b'\n']))
1114     }
1115
1116     /// Write a single char, encoded as UTF-8.
1117     #[inline]
1118     fn write_char(&mut self, c: char) -> IoResult<()> {
1119         let mut buf = [0u8, ..4];
1120         let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
1121         self.write(buf.slice_to(n))
1122     }
1123
1124     /// Write the result of passing n through `int::to_str_bytes`.
1125     #[inline]
1126     fn write_int(&mut self, n: int) -> IoResult<()> {
1127         write!(self, "{:d}", n)
1128     }
1129
1130     /// Write the result of passing n through `uint::to_str_bytes`.
1131     #[inline]
1132     fn write_uint(&mut self, n: uint) -> IoResult<()> {
1133         write!(self, "{:u}", n)
1134     }
1135
1136     /// Write a little-endian uint (number of bytes depends on system).
1137     #[inline]
1138     fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1139         extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
1140     }
1141
1142     /// Write a little-endian int (number of bytes depends on system).
1143     #[inline]
1144     fn write_le_int(&mut self, n: int) -> IoResult<()> {
1145         extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
1146     }
1147
1148     /// Write a big-endian uint (number of bytes depends on system).
1149     #[inline]
1150     fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1151         extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
1152     }
1153
1154     /// Write a big-endian int (number of bytes depends on system).
1155     #[inline]
1156     fn write_be_int(&mut self, n: int) -> IoResult<()> {
1157         extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
1158     }
1159
1160     /// Write a big-endian u64 (8 bytes).
1161     #[inline]
1162     fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1163         extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
1164     }
1165
1166     /// Write a big-endian u32 (4 bytes).
1167     #[inline]
1168     fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1169         extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1170     }
1171
1172     /// Write a big-endian u16 (2 bytes).
1173     #[inline]
1174     fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1175         extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1176     }
1177
1178     /// Write a big-endian i64 (8 bytes).
1179     #[inline]
1180     fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1181         extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1182     }
1183
1184     /// Write a big-endian i32 (4 bytes).
1185     #[inline]
1186     fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1187         extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1188     }
1189
1190     /// Write a big-endian i16 (2 bytes).
1191     #[inline]
1192     fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1193         extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1194     }
1195
1196     /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1197     #[inline]
1198     fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1199         unsafe {
1200             self.write_be_u64(transmute(f))
1201         }
1202     }
1203
1204     /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1205     #[inline]
1206     fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1207         unsafe {
1208             self.write_be_u32(transmute(f))
1209         }
1210     }
1211
1212     /// Write a little-endian u64 (8 bytes).
1213     #[inline]
1214     fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1215         extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
1216     }
1217
1218     /// Write a little-endian u32 (4 bytes).
1219     #[inline]
1220     fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1221         extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1222     }
1223
1224     /// Write a little-endian u16 (2 bytes).
1225     #[inline]
1226     fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1227         extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1228     }
1229
1230     /// Write a little-endian i64 (8 bytes).
1231     #[inline]
1232     fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1233         extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1234     }
1235
1236     /// Write a little-endian i32 (4 bytes).
1237     #[inline]
1238     fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1239         extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1240     }
1241
1242     /// Write a little-endian i16 (2 bytes).
1243     #[inline]
1244     fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1245         extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1246     }
1247
1248     /// Write a little-endian IEEE754 double-precision floating-point
1249     /// (8 bytes).
1250     #[inline]
1251     fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1252         unsafe {
1253             self.write_le_u64(transmute(f))
1254         }
1255     }
1256
1257     /// Write a little-endian IEEE754 single-precision floating-point
1258     /// (4 bytes).
1259     #[inline]
1260     fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1261         unsafe {
1262             self.write_le_u32(transmute(f))
1263         }
1264     }
1265
1266     /// Write a u8 (1 byte).
1267     #[inline]
1268     fn write_u8(&mut self, n: u8) -> IoResult<()> {
1269         self.write([n])
1270     }
1271
1272     /// Write an i8 (1 byte).
1273     #[inline]
1274     fn write_i8(&mut self, n: i8) -> IoResult<()> {
1275         self.write([n as u8])
1276     }
1277
1278     /// Creates a wrapper around a mutable reference to the writer.
1279     ///
1280     /// This is useful to allow applying wrappers while still
1281     /// retaining ownership of the original value.
1282     #[inline]
1283     fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self> {
1284         RefWriter { inner: self }
1285     }
1286 }
1287
1288 #[cfg(stage0)]
1289 impl Writer for Box<Writer+'static> {
1290     #[inline]
1291     fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
1292
1293     #[inline]
1294     fn flush(&mut self) -> IoResult<()> { self.flush() }
1295 }
1296
1297 #[cfg(not(stage0))]
1298 impl<'a> Writer for Box<Writer+'a> {
1299     #[inline]
1300     fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
1301
1302     #[inline]
1303     fn flush(&mut self) -> IoResult<()> { self.flush() }
1304 }
1305
1306 impl<'a> Writer for &'a mut Writer+'a {
1307     #[inline]
1308     fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
1309
1310     #[inline]
1311     fn flush(&mut self) -> IoResult<()> { self.flush() }
1312 }
1313
1314 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1315 /// to another writer. This is often useful when composing streams.
1316 ///
1317 /// # Example
1318 ///
1319 /// ```
1320 /// # fn main() {}
1321 /// # fn process_input<R: Reader>(r: R) {}
1322 /// # fn foo () {
1323 /// use std::io::util::TeeReader;
1324 /// use std::io::{stdin, MemWriter};
1325 ///
1326 /// let mut output = MemWriter::new();
1327 ///
1328 /// {
1329 ///     // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1330 ///     // handle to it in the outer scope
1331 ///     let mut tee = TeeReader::new(stdin(), output.by_ref());
1332 ///     process_input(tee);
1333 /// }
1334 ///
1335 /// println!("input processed: {}", output.unwrap());
1336 /// # }
1337 /// ```
1338 pub struct RefWriter<'a, W:'a> {
1339     /// The underlying writer which this is referencing
1340     inner: &'a mut W
1341 }
1342
1343 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1344     #[inline]
1345     fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
1346
1347     #[inline]
1348     fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1349 }
1350
1351
1352 /// A Stream is a readable and a writable object. Data written is typically
1353 /// received by the object which reads receive data from.
1354 pub trait Stream: Reader + Writer { }
1355
1356 impl<T: Reader + Writer> Stream for T {}
1357
1358 /// An iterator that reads a line on each iteration,
1359 /// until `.read_line()` encounters `EndOfFile`.
1360 ///
1361 /// # Notes about the Iteration Protocol
1362 ///
1363 /// The `Lines` may yield `None` and thus terminate
1364 /// an iteration, but continue to yield elements if iteration
1365 /// is attempted again.
1366 ///
1367 /// # Error
1368 ///
1369 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1370 /// is returned by the iterator and should be handled by the caller.
1371 pub struct Lines<'r, T:'r> {
1372     buffer: &'r mut T,
1373 }
1374
1375 impl<'r, T: Buffer> Iterator<IoResult<String>> for Lines<'r, T> {
1376     fn next(&mut self) -> Option<IoResult<String>> {
1377         match self.buffer.read_line() {
1378             Ok(x) => Some(Ok(x)),
1379             Err(IoError { kind: EndOfFile, ..}) => None,
1380             Err(y) => Some(Err(y))
1381         }
1382     }
1383 }
1384
1385 /// An iterator that reads a utf8-encoded character on each iteration,
1386 /// until `.read_char()` encounters `EndOfFile`.
1387 ///
1388 /// # Notes about the Iteration Protocol
1389 ///
1390 /// The `Chars` may yield `None` and thus terminate
1391 /// an iteration, but continue to yield elements if iteration
1392 /// is attempted again.
1393 ///
1394 /// # Error
1395 ///
1396 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1397 /// is returned by the iterator and should be handled by the caller.
1398 pub struct Chars<'r, T:'r> {
1399     buffer: &'r mut T
1400 }
1401
1402 impl<'r, T: Buffer> Iterator<IoResult<char>> for Chars<'r, T> {
1403     fn next(&mut self) -> Option<IoResult<char>> {
1404         match self.buffer.read_char() {
1405             Ok(x) => Some(Ok(x)),
1406             Err(IoError { kind: EndOfFile, ..}) => None,
1407             Err(y) => Some(Err(y))
1408         }
1409     }
1410 }
1411
1412 /// A Buffer is a type of reader which has some form of internal buffering to
1413 /// allow certain kinds of reading operations to be more optimized than others.
1414 /// This type extends the `Reader` trait with a few methods that are not
1415 /// possible to reasonably implement with purely a read interface.
1416 pub trait Buffer: Reader {
1417     /// Fills the internal buffer of this object, returning the buffer contents.
1418     /// Note that none of the contents will be "read" in the sense that later
1419     /// calling `read` may return the same contents.
1420     ///
1421     /// The `consume` function must be called with the number of bytes that are
1422     /// consumed from this buffer returned to ensure that the bytes are never
1423     /// returned twice.
1424     ///
1425     /// # Error
1426     ///
1427     /// This function will return an I/O error if the underlying reader was
1428     /// read, but returned an error. Note that it is not an error to return a
1429     /// 0-length buffer.
1430     fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1431
1432     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1433     /// so they should no longer be returned in calls to `read`.
1434     fn consume(&mut self, amt: uint);
1435
1436     /// Reads the next line of input, interpreted as a sequence of UTF-8
1437     /// encoded Unicode codepoints. If a newline is encountered, then the
1438     /// newline is contained in the returned string.
1439     ///
1440     /// # Example
1441     ///
1442     /// ```rust
1443     /// use std::io;
1444     ///
1445     /// let mut reader = io::stdin();
1446     /// let input = reader.read_line().ok().unwrap_or("nothing".to_string());
1447     /// ```
1448     ///
1449     /// # Error
1450     ///
1451     /// This function has the same error semantics as `read_until`:
1452     ///
1453     /// * All non-EOF errors will be returned immediately
1454     /// * If an error is returned previously consumed bytes are lost
1455     /// * EOF is only returned if no bytes have been read
1456     /// * Reach EOF may mean that the delimiter is not present in the return
1457     ///   value
1458     ///
1459     /// Additionally, this function can fail if the line of input read is not a
1460     /// valid UTF-8 sequence of bytes.
1461     fn read_line(&mut self) -> IoResult<String> {
1462         self.read_until(b'\n').and_then(|line|
1463             match String::from_utf8(line) {
1464                 Ok(s)  => Ok(s),
1465                 Err(_) => Err(standard_error(InvalidInput)),
1466             }
1467         )
1468     }
1469
1470     /// Create an iterator that reads a line on each iteration until EOF.
1471     ///
1472     /// # Error
1473     ///
1474     /// Any error other than `EndOfFile` that is produced by the underlying Reader
1475     /// is returned by the iterator and should be handled by the caller.
1476     fn lines<'r>(&'r mut self) -> Lines<'r, Self> {
1477         Lines { buffer: self }
1478     }
1479
1480     /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1481     /// specified byte is encountered, reading ceases and the bytes up to and
1482     /// including the delimiter are returned.
1483     ///
1484     /// # Error
1485     ///
1486     /// If any I/O error is encountered other than EOF, the error is immediately
1487     /// returned. Note that this may discard bytes which have already been read,
1488     /// and those bytes will *not* be returned. It is recommended to use other
1489     /// methods if this case is worrying.
1490     ///
1491     /// If EOF is encountered, then this function will return EOF if 0 bytes
1492     /// have been read, otherwise the pending byte buffer is returned. This
1493     /// is the reason that the byte buffer returned may not always contain the
1494     /// delimiter.
1495     fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1496         let mut res = Vec::new();
1497
1498         let mut used;
1499         loop {
1500             {
1501                 let available = match self.fill_buf() {
1502                     Ok(n) => n,
1503                     Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1504                         used = 0;
1505                         break
1506                     }
1507                     Err(e) => return Err(e)
1508                 };
1509                 match available.iter().position(|&b| b == byte) {
1510                     Some(i) => {
1511                         res.push_all(available.slice_to(i + 1));
1512                         used = i + 1;
1513                         break
1514                     }
1515                     None => {
1516                         res.push_all(available);
1517                         used = available.len();
1518                     }
1519                 }
1520             }
1521             self.consume(used);
1522         }
1523         self.consume(used);
1524         Ok(res)
1525     }
1526
1527     /// Reads the next utf8-encoded character from the underlying stream.
1528     ///
1529     /// # Error
1530     ///
1531     /// If an I/O error occurs, or EOF, then this function will return `Err`.
1532     /// This function will also return error if the stream does not contain a
1533     /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1534     fn read_char(&mut self) -> IoResult<char> {
1535         let first_byte = try!(self.read_byte());
1536         let width = str::utf8_char_width(first_byte);
1537         if width == 1 { return Ok(first_byte as char) }
1538         if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1539         let mut buf = [first_byte, 0, 0, 0];
1540         {
1541             let mut start = 1;
1542             while start < width {
1543                 match try!(self.read(buf.mut_slice(start, width))) {
1544                     n if n == width - start => break,
1545                     n if n < width - start => { start += n; }
1546                     _ => return Err(standard_error(InvalidInput)),
1547                 }
1548             }
1549         }
1550         match str::from_utf8(buf.slice_to(width)) {
1551             Some(s) => Ok(s.char_at(0)),
1552             None => Err(standard_error(InvalidInput))
1553         }
1554     }
1555
1556     /// Create an iterator that reads a utf8-encoded character on each iteration
1557     /// until EOF.
1558     ///
1559     /// # Error
1560     ///
1561     /// Any error other than `EndOfFile` that is produced by the underlying Reader
1562     /// is returned by the iterator and should be handled by the caller.
1563     fn chars<'r>(&'r mut self) -> Chars<'r, Self> {
1564         Chars { buffer: self }
1565     }
1566 }
1567
1568 /// When seeking, the resulting cursor is offset from a base by the offset given
1569 /// to the `seek` function. The base used is specified by this enumeration.
1570 pub enum SeekStyle {
1571     /// Seek from the beginning of the stream
1572     SeekSet,
1573     /// Seek from the end of the stream
1574     SeekEnd,
1575     /// Seek from the current position
1576     SeekCur,
1577 }
1578
1579 /// An object implementing `Seek` internally has some form of cursor which can
1580 /// be moved within a stream of bytes. The stream typically has a fixed size,
1581 /// allowing seeking relative to either end.
1582 pub trait Seek {
1583     /// Return position of file cursor in the stream
1584     fn tell(&self) -> IoResult<u64>;
1585
1586     /// Seek to an offset in a stream
1587     ///
1588     /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1589     /// allowed, but seeking before position 0 is not allowed.
1590     ///
1591     /// # Errors
1592     ///
1593     /// * Seeking to a negative offset is considered an error
1594     /// * Seeking past the end of the stream does not modify the underlying
1595     ///   stream, but the next write may cause the previous data to be filled in
1596     ///   with a bit pattern.
1597     fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1598 }
1599
1600 /// A listener is a value that can consume itself to start listening for
1601 /// connections.
1602 ///
1603 /// Doing so produces some sort of Acceptor.
1604 pub trait Listener<T, A: Acceptor<T>> {
1605     /// Spin up the listener and start queuing incoming connections
1606     ///
1607     /// # Error
1608     ///
1609     /// Returns `Err` if this listener could not be bound to listen for
1610     /// connections. In all cases, this listener is consumed.
1611     fn listen(self) -> IoResult<A>;
1612 }
1613
1614 /// An acceptor is a value that presents incoming connections
1615 pub trait Acceptor<T> {
1616     /// Wait for and accept an incoming connection
1617     ///
1618     /// # Error
1619     ///
1620     /// Returns `Err` if an I/O error is encountered.
1621     fn accept(&mut self) -> IoResult<T>;
1622
1623     /// Create an iterator over incoming connection attempts.
1624     ///
1625     /// Note that I/O errors will be yielded by the iterator itself.
1626     fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1627         IncomingConnections { inc: self }
1628     }
1629 }
1630
1631 /// An infinite iterator over incoming connection attempts.
1632 /// Calling `next` will block the task until a connection is attempted.
1633 ///
1634 /// Since connection attempts can continue forever, this iterator always returns
1635 /// `Some`. The `Some` contains the `IoResult` representing whether the
1636 /// connection attempt was successful.  A successful connection will be wrapped
1637 /// in `Ok`. A failed connection is represented as an `Err`.
1638 pub struct IncomingConnections<'a, A:'a> {
1639     inc: &'a mut A,
1640 }
1641
1642 impl<'a, T, A: Acceptor<T>> Iterator<IoResult<T>> for IncomingConnections<'a, A> {
1643     fn next(&mut self) -> Option<IoResult<T>> {
1644         Some(self.inc.accept())
1645     }
1646 }
1647
1648 /// Creates a standard error for a commonly used flavor of error. The `detail`
1649 /// field of the returned error will always be `None`.
1650 ///
1651 /// # Example
1652 ///
1653 /// ```
1654 /// use std::io;
1655 ///
1656 /// let eof = io::standard_error(io::EndOfFile);
1657 /// let einval = io::standard_error(io::InvalidInput);
1658 /// ```
1659 pub fn standard_error(kind: IoErrorKind) -> IoError {
1660     let desc = match kind {
1661         EndOfFile => "end of file",
1662         IoUnavailable => "I/O is unavailable",
1663         InvalidInput => "invalid input",
1664         OtherIoError => "unknown I/O error",
1665         FileNotFound => "file not found",
1666         PermissionDenied => "permission denied",
1667         ConnectionFailed => "connection failed",
1668         Closed => "stream is closed",
1669         ConnectionRefused => "connection refused",
1670         ConnectionReset => "connection reset",
1671         ConnectionAborted => "connection aborted",
1672         NotConnected => "not connected",
1673         BrokenPipe => "broken pipe",
1674         PathAlreadyExists => "file already exists",
1675         PathDoesntExist => "no such file",
1676         MismatchedFileTypeForOperation => "mismatched file type",
1677         ResourceUnavailable => "resource unavailable",
1678         TimedOut => "operation timed out",
1679         ShortWrite(..) => "short write",
1680         NoProgress => "no progress",
1681     };
1682     IoError {
1683         kind: kind,
1684         desc: desc,
1685         detail: None,
1686     }
1687 }
1688
1689 /// A mode specifies how a file should be opened or created. These modes are
1690 /// passed to `File::open_mode` and are used to control where the file is
1691 /// positioned when it is initially opened.
1692 pub enum FileMode {
1693     /// Opens a file positioned at the beginning.
1694     Open,
1695     /// Opens a file positioned at EOF.
1696     Append,
1697     /// Opens a file, truncating it if it already exists.
1698     Truncate,
1699 }
1700
1701 /// Access permissions with which the file should be opened. `File`s
1702 /// opened with `Read` will return an error if written to.
1703 pub enum FileAccess {
1704     /// Read-only access, requests to write will result in an error
1705     Read,
1706     /// Write-only access, requests to read will result in an error
1707     Write,
1708     /// Read-write access, no requests are denied by default
1709     ReadWrite,
1710 }
1711
1712 /// Different kinds of files which can be identified by a call to stat
1713 #[deriving(PartialEq, Show, Hash)]
1714 pub enum FileType {
1715     /// This is a normal file, corresponding to `S_IFREG`
1716     TypeFile,
1717
1718     /// This file is a directory, corresponding to `S_IFDIR`
1719     TypeDirectory,
1720
1721     /// This file is a named pipe, corresponding to `S_IFIFO`
1722     TypeNamedPipe,
1723
1724     /// This file is a block device, corresponding to `S_IFBLK`
1725     TypeBlockSpecial,
1726
1727     /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1728     TypeSymlink,
1729
1730     /// The type of this file is not recognized as one of the other categories
1731     TypeUnknown,
1732 }
1733
1734 /// A structure used to describe metadata information about a file. This
1735 /// structure is created through the `stat` method on a `Path`.
1736 ///
1737 /// # Example
1738 ///
1739 /// ```
1740 /// # fn main() {}
1741 /// # fn foo() {
1742 /// let info = match Path::new("foo.txt").stat() {
1743 ///     Ok(stat) => stat,
1744 ///     Err(e) => fail!("couldn't read foo.txt: {}", e),
1745 /// };
1746 ///
1747 /// println!("byte size: {}", info.size);
1748 /// # }
1749 /// ```
1750 #[deriving(Hash)]
1751 pub struct FileStat {
1752     /// The size of the file, in bytes
1753     pub size: u64,
1754     /// The kind of file this path points to (directory, file, pipe, etc.)
1755     pub kind: FileType,
1756     /// The file permissions currently on the file
1757     pub perm: FilePermission,
1758
1759     // FIXME(#10301): These time fields are pretty useless without an actual
1760     //                time representation, what are the milliseconds relative
1761     //                to?
1762
1763     /// The time that the file was created at, in platform-dependent
1764     /// milliseconds
1765     pub created: u64,
1766     /// The time that this file was last modified, in platform-dependent
1767     /// milliseconds
1768     pub modified: u64,
1769     /// The time that this file was last accessed, in platform-dependent
1770     /// milliseconds
1771     pub accessed: u64,
1772
1773     /// Information returned by stat() which is not guaranteed to be
1774     /// platform-independent. This information may be useful on some platforms,
1775     /// but it may have different meanings or no meaning at all on other
1776     /// platforms.
1777     ///
1778     /// Usage of this field is discouraged, but if access is desired then the
1779     /// fields are located here.
1780     #[unstable]
1781     pub unstable: UnstableFileStat,
1782 }
1783
1784 /// This structure represents all of the possible information which can be
1785 /// returned from a `stat` syscall which is not contained in the `FileStat`
1786 /// structure. This information is not necessarily platform independent, and may
1787 /// have different meanings or no meaning at all on some platforms.
1788 #[unstable]
1789 #[deriving(Hash)]
1790 pub struct UnstableFileStat {
1791     /// The ID of the device containing the file.
1792     pub device: u64,
1793     /// The file serial number.
1794     pub inode: u64,
1795     /// The device ID.
1796     pub rdev: u64,
1797     /// The number of hard links to this file.
1798     pub nlink: u64,
1799     /// The user ID of the file.
1800     pub uid: u64,
1801     /// The group ID of the file.
1802     pub gid: u64,
1803     /// The optimal block size for I/O.
1804     pub blksize: u64,
1805     /// The blocks allocated for this file.
1806     pub blocks: u64,
1807     /// User-defined flags for the file.
1808     pub flags: u64,
1809     /// The file generation number.
1810     pub gen: u64,
1811 }
1812
1813 bitflags! {
1814     #[doc = "A set of permissions for a file or directory is represented"]
1815     #[doc = "by a set of flags which are or'd together."]
1816     flags FilePermission: u32 {
1817         static UserRead     = 0o400,
1818         static UserWrite    = 0o200,
1819         static UserExecute  = 0o100,
1820         static GroupRead    = 0o040,
1821         static GroupWrite   = 0o020,
1822         static GroupExecute = 0o010,
1823         static OtherRead    = 0o004,
1824         static OtherWrite   = 0o002,
1825         static OtherExecute = 0o001,
1826
1827         static UserRWX  = UserRead.bits | UserWrite.bits | UserExecute.bits,
1828         static GroupRWX = GroupRead.bits | GroupWrite.bits | GroupExecute.bits,
1829         static OtherRWX = OtherRead.bits | OtherWrite.bits | OtherExecute.bits,
1830
1831         #[doc = "Permissions for user owned files, equivalent to 0644 on"]
1832         #[doc = "unix-like systems."]
1833         static UserFile = UserRead.bits | UserWrite.bits | GroupRead.bits | OtherRead.bits,
1834
1835         #[doc = "Permissions for user owned directories, equivalent to 0755 on"]
1836         #[doc = "unix-like systems."]
1837         static UserDir  = UserRWX.bits | GroupRead.bits | GroupExecute.bits |
1838                    OtherRead.bits | OtherExecute.bits,
1839
1840         #[doc = "Permissions for user owned executables, equivalent to 0755"]
1841         #[doc = "on unix-like systems."]
1842         static UserExec = UserDir.bits,
1843
1844         #[doc = "All possible permissions enabled."]
1845         static AllPermissions = UserRWX.bits | GroupRWX.bits | OtherRWX.bits,
1846     }
1847 }
1848
1849 impl Default for FilePermission {
1850     #[inline]
1851     fn default() -> FilePermission { FilePermission::empty() }
1852 }
1853
1854 impl fmt::Show for FilePermission {
1855     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1856         formatter.fill = '0';
1857         formatter.width = Some(4);
1858         (&self.bits as &fmt::Octal).fmt(formatter)
1859     }
1860 }
1861
1862 #[cfg(test)]
1863 mod tests {
1864     use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput};
1865     use prelude::*;
1866     use uint;
1867
1868     #[deriving(Clone, PartialEq, Show)]
1869     enum BadReaderBehavior {
1870         GoodBehavior(uint),
1871         BadBehavior(uint)
1872     }
1873
1874     struct BadReader<T> {
1875         r: T,
1876         behavior: Vec<BadReaderBehavior>,
1877     }
1878
1879     impl<T: Reader> BadReader<T> {
1880         fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1881             BadReader { behavior: behavior, r: r }
1882         }
1883     }
1884
1885     impl<T: Reader> Reader for BadReader<T> {
1886         fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1887             let BadReader { ref mut behavior, ref mut r } = *self;
1888             loop {
1889                 if behavior.is_empty() {
1890                     // fall back on good
1891                     return r.read(buf);
1892                 }
1893                 match behavior.as_mut_slice()[0] {
1894                     GoodBehavior(0) => (),
1895                     GoodBehavior(ref mut x) => {
1896                         *x -= 1;
1897                         return r.read(buf);
1898                     }
1899                     BadBehavior(0) => (),
1900                     BadBehavior(ref mut x) => {
1901                         *x -= 1;
1902                         return Ok(0);
1903                     }
1904                 };
1905                 behavior.shift();
1906             }
1907         }
1908     }
1909
1910     #[test]
1911     fn test_read_at_least() {
1912         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1913                                    Vec::from_slice([GoodBehavior(uint::MAX)]));
1914         let mut buf = [0u8, ..5];
1915         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1916         assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1917         assert!(r.read_at_least(0, buf).is_ok());
1918
1919         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1920                                    Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
1921         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1922
1923         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1924                                    Vec::from_slice([BadBehavior(1), GoodBehavior(1),
1925                                                     BadBehavior(50), GoodBehavior(uint::MAX)]));
1926         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1927         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1928
1929         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1930                                    Vec::from_slice([BadBehavior(uint::MAX)]));
1931         assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1932
1933         let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
1934         assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1935         assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1936     }
1937
1938     #[test]
1939     fn test_push_at_least() {
1940         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1941                                    Vec::from_slice([GoodBehavior(uint::MAX)]));
1942         let mut buf = Vec::new();
1943         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1944         assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1945
1946         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1947                                    Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
1948         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1949
1950         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1951                                    Vec::from_slice([BadBehavior(1), GoodBehavior(1),
1952                                                     BadBehavior(50), GoodBehavior(uint::MAX)]));
1953         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1954         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1955
1956         let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
1957                                    Vec::from_slice([BadBehavior(uint::MAX)]));
1958         assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1959
1960         let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
1961         assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
1962     }
1963
1964     #[test]
1965     fn test_show() {
1966         use super::*;
1967
1968         assert_eq!(format!("{}", UserRead), "0400".to_string());
1969         assert_eq!(format!("{}", UserFile), "0644".to_string());
1970         assert_eq!(format!("{}", UserExec), "0755".to_string());
1971         assert_eq!(format!("{}", UserRWX),  "0700".to_string());
1972         assert_eq!(format!("{}", GroupRWX), "0070".to_string());
1973         assert_eq!(format!("{}", OtherRWX), "0007".to_string());
1974         assert_eq!(format!("{}", AllPermissions), "0777".to_string());
1975         assert_eq!(format!("{}", UserRead | UserWrite | OtherWrite), "0602".to_string());
1976     }
1977 }