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