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