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