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