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