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