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