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