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