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