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