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