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