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