mod.rs 43.5 KB
Newer Older
C
Chris Wong 已提交
1
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12
/*! Synchronous I/O

B
Brian Anderson 已提交
13 14
This module defines the Rust interface for synchronous I/O.
It models byte-oriented input and output with the Reader and Writer traits.
15 16
Types that implement both `Reader` and `Writer` are called 'streams',
and automatically implement the `Stream` trait.
B
Brian Anderson 已提交
17 18 19 20
Implementations are provided for common I/O streams like
file, TCP, UDP, Unix domain sockets.
Readers and Writers may be composed to add capabilities like string
parsing, encoding, and compression.
21 22 23 24 25 26 27

# Examples

Some examples of obvious things you might want to do

* Read lines from stdin

28
    ```rust
A
Alex Crichton 已提交
29
    use std::io::BufferedReader;
A
Alex Crichton 已提交
30 31
    use std::io::stdin;

32 33
    let mut stdin = BufferedReader::new(stdin());
    for line in stdin.lines() {
34
        print!("{}", line);
35
    }
36
    ```
37

38
* Read a complete file
39

40
    ```rust
A
Alex Crichton 已提交
41 42
    use std::io::File;

43 44
    let contents = File::open(&Path::new("message.txt")).read_to_end();
    ```
45 46 47

* Write a line to a file

48
    ```rust
49
    # #[allow(unused_must_use)];
A
Alex Crichton 已提交
50 51
    use std::io::File;

52 53
    let mut file = File::create(&Path::new("message.txt"));
    file.write(bytes!("hello, file!\n"));
54 55
    # drop(file);
    # ::std::io::fs::unlink(&Path::new("message.txt"));
56
    ```
57 58 59

* Iterate over the lines of a file

60
    ```rust
A
Alex Crichton 已提交
61
    use std::io::BufferedReader;
A
Alex Crichton 已提交
62 63
    use std::io::File;

64 65 66
    let path = Path::new("message.txt");
    let mut file = BufferedReader::new(File::open(&path));
    for line in file.lines() {
67
        print!("{}", line);
68 69
    }
    ```
70

71 72
* Pull the lines of a file into a vector of strings

73
    ```rust
A
Alex Crichton 已提交
74
    use std::io::BufferedReader;
A
Alex Crichton 已提交
75 76
    use std::io::File;

77 78 79 80
    let path = Path::new("message.txt");
    let mut file = BufferedReader::new(File::open(&path));
    let lines: ~[~str] = file.lines().collect();
    ```
81

V
Virgile Andreani 已提交
82
* Make a simple HTTP request
83
  FIXME This needs more improvement: TcpStream constructor taking &str,
84
  `write_str` and `write_line` methods.
85

A
Alex Crichton 已提交
86
    ```rust,should_fail
87
    # #[allow(unused_must_use)];
A
Alex Crichton 已提交
88 89 90
    use std::io::net::ip::SocketAddr;
    use std::io::net::tcp::TcpStream;

91 92 93
    let addr = from_str::<SocketAddr>("127.0.0.1:8080").unwrap();
    let mut socket = TcpStream::connect(addr).unwrap();
    socket.write(bytes!("GET / HTTP/1.0\n\n"));
94
    let response = socket.read_to_end();
95
    ```
96

97 98 99
* Connect based on URL? Requires thinking about where the URL type lives
  and how to make protocol handlers extensible, e.g. the "tcp" protocol
  yields a `TcpStream`.
100
  FIXME this is not implemented now.
101

102 103 104
    ```rust
    // connect("tcp://localhost:8080");
    ```
105 106 107

# Terms

B
Brian Anderson 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
* Reader - An I/O source, reads bytes into a buffer
* Writer - An I/O sink, writes bytes from a buffer
* Stream - Typical I/O sources like files and sockets are both Readers and Writers,
  and are collectively referred to a `streams`.
  such as encoding or decoding

# Blocking and synchrony

When discussing I/O you often hear the terms 'synchronous' and
'asynchronous', along with 'blocking' and 'non-blocking' compared and
contrasted. A synchronous I/O interface performs each I/O operation to
completion before proceeding to the next. Synchronous interfaces are
usually used in imperative style as a sequence of commands. An
asynchronous interface allows multiple I/O requests to be issued
simultaneously, without waiting for each to complete before proceeding
to the next.

Asynchronous interfaces are used to achieve 'non-blocking' I/O. In
traditional single-threaded systems, performing a synchronous I/O
operation means that the program stops all activity (it 'blocks')
until the I/O is complete. Blocking is bad for performance when
there are other computations that could be done.

Asynchronous interfaces are most often associated with the callback
(continuation-passing) style popularised by node.js. Such systems rely
on all computations being run inside an event loop which maintains a
list of all pending I/O events; when one completes the registered
135
callback is run and the code that made the I/O request continues.
B
Brian Anderson 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
Such interfaces achieve non-blocking at the expense of being more
difficult to reason about.

Rust's I/O interface is synchronous - easy to read - and non-blocking by default.

Remember that Rust tasks are 'green threads', lightweight threads that
are multiplexed onto a single operating system thread. If that system
thread blocks then no other task may proceed. Rust tasks are
relatively cheap to create, so as long as other tasks are free to
execute then non-blocking code may be written by simply creating a new
task.

When discussing blocking in regards to Rust's I/O model, we are
concerned with whether performing I/O blocks other Rust tasks from
proceeding. In other words, when a task calls `read`, it must then
wait (or 'sleep', or 'block') until the call to `read` is complete.
During this time, other tasks may or may not be executed, depending on
how `read` is implemented.


Rust's default I/O implementation is non-blocking; by cooperating
directly with the task scheduler it arranges to never block progress
of *other* tasks. Under the hood, Rust uses asynchronous I/O via a
per-scheduler (and hence per-thread) event loop. Synchronous I/O
requests are implemented by descheduling the running task and
performing an asynchronous request; the task is only resumed once the
asynchronous request completes.

164 165
# Error Handling

B
Brian Anderson 已提交
166
I/O is an area where nearly every operation can result in unexpected
A
Alex Crichton 已提交
167 168 169
errors. Errors should be painfully visible when they happen, and handling them
should be easy to work with. It should be convenient to handle specific I/O
errors, and it should also be convenient to not deal with I/O errors.
B
Brian Anderson 已提交
170 171 172 173

Rust's I/O employs a combination of techniques to reduce boilerplate
while still providing feedback about errors. The basic strategy:

A
Alex Crichton 已提交
174 175 176 177 178 179 180 181
* All I/O operations return `IoResult<T>` which is equivalent to
  `Result<T, IoError>`. The core `Result` type is defined in the `std::result`
  module.
* If the `Result` type goes unused, then the compiler will by default emit a
  warning about the unused result.
* Common traits are implemented for `IoResult`, e.g.
  `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
  to be 'unwrapped' before use.
B
Brian Anderson 已提交
182 183

These features combine in the API to allow for expressions like
A
Adrien Tétar 已提交
184 185 186
`File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n"))`
without having to worry about whether "diary.txt" exists or whether
the write succeeds. As written, if either `new` or `write_line`
A
Alex Crichton 已提交
187 188
encounters an error then the result of the entire expression will
be an error.
A
Adrien Tétar 已提交
189 190 191 192

If you wanted to handle the error though you might write:

```rust
193
# #[allow(unused_must_use)];
A
Adrien Tétar 已提交
194 195
use std::io::File;

A
Alex Crichton 已提交
196 197 198
match File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")) {
    Ok(()) => { /* succeeded */ }
    Err(e) => println!("failed to write to my diary: {}", e),
A
Adrien Tétar 已提交
199
}
A
Alex Crichton 已提交
200

A
Adrien Tétar 已提交
201 202
# ::std::io::fs::unlink(&Path::new("diary.txt"));
```
B
Brian Anderson 已提交
203

A
Alex Crichton 已提交
204 205 206 207 208 209 210 211
So what actually happens if `create` encounters an error?
It's important to know that what `new` returns is not a `File`
but an `IoResult<File>`.  If the file does not open, then `new` will simply
return `Err(..)`. Because there is an implementation of `Writer` (the trait
required ultimately required for types to implement `write_line`) there is no
need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
on it. If `new` returned an `Err(..)` then the followup call to `write_line`
will also return an error.
B
Brian Anderson 已提交
212

213
# Issues with i/o scheduler affinity, work stealing, task pinning
B
Brian Anderson 已提交
214

215 216 217 218
# Resource management

* `close` vs. RAII

B
Brian Anderson 已提交
219 220 221
# Paths, URLs and overloaded constructors


222

B
Brian Anderson 已提交
223 224 225 226 227
# Scope

In scope for core

* Url?
228 229 230 231 232 233 234 235

Some I/O things don't belong in core

  - url
  - net - `fn connect`
    - http
  - flate

B
Brian Anderson 已提交
236 237 238 239 240
Out of scope

* Async I/O. We'll probably want it eventually


241
# FIXME Questions and issues
242 243 244 245 246 247 248 249 250

* Should default constructors take `Path` or `&str`? `Path` makes simple cases verbose.
  Overloading would be nice.
* Add overloading for Path and &str and Url &str
* stdin/err/out
* print, println, etc.
* fsync
* relationship with filesystem querying, Directory, File types etc.
* Rename Reader/Writer to ByteReader/Writer, make Reader/Writer generic?
B
Brian Anderson 已提交
251
* Can Port and Chan be implementations of a generic Reader<T>/Writer<T>?
252 253 254 255 256 257 258
* Trait for things that are both readers and writers, Stream?
* How to handle newline conversion
* String conversion
* open vs. connect for generic stream opening
* Do we need `close` at all? dtors might be good enough
* How does I/O relate to the Iterator trait?
* std::base64 filters
B
Brian Anderson 已提交
259
* Using conditions is a big unknown since we don't have much experience with them
260
* Too many uses of OtherIoError
261 262 263

*/

A
Alex Crichton 已提交
264
#[allow(missing_doc)];
265
#[deny(unused_must_use)];
A
Alex Crichton 已提交
266

267
use cast;
268
use char::Char;
A
Alex Crichton 已提交
269
use container::Container;
A
Alex Crichton 已提交
270
use fmt;
271
use int;
A
Alex Crichton 已提交
272
use iter::Iterator;
273
use option::{Option, Some, None};
A
Alex Crichton 已提交
274
use path::Path;
275
use result::{Ok, Err, Result};
A
Alex Crichton 已提交
276
use str::{StrSlice, OwnedStr};
A
Alex Crichton 已提交
277
use str;
278 279 280
use to_str::ToStr;
use uint;
use unstable::finally::Finally;
281
use vec::{OwnedVector, MutableVector, ImmutableVector, OwnedCloneableVector};
282
use vec;
283 284 285 286 287 288 289 290

// Reexports
pub use self::stdio::stdin;
pub use self::stdio::stdout;
pub use self::stdio::stderr;
pub use self::stdio::print;
pub use self::stdio::println;

291
pub use self::fs::File;
J
Jeff Olson 已提交
292
pub use self::timer::Timer;
293 294 295 296
pub use self::net::ip::IpAddr;
pub use self::net::tcp::TcpListener;
pub use self::net::tcp::TcpStream;
pub use self::net::udp::UdpStream;
297 298
pub use self::pipe::PipeStream;
pub use self::process::Process;
299

A
Alex Crichton 已提交
300 301 302 303 304
pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
                         LineBufferedWriter};
pub use self::comm_adapters::{PortReader, ChanWriter};

305 306
/// Various utility functions useful for writing I/O tests
pub mod test;
A
Alex Crichton 已提交
307

308 309
/// Synchronous, non-blocking filesystem operations.
pub mod fs;
310

311 312 313 314 315 316
/// Synchronous, in-memory I/O.
pub mod pipe;

/// Child process management.
pub mod process;

317
/// Synchronous, non-blocking network I/O.
318
pub mod net;
319 320

/// Readers and Writers for memory buffers and strings.
A
Alex Crichton 已提交
321
mod mem;
322 323 324 325

/// Non-blocking access to stdin, stdout, stderr
pub mod stdio;

A
Alex Crichton 已提交
326 327
/// Implementations for Result
mod result;
328

329
/// Extension traits
330
pub mod extensions;
331

J
Jeff Olson 已提交
332
/// Basic Timer
333
pub mod timer;
J
Jeff Olson 已提交
334

S
Steven Fackler 已提交
335
/// Buffered I/O wrappers
A
Alex Crichton 已提交
336
mod buffered;
S
Steven Fackler 已提交
337

338 339 340
/// Signal handling
pub mod signal;

S
Steven Fackler 已提交
341 342 343
/// Utility implementations of Reader and Writer
pub mod util;

A
Alex Crichton 已提交
344
/// Adapatation of Chan/Port types to a Writer/Reader type.
A
Alex Crichton 已提交
345
mod comm_adapters;
A
Alex Crichton 已提交
346

347
/// The default buffer size for various I/O operations
A
Alex Crichton 已提交
348 349
// libuv recommends 64k buffers to maximize throughput
// https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
350
static DEFAULT_BUF_SIZE: uint = 1024 * 64;
351

A
Alex Crichton 已提交
352 353
pub type IoResult<T> = Result<T, IoError>;

354 355
/// The type passed to I/O condition handlers to indicate error
///
356
/// # FIXME
357 358
///
/// Is something like this sufficient? It's kind of archaic
A
Alex Crichton 已提交
359
#[deriving(Eq, Clone)]
360 361 362 363 364 365
pub struct IoError {
    kind: IoErrorKind,
    desc: &'static str,
    detail: Option<~str>
}

366
impl fmt::Show for IoError {
367 368 369
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        if_ok!(fmt.buf.write_str(self.desc));
        match self.detail {
A
Alex Crichton 已提交
370 371 372 373 374 375
            Some(ref s) => write!(fmt.buf, " ({})", *s),
            None => Ok(())
        }
    }
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389
// FIXME: #8242 implementing manually because deriving doesn't work for some reason
impl ToStr for IoError {
    fn to_str(&self) -> ~str {
        let mut s = ~"IoError { kind: ";
        s.push_str(self.kind.to_str());
        s.push_str(", desc: ");
        s.push_str(self.desc);
        s.push_str(", detail: ");
        s.push_str(self.detail.to_str());
        s.push_str(" }");
        s
    }
}

A
Alex Crichton 已提交
390
#[deriving(Eq, Clone)]
391
pub enum IoErrorKind {
392 393
    OtherIoError,
    EndOfFile,
394
    FileNotFound,
395
    PermissionDenied,
396 397
    ConnectionFailed,
    Closed,
398
    ConnectionRefused,
B
Brian Anderson 已提交
399
    ConnectionReset,
400
    ConnectionAborted,
K
klutzy 已提交
401
    NotConnected,
402 403 404
    BrokenPipe,
    PathAlreadyExists,
    PathDoesntExist,
405
    MismatchedFileTypeForOperation,
406
    ResourceUnavailable,
407
    IoUnavailable,
408
    InvalidInput,
409
}
410

411 412 413 414 415 416 417 418 419 420 421 422
// FIXME: #8242 implementing manually because deriving doesn't work for some reason
impl ToStr for IoErrorKind {
    fn to_str(&self) -> ~str {
        match *self {
            OtherIoError => ~"OtherIoError",
            EndOfFile => ~"EndOfFile",
            FileNotFound => ~"FileNotFound",
            PermissionDenied => ~"PermissionDenied",
            ConnectionFailed => ~"ConnectionFailed",
            Closed => ~"Closed",
            ConnectionRefused => ~"ConnectionRefused",
            ConnectionReset => ~"ConnectionReset",
K
klutzy 已提交
423
            NotConnected => ~"NotConnected",
424 425 426
            BrokenPipe => ~"BrokenPipe",
            PathAlreadyExists => ~"PathAlreadyExists",
            PathDoesntExist => ~"PathDoesntExist",
427 428
            MismatchedFileTypeForOperation => ~"MismatchedFileTypeForOperation",
            IoUnavailable => ~"IoUnavailable",
429
            ResourceUnavailable => ~"ResourceUnavailable",
430
            ConnectionAborted => ~"ConnectionAborted",
431
            InvalidInput => ~"InvalidInput",
432 433 434 435
        }
    }
}

436
pub trait Reader {
437

A
Alex Crichton 已提交
438
    // Only method which need to get implemented for this trait
439

440
    /// Read bytes, up to the length of `buf` and place them in `buf`.
441
    /// Returns the number of bytes read. The number of bytes read my
A
Alex Crichton 已提交
442
    /// be less than the number requested, even 0. Returns `Err` on EOF.
443
    ///
A
Alex Crichton 已提交
444
    /// # Error
445
    ///
A
Alex Crichton 已提交
446 447 448 449
    /// If an error occurs during this I/O operation, then it is returned as
    /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
    /// inspected for in the error's `kind` field. Also note that reading 0
    /// bytes is not considered an error in all circumstances
A
Alex Crichton 已提交
450
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
451

452 453
    // Convenient helper methods based on the above methods

A
Alex Crichton 已提交
454
    /// Reads a single byte. Returns `Err` on EOF.
A
Alex Crichton 已提交
455
    fn read_byte(&mut self) -> IoResult<u8> {
456
        let mut buf = [0];
A
Alex Crichton 已提交
457 458 459 460 461 462 463 464
        loop {
            match self.read(buf) {
                Ok(0) => {
                    debug!("read 0 bytes. trying again");
                }
                Ok(1) => return Ok(buf[0]),
                Ok(_) => unreachable!(),
                Err(e) => return Err(e)
465 466 467 468 469 470 471
            }
        }
    }

    /// Reads `len` bytes and appends them to a vector.
    ///
    /// May push fewer than the requested number of bytes on error
A
Alex Crichton 已提交
472 473 474
    /// or EOF. If `Ok(())` is returned, then all of the requested bytes were
    /// pushed on to the vector, otherwise the amount `len` bytes couldn't be
    /// read (an error was encountered), and the error is returned.
A
Alex Crichton 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488
    fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> IoResult<()> {
        let start_len = buf.len();
        let mut total_read = 0;

        buf.reserve_additional(len);
        unsafe { buf.set_len(start_len + len); }

        (|| {
            while total_read < len {
                let len = buf.len();
                let slice = buf.mut_slice(start_len + total_read, len);
                match self.read(slice) {
                    Ok(nread) => {
                        total_read += nread;
489
                    }
A
Alex Crichton 已提交
490
                    Err(e) => return Err(e)
491
                }
A
Alex Crichton 已提交
492 493 494
            }
            Ok(())
        }).finally(|| unsafe { buf.set_len(start_len + total_read) })
495 496 497 498
    }

    /// Reads `len` bytes and gives you back a new vector of length `len`
    ///
A
Alex Crichton 已提交
499
    /// # Error
500
    ///
A
Alex Crichton 已提交
501 502 503 504 505
    /// Fails with the same conditions as `read`. Additionally returns error on
    /// on EOF. Note that if an error is returned, then some number of bytes may
    /// have already been consumed from the underlying reader, and they are lost
    /// (not returned as part of the error). If this is unacceptable, then it is
    /// recommended to use the `push_bytes` or `read` methods.
A
Alex Crichton 已提交
506
    fn read_bytes(&mut self, len: uint) -> IoResult<~[u8]> {
507
        let mut buf = vec::with_capacity(len);
A
Alex Crichton 已提交
508 509 510 511
        match self.push_bytes(&mut buf, len) {
            Ok(()) => Ok(buf),
            Err(e) => Err(e),
        }
512 513 514 515
    }

    /// Reads all remaining bytes from the stream.
    ///
A
Alex Crichton 已提交
516 517 518 519
    /// # Error
    ///
    /// Returns any non-EOF error immediately. Previously read bytes are
    /// discarded when an error is returned.
520
    ///
521
    /// When EOF is encountered, all bytes read up to that point are returned.
A
Alex Crichton 已提交
522
    fn read_to_end(&mut self) -> IoResult<~[u8]> {
523
        let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE);
A
Alex Crichton 已提交
524 525 526
        loop {
            match self.push_bytes(&mut buf, DEFAULT_BUF_SIZE) {
                Ok(()) => {}
527
                Err(ref e) if e.kind == EndOfFile => break,
A
Alex Crichton 已提交
528
                Err(e) => return Err(e)
529
            }
A
Alex Crichton 已提交
530 531
        }
        return Ok(buf);
532 533
    }

534 535 536
    /// Reads all of the remaining bytes of this stream, interpreting them as a
    /// UTF-8 encoded stream. The corresponding string is returned.
    ///
A
Alex Crichton 已提交
537
    /// # Error
538
    ///
A
Alex Crichton 已提交
539 540 541
    /// This function returns all of the same errors as `read_to_end` with an
    /// additional error if the reader's contents are not a valid sequence of
    /// UTF-8 bytes.
A
Alex Crichton 已提交
542 543 544 545 546
    fn read_to_str(&mut self) -> IoResult<~str> {
        self.read_to_end().and_then(|s| {
            match str::from_utf8_owned(s) {
                Some(s) => Ok(s),
                None => Err(standard_error(InvalidInput)),
547
            }
A
Alex Crichton 已提交
548
        })
549 550
    }

551 552 553
    /// Create an iterator that reads a single byte on
    /// each iteration, until EOF.
    ///
A
Alex Crichton 已提交
554
    /// # Error
555
    ///
A
Alex Crichton 已提交
556 557 558 559
    /// The iterator protocol causes all specifics about errors encountered to
    /// be swallowed. All errors will be signified by returning `None` from the
    /// iterator. If this is undesirable, it is recommended to use the
    /// `read_byte` method.
P
Palmer Cox 已提交
560 561
    fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self> {
        extensions::Bytes::new(self)
562 563 564 565 566 567 568
    }

    // Byte conversion helpers

    /// Reads `n` little-endian unsigned integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
A
Alex Crichton 已提交
569
    fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
570 571 572 573 574 575
        assert!(nbytes > 0 && nbytes <= 8);

        let mut val = 0u64;
        let mut pos = 0;
        let mut i = nbytes;
        while i > 0 {
A
Alex Crichton 已提交
576
            val += (if_ok!(self.read_u8()) as u64) << pos;
577 578 579
            pos += 8;
            i -= 1;
        }
A
Alex Crichton 已提交
580
        Ok(val)
581 582 583 584 585
    }

    /// Reads `n` little-endian signed integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
A
Alex Crichton 已提交
586 587
    fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
        self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
588 589 590 591 592
    }

    /// Reads `n` big-endian unsigned integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
A
Alex Crichton 已提交
593
    fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
594 595 596 597 598 599
        assert!(nbytes > 0 && nbytes <= 8);

        let mut val = 0u64;
        let mut i = nbytes;
        while i > 0 {
            i -= 1;
A
Alex Crichton 已提交
600
            val += (if_ok!(self.read_u8()) as u64) << i * 8;
601
        }
A
Alex Crichton 已提交
602
        Ok(val)
603 604 605 606 607
    }

    /// Reads `n` big-endian signed integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
A
Alex Crichton 已提交
608 609
    fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
        self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
610 611 612 613 614
    }

    /// Reads a little-endian unsigned integer.
    ///
    /// The number of bytes returned is system-dependant.
A
Alex Crichton 已提交
615 616
    fn read_le_uint(&mut self) -> IoResult<uint> {
        self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
617 618 619 620 621
    }

    /// Reads a little-endian integer.
    ///
    /// The number of bytes returned is system-dependant.
A
Alex Crichton 已提交
622 623
    fn read_le_int(&mut self) -> IoResult<int> {
        self.read_le_int_n(int::BYTES).map(|i| i as int)
624 625 626 627 628
    }

    /// Reads a big-endian unsigned integer.
    ///
    /// The number of bytes returned is system-dependant.
A
Alex Crichton 已提交
629 630
    fn read_be_uint(&mut self) -> IoResult<uint> {
        self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
631 632 633 634 635
    }

    /// Reads a big-endian integer.
    ///
    /// The number of bytes returned is system-dependant.
A
Alex Crichton 已提交
636 637
    fn read_be_int(&mut self) -> IoResult<int> {
        self.read_be_int_n(int::BYTES).map(|i| i as int)
638 639 640 641 642
    }

    /// Reads a big-endian `u64`.
    ///
    /// `u64`s are 8 bytes long.
A
Alex Crichton 已提交
643
    fn read_be_u64(&mut self) -> IoResult<u64> {
644
        self.read_be_uint_n(8)
645 646 647 648 649
    }

    /// Reads a big-endian `u32`.
    ///
    /// `u32`s are 4 bytes long.
A
Alex Crichton 已提交
650 651
    fn read_be_u32(&mut self) -> IoResult<u32> {
        self.read_be_uint_n(4).map(|i| i as u32)
652 653 654 655 656
    }

    /// Reads a big-endian `u16`.
    ///
    /// `u16`s are 2 bytes long.
A
Alex Crichton 已提交
657 658
    fn read_be_u16(&mut self) -> IoResult<u16> {
        self.read_be_uint_n(2).map(|i| i as u16)
659 660 661 662 663
    }

    /// Reads a big-endian `i64`.
    ///
    /// `i64`s are 8 bytes long.
A
Alex Crichton 已提交
664
    fn read_be_i64(&mut self) -> IoResult<i64> {
665
        self.read_be_int_n(8)
666 667 668 669 670
    }

    /// Reads a big-endian `i32`.
    ///
    /// `i32`s are 4 bytes long.
A
Alex Crichton 已提交
671 672
    fn read_be_i32(&mut self) -> IoResult<i32> {
        self.read_be_int_n(4).map(|i| i as i32)
673 674 675 676 677
    }

    /// Reads a big-endian `i16`.
    ///
    /// `i16`s are 2 bytes long.
A
Alex Crichton 已提交
678 679
    fn read_be_i16(&mut self) -> IoResult<i16> {
        self.read_be_int_n(2).map(|i| i as i16)
680 681 682 683 684
    }

    /// Reads a big-endian `f64`.
    ///
    /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
A
Alex Crichton 已提交
685 686 687 688
    fn read_be_f64(&mut self) -> IoResult<f64> {
        self.read_be_u64().map(|i| unsafe {
            cast::transmute::<u64, f64>(i)
        })
689 690 691 692 693
    }

    /// Reads a big-endian `f32`.
    ///
    /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
A
Alex Crichton 已提交
694 695 696 697
    fn read_be_f32(&mut self) -> IoResult<f32> {
        self.read_be_u32().map(|i| unsafe {
            cast::transmute::<u32, f32>(i)
        })
698 699 700 701 702
    }

    /// Reads a little-endian `u64`.
    ///
    /// `u64`s are 8 bytes long.
A
Alex Crichton 已提交
703
    fn read_le_u64(&mut self) -> IoResult<u64> {
704
        self.read_le_uint_n(8)
705 706 707 708 709
    }

    /// Reads a little-endian `u32`.
    ///
    /// `u32`s are 4 bytes long.
A
Alex Crichton 已提交
710 711
    fn read_le_u32(&mut self) -> IoResult<u32> {
        self.read_le_uint_n(4).map(|i| i as u32)
712 713 714 715 716
    }

    /// Reads a little-endian `u16`.
    ///
    /// `u16`s are 2 bytes long.
A
Alex Crichton 已提交
717 718
    fn read_le_u16(&mut self) -> IoResult<u16> {
        self.read_le_uint_n(2).map(|i| i as u16)
719 720 721 722 723
    }

    /// Reads a little-endian `i64`.
    ///
    /// `i64`s are 8 bytes long.
A
Alex Crichton 已提交
724
    fn read_le_i64(&mut self) -> IoResult<i64> {
725
        self.read_le_int_n(8)
726 727 728 729 730
    }

    /// Reads a little-endian `i32`.
    ///
    /// `i32`s are 4 bytes long.
A
Alex Crichton 已提交
731 732
    fn read_le_i32(&mut self) -> IoResult<i32> {
        self.read_le_int_n(4).map(|i| i as i32)
733 734 735 736 737
    }

    /// Reads a little-endian `i16`.
    ///
    /// `i16`s are 2 bytes long.
A
Alex Crichton 已提交
738 739
    fn read_le_i16(&mut self) -> IoResult<i16> {
        self.read_le_int_n(2).map(|i| i as i16)
740 741 742 743 744
    }

    /// Reads a little-endian `f64`.
    ///
    /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
A
Alex Crichton 已提交
745 746 747 748
    fn read_le_f64(&mut self) -> IoResult<f64> {
        self.read_le_u64().map(|i| unsafe {
            cast::transmute::<u64, f64>(i)
        })
749 750 751 752 753
    }

    /// Reads a little-endian `f32`.
    ///
    /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
A
Alex Crichton 已提交
754 755 756 757
    fn read_le_f32(&mut self) -> IoResult<f32> {
        self.read_le_u32().map(|i| unsafe {
            cast::transmute::<u32, f32>(i)
        })
758 759 760 761 762
    }

    /// Read a u8.
    ///
    /// `u8`s are 1 byte.
A
Alex Crichton 已提交
763 764
    fn read_u8(&mut self) -> IoResult<u8> {
        self.read_byte()
765 766 767 768 769
    }

    /// Read an i8.
    ///
    /// `i8`s are 1 byte.
A
Alex Crichton 已提交
770 771
    fn read_i8(&mut self) -> IoResult<i8> {
        self.read_byte().map(|i| i as i8)
772 773
    }

774
}
775

776
impl Reader for ~Reader {
A
Alex Crichton 已提交
777
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
778 779
}

E
Erik Price 已提交
780
impl<'a> Reader for &'a mut Reader {
A
Alex Crichton 已提交
781
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
782 783
}

784 785 786 787 788
fn extend_sign(val: u64, nbytes: uint) -> i64 {
    let shift = (8 - nbytes) * 8;
    (val << shift) as i64 >> shift
}

789
pub trait Writer {
A
Alex Crichton 已提交
790
    /// Write the entirety of a given buffer
791
    ///
A
Alex Crichton 已提交
792
    /// # Errors
793
    ///
A
Alex Crichton 已提交
794 795 796 797
    /// If an error happens during the I/O operation, the error is returned as
    /// `Err`. Note that it is considered an error if the entire buffer could
    /// not be written, and if an error is returned then it is unknown how much
    /// data (if any) was actually written.
A
Alex Crichton 已提交
798
    fn write(&mut self, buf: &[u8]) -> IoResult<()>;
799

800 801 802
    /// Flush this output stream, ensuring that all intermediately buffered
    /// contents reach their destination.
    ///
H
Huon Wilson 已提交
803
    /// This is by default a no-op and implementers of the `Writer` trait should
804
    /// decide whether their stream needs to be buffered or not.
A
Alex Crichton 已提交
805
    fn flush(&mut self) -> IoResult<()> { Ok(()) }
806

807 808 809 810 811 812
    /// Write a rust string into this sink.
    ///
    /// The bytes written will be the UTF-8 encoded version of the input string.
    /// If other encodings are desired, it is recommended to compose this stream
    /// with another performing the conversion, or to use `write` with a
    /// converted byte-array instead.
A
Alex Crichton 已提交
813 814
    fn write_str(&mut self, s: &str) -> IoResult<()> {
        self.write(s.as_bytes())
815 816 817 818 819 820 821 822 823
    }

    /// Writes a string into this sink, and then writes a literal newline (`\n`)
    /// byte afterwards. Note that the writing of the newline is *not* atomic in
    /// the sense that the call to `write` is invoked twice (once with the
    /// string and once with a newline character).
    ///
    /// If other encodings or line ending flavors are desired, it is recommended
    /// that the `write` method is used specifically instead.
A
Alex Crichton 已提交
824 825
    fn write_line(&mut self, s: &str) -> IoResult<()> {
        self.write_str(s).and_then(|()| self.write(['\n' as u8]))
826 827
    }

828
    /// Write a single char, encoded as UTF-8.
A
Alex Crichton 已提交
829
    fn write_char(&mut self, c: char) -> IoResult<()> {
830 831
        let mut buf = [0u8, ..4];
        let n = c.encode_utf8(buf.as_mut_slice());
A
Alex Crichton 已提交
832
        self.write(buf.slice_to(n))
833 834
    }

835
    /// Write the result of passing n through `int::to_str_bytes`.
A
Alex Crichton 已提交
836
    fn write_int(&mut self, n: int) -> IoResult<()> {
837 838 839 840
        int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
    }

    /// Write the result of passing n through `uint::to_str_bytes`.
A
Alex Crichton 已提交
841
    fn write_uint(&mut self, n: uint) -> IoResult<()> {
842 843 844 845
        uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
    }

    /// Write a little-endian uint (number of bytes depends on system).
A
Alex Crichton 已提交
846
    fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
C
Chris Wong 已提交
847
        extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
848 849 850
    }

    /// Write a little-endian int (number of bytes depends on system).
A
Alex Crichton 已提交
851
    fn write_le_int(&mut self, n: int) -> IoResult<()> {
C
Chris Wong 已提交
852
        extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
853 854 855
    }

    /// Write a big-endian uint (number of bytes depends on system).
A
Alex Crichton 已提交
856
    fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
C
Chris Wong 已提交
857
        extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
858 859 860
    }

    /// Write a big-endian int (number of bytes depends on system).
A
Alex Crichton 已提交
861
    fn write_be_int(&mut self, n: int) -> IoResult<()> {
C
Chris Wong 已提交
862
        extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
863 864 865
    }

    /// Write a big-endian u64 (8 bytes).
A
Alex Crichton 已提交
866
    fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
867 868 869 870
        extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
    }

    /// Write a big-endian u32 (4 bytes).
A
Alex Crichton 已提交
871
    fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
872 873 874 875
        extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a big-endian u16 (2 bytes).
A
Alex Crichton 已提交
876
    fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
877 878 879 880
        extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a big-endian i64 (8 bytes).
A
Alex Crichton 已提交
881
    fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
882 883 884 885
        extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
    }

    /// Write a big-endian i32 (4 bytes).
A
Alex Crichton 已提交
886
    fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
887 888 889 890
        extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a big-endian i16 (2 bytes).
A
Alex Crichton 已提交
891
    fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
892 893 894 895
        extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
A
Alex Crichton 已提交
896
    fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
897 898 899 900 901 902
        unsafe {
            self.write_be_u64(cast::transmute(f))
        }
    }

    /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
A
Alex Crichton 已提交
903
    fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
904 905 906 907 908 909
        unsafe {
            self.write_be_u32(cast::transmute(f))
        }
    }

    /// Write a little-endian u64 (8 bytes).
A
Alex Crichton 已提交
910
    fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
911 912 913 914
        extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
    }

    /// Write a little-endian u32 (4 bytes).
A
Alex Crichton 已提交
915
    fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
916 917 918 919
        extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a little-endian u16 (2 bytes).
A
Alex Crichton 已提交
920
    fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
921 922 923 924
        extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a little-endian i64 (8 bytes).
A
Alex Crichton 已提交
925
    fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
926 927 928 929
        extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
    }

    /// Write a little-endian i32 (4 bytes).
A
Alex Crichton 已提交
930
    fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
931 932 933 934
        extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a little-endian i16 (2 bytes).
A
Alex Crichton 已提交
935
    fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
936 937 938 939 940
        extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a little-endian IEEE754 double-precision floating-point
    /// (8 bytes).
A
Alex Crichton 已提交
941
    fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
942 943 944 945 946 947 948
        unsafe {
            self.write_le_u64(cast::transmute(f))
        }
    }

    /// Write a little-endian IEEE754 single-precision floating-point
    /// (4 bytes).
A
Alex Crichton 已提交
949
    fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
950 951 952 953 954 955
        unsafe {
            self.write_le_u32(cast::transmute(f))
        }
    }

    /// Write a u8 (1 byte).
A
Alex Crichton 已提交
956
    fn write_u8(&mut self, n: u8) -> IoResult<()> {
957 958 959 960
        self.write([n])
    }

    /// Write a i8 (1 byte).
A
Alex Crichton 已提交
961
    fn write_i8(&mut self, n: i8) -> IoResult<()> {
962 963
        self.write([n as u8])
    }
964 965
}

966
impl Writer for ~Writer {
A
Alex Crichton 已提交
967 968
    fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
    fn flush(&mut self) -> IoResult<()> { self.flush() }
969 970
}

E
Erik Price 已提交
971
impl<'a> Writer for &'a mut Writer {
A
Alex Crichton 已提交
972 973
    fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
    fn flush(&mut self) -> IoResult<()> { self.flush() }
974 975
}

B
Brian Anderson 已提交
976
pub trait Stream: Reader + Writer { }
977

978
impl<T: Reader + Writer> Stream for T {}
979

980 981 982 983 984
/// An iterator that reads a line on each iteration,
/// until `.read_line()` returns `None`.
///
/// # Notes about the Iteration Protocol
///
P
Palmer Cox 已提交
985
/// The `Lines` may yield `None` and thus terminate
986 987 988
/// an iteration, but continue to yield elements if iteration
/// is attempted again.
///
A
Alex Crichton 已提交
989
/// # Error
990
///
A
Alex Crichton 已提交
991 992 993
/// This iterator will swallow all I/O errors, transforming `Err` values to
/// `None`. If errors need to be handled, it is recommended to use the
/// `read_line` method directly.
P
Palmer Cox 已提交
994
pub struct Lines<'r, T> {
995 996 997
    priv buffer: &'r mut T,
}

P
Palmer Cox 已提交
998
impl<'r, T: Buffer> Iterator<~str> for Lines<'r, T> {
999
    fn next(&mut self) -> Option<~str> {
A
Alex Crichton 已提交
1000
        self.buffer.read_line().ok()
1001 1002 1003
    }
}

A
Alex Crichton 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
/// A Buffer is a type of reader which has some form of internal buffering to
/// allow certain kinds of reading operations to be more optimized than others.
/// This type extends the `Reader` trait with a few methods that are not
/// possible to reasonably implement with purely a read interface.
pub trait Buffer: Reader {
    /// Fills the internal buffer of this object, returning the buffer contents.
    /// Note that none of the contents will be "read" in the sense that later
    /// calling `read` may return the same contents.
    ///
    /// The `consume` function must be called with the number of bytes that are
    /// consumed from this buffer returned to ensure that the bytes are never
    /// returned twice.
    ///
A
Alex Crichton 已提交
1017
    /// # Error
A
Alex Crichton 已提交
1018
    ///
A
Alex Crichton 已提交
1019 1020 1021
    /// This function will return an I/O error if the underlying reader was
    /// read, but returned an error. Note that it is not an error to return a
    /// 0-length buffer.
A
Alex Crichton 已提交
1022
    fn fill<'a>(&'a mut self) -> IoResult<&'a [u8]>;
A
Alex Crichton 已提交
1023 1024 1025 1026 1027

    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
    /// so they should no longer be returned in calls to `fill` or `read`.
    fn consume(&mut self, amt: uint);

1028
    /// Reads the next line of input, interpreted as a sequence of UTF-8
A
Alex Crichton 已提交
1029 1030 1031
    /// encoded unicode codepoints. If a newline is encountered, then the
    /// newline is contained in the returned string.
    ///
A
Adrien Tétar 已提交
1032 1033 1034
    /// # Example
    ///
    /// ```rust
A
Alex Crichton 已提交
1035
    /// use std::io::{BufferedReader, stdin};
A
Adrien Tétar 已提交
1036
    ///
A
Alex Crichton 已提交
1037
    /// let mut reader = BufferedReader::new(stdin());
A
Adrien Tétar 已提交
1038
    ///
A
Alex Crichton 已提交
1039
    /// let input = reader.read_line().ok().unwrap_or(~"nothing");
A
Adrien Tétar 已提交
1040 1041
    /// ```
    ///
A
Alex Crichton 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050
    /// # Error
    ///
    /// This function has the same error semantics as `read_until`:
    ///
    /// * All non-EOF errors will be returned immediately
    /// * If an error is returned previously consumed bytes are lost
    /// * EOF is only returned if no bytes have been read
    /// * Reach EOF may mean that the delimiter is not present in the return
    ///   value
A
Alex Crichton 已提交
1051
    ///
A
Alex Crichton 已提交
1052 1053
    /// Additionally, this function can fail if the line of input read is not a
    /// valid UTF-8 sequence of bytes.
A
Alex Crichton 已提交
1054
    fn read_line(&mut self) -> IoResult<~str> {
A
Alex Crichton 已提交
1055 1056 1057 1058 1059 1060
        self.read_until('\n' as u8).and_then(|line|
            match str::from_utf8_owned(line) {
                Some(s) => Ok(s),
                None => Err(standard_error(InvalidInput)),
            }
        )
A
Alex Crichton 已提交
1061 1062
    }

1063 1064
    /// Create an iterator that reads a line on each iteration until EOF.
    ///
A
Alex Crichton 已提交
1065
    /// # Error
1066
    ///
A
Alex Crichton 已提交
1067 1068 1069
    /// This iterator will transform all error values to `None`, discarding the
    /// cause of the error. If this is undesirable, it is recommended to call
    /// `read_line` directly.
P
Palmer Cox 已提交
1070
    fn lines<'r>(&'r mut self) -> Lines<'r, Self> {
A
Alex Crichton 已提交
1071
        Lines { buffer: self }
1072 1073
    }

H
Huon Wilson 已提交
1074
    /// Reads a sequence of bytes leading up to a specified delimiter. Once the
A
Alex Crichton 已提交
1075 1076 1077
    /// specified byte is encountered, reading ceases and the bytes up to and
    /// including the delimiter are returned.
    ///
A
Alex Crichton 已提交
1078
    /// # Error
A
Alex Crichton 已提交
1079
    ///
A
Alex Crichton 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088
    /// If any I/O error is encountered other than EOF, the error is immediately
    /// returned. Note that this may discard bytes which have already been read,
    /// and those bytes will *not* be returned. It is recommended to use other
    /// methods if this case is worrying.
    ///
    /// If EOF is encountered, then this function will return EOF if 0 bytes
    /// have been read, otherwise the pending byte buffer is returned. This
    /// is the reason that the byte buffer returned may not always contain the
    /// delimiter.
A
Alex Crichton 已提交
1089
    fn read_until(&mut self, byte: u8) -> IoResult<~[u8]> {
A
Alex Crichton 已提交
1090
        let mut res = ~[];
1091

A
Alex Crichton 已提交
1092 1093 1094
        let mut used;
        loop {
            {
A
Alex Crichton 已提交
1095 1096 1097 1098 1099 1100 1101 1102
                let available = match self.fill() {
                    Ok(n) => n,
                    Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
                        used = 0;
                        break
                    }
                    Err(e) => return Err(e)
                };
A
Alex Crichton 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111
                match available.iter().position(|&b| b == byte) {
                    Some(i) => {
                        res.push_all(available.slice_to(i + 1));
                        used = i + 1;
                        break
                    }
                    None => {
                        res.push_all(available);
                        used = available.len();
A
Alex Crichton 已提交
1112 1113
                    }
                }
A
Alex Crichton 已提交
1114
            }
A
Alex Crichton 已提交
1115
            self.consume(used);
A
Alex Crichton 已提交
1116 1117 1118
        }
        self.consume(used);
        Ok(res)
A
Alex Crichton 已提交
1119
    }
1120 1121 1122

    /// Reads the next utf8-encoded character from the underlying stream.
    ///
A
Alex Crichton 已提交
1123
    /// # Error
1124
    ///
A
Alex Crichton 已提交
1125 1126 1127
    /// If an I/O error occurs, or EOF, then this function will return `Err`.
    /// This function will also return error if the stream does not contain a
    /// valid utf-8 encoded codepoint as the next few bytes in the stream.
A
Alex Crichton 已提交
1128
    fn read_char(&mut self) -> IoResult<char> {
1129 1130 1131 1132 1133
        let first_byte = if_ok!(self.read_byte());
        let width = str::utf8_char_width(first_byte);
        if width == 1 { return Ok(first_byte as char) }
        if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
        let mut buf = [first_byte, 0, 0, 0];
1134
        {
1135 1136
            let mut start = 1;
            while start < width {
A
Alex Crichton 已提交
1137 1138 1139 1140
                match if_ok!(self.read(buf.mut_slice(start, width))) {
                    n if n == width - start => break,
                    n if n < width - start => { start += n; }
                    _ => return Err(standard_error(InvalidInput)),
1141 1142
                }
            }
1143
        }
1144
        match str::from_utf8(buf.slice_to(width)) {
A
Alex Crichton 已提交
1145 1146
            Some(s) => Ok(s.char_at(0)),
            None => Err(standard_error(InvalidInput))
1147 1148
        }
    }
A
Alex Crichton 已提交
1149 1150
}

1151 1152 1153 1154 1155 1156 1157 1158 1159
pub enum SeekStyle {
    /// Seek from the beginning of the stream
    SeekSet,
    /// Seek from the end of the stream
    SeekEnd,
    /// Seek from the current position
    SeekCur,
}

1160
/// # FIXME
1161
/// * Are `u64` and `i64` the right choices?
1162
pub trait Seek {
1163
    /// Return position of file cursor in the stream
A
Alex Crichton 已提交
1164
    fn tell(&self) -> IoResult<u64>;
1165 1166 1167 1168 1169

    /// Seek to an offset in a stream
    ///
    /// A successful seek clears the EOF indicator.
    ///
1170
    /// # FIXME
1171 1172
    ///
    /// * What is the behavior when seeking past the end of a stream?
A
Alex Crichton 已提交
1173
    fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1174 1175
}

A
Alex Crichton 已提交
1176 1177 1178
/// A listener is a value that can consume itself to start listening for
/// connections.
///
1179 1180
/// Doing so produces some sort of Acceptor.
pub trait Listener<T, A: Acceptor<T>> {
H
Huon Wilson 已提交
1181
    /// Spin up the listener and start queuing incoming connections
1182
    ///
A
Alex Crichton 已提交
1183
    /// # Error
1184
    ///
A
Alex Crichton 已提交
1185 1186
    /// Returns `Err` if this listener could not be bound to listen for
    /// connections. In all cases, this listener is consumed.
A
Alex Crichton 已提交
1187
    fn listen(self) -> IoResult<A>;
1188 1189 1190 1191 1192 1193
}

/// An acceptor is a value that presents incoming connections
pub trait Acceptor<T> {
    /// Wait for and accept an incoming connection
    ///
A
Alex Crichton 已提交
1194 1195 1196
    /// # Error
    ///
    /// Returns `Err` if an I/O error is encountered.
A
Alex Crichton 已提交
1197
    fn accept(&mut self) -> IoResult<T>;
1198

A
Alex Crichton 已提交
1199 1200 1201
    /// Create an iterator over incoming connection attempts.
    ///
    /// Note that I/O errors will be yielded by the iterator itself.
P
Palmer Cox 已提交
1202 1203
    fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
        IncomingConnections { inc: self }
1204 1205 1206 1207 1208
    }
}

/// An infinite iterator over incoming connection attempts.
/// Calling `next` will block the task until a connection is attempted.
1209
///
A
Alex Crichton 已提交
1210 1211 1212 1213
/// Since connection attempts can continue forever, this iterator always returns
/// `Some`. The `Some` contains the `IoResult` representing whether the
/// connection attempt was succesful.  A successful connection will be wrapped
/// in `Ok`. A failed connection is represented as an `Err`.
1214
pub struct IncomingConnections<'a, A> {
E
Erik Price 已提交
1215
    priv inc: &'a mut A,
1216 1217
}

A
Alex Crichton 已提交
1218 1219
impl<'a, T, A: Acceptor<T>> Iterator<IoResult<T>> for IncomingConnections<'a, A> {
    fn next(&mut self) -> Option<IoResult<T>> {
1220
        Some(self.inc.accept())
1221
    }
1222 1223
}

1224
pub fn standard_error(kind: IoErrorKind) -> IoError {
1225 1226 1227 1228
    let desc = match kind {
        EndOfFile => "end of file",
        IoUnavailable => "I/O is unavailable",
        InvalidInput => "invalid input",
1229
        _ => fail!()
1230 1231 1232 1233 1234
    };
    IoError {
        kind: kind,
        desc: desc,
        detail: None,
1235 1236
    }
}
1237 1238 1239 1240 1241 1242 1243

pub fn placeholder_error() -> IoError {
    IoError {
        kind: OtherIoError,
        desc: "Placeholder error. You shouldn't be seeing this",
        detail: None
    }
1244
}
1245

1246 1247 1248
/// A mode specifies how a file should be opened or created. These modes are
/// passed to `File::open_mode` and are used to control where the file is
/// positioned when it is initially opened.
1249
pub enum FileMode {
1250
    /// Opens a file positioned at the beginning.
1251
    Open,
1252
    /// Opens a file positioned at EOF.
1253
    Append,
1254
    /// Opens a file, truncating it if it already exists.
1255 1256 1257
    Truncate,
}

1258
/// Access permissions with which the file should be opened. `File`s
A
Alex Crichton 已提交
1259
/// opened with `Read` will return an error if written to.
1260 1261 1262
pub enum FileAccess {
    Read,
    Write,
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
    ReadWrite,
}

/// Different kinds of files which can be identified by a call to stat
#[deriving(Eq)]
pub enum FileType {
    TypeFile,
    TypeDirectory,
    TypeNamedPipe,
    TypeBlockSpecial,
    TypeSymlink,
    TypeUnknown,
1275
}
J
Jeff Olson 已提交
1276 1277

pub struct FileStat {
1278
    /// The path that this stat structure is describing
J
Jeff Olson 已提交
1279
    path: Path,
1280
    /// The size of the file, in bytes
J
Jeff Olson 已提交
1281
    size: u64,
1282 1283 1284 1285 1286
    /// The kind of file this path points to (directory, file, pipe, etc.)
    kind: FileType,
    /// The file permissions currently on the file
    perm: FilePermission,

1287 1288 1289
    // FIXME(#10301): These time fields are pretty useless without an actual
    //                time representation, what are the milliseconds relative
    //                to?
1290 1291 1292

    /// The time that the file was created at, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1293
    created: u64,
1294 1295
    /// The time that this file was last modified, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1296
    modified: u64,
1297 1298
    /// The time that this file was last accessed, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1299
    accessed: u64,
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
    /// Information returned by stat() which is not guaranteed to be
    /// platform-independent. This information may be useful on some platforms,
    /// but it may have different meanings or no meaning at all on other
    /// platforms.
    ///
    /// Usage of this field is discouraged, but if access is desired then the
    /// fields are located here.
    #[unstable]
    unstable: UnstableFileStat,
}

/// This structure represents all of the possible information which can be
/// returned from a `stat` syscall which is not contained in the `FileStat`
/// structure. This information is not necessarily platform independent, and may
/// have different meanings or no meaning at all on some platforms.
#[unstable]
pub struct UnstableFileStat {
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    device: u64,
    inode: u64,
    rdev: u64,
    nlink: u64,
    uid: u64,
    gid: u64,
    blksize: u64,
    blocks: u64,
    flags: u64,
    gen: u64,
J
Jeff Olson 已提交
1328
}
1329

1330 1331
/// A set of permissions for a file or directory is represented by a set of
/// flags which are or'd together.
1332
pub type FilePermission = u32;
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

// Each permission bit
pub static UserRead: FilePermission     = 0x100;
pub static UserWrite: FilePermission    = 0x080;
pub static UserExecute: FilePermission  = 0x040;
pub static GroupRead: FilePermission    = 0x020;
pub static GroupWrite: FilePermission   = 0x010;
pub static GroupExecute: FilePermission = 0x008;
pub static OtherRead: FilePermission    = 0x004;
pub static OtherWrite: FilePermission   = 0x002;
pub static OtherExecute: FilePermission = 0x001;

// Common combinations of these bits
pub static UserRWX: FilePermission  = UserRead | UserWrite | UserExecute;
pub static GroupRWX: FilePermission = GroupRead | GroupWrite | GroupExecute;
pub static OtherRWX: FilePermission = OtherRead | OtherWrite | OtherExecute;

/// A set of permissions for user owned files, this is equivalent to 0644 on
/// unix-like systems.
pub static UserFile: FilePermission = UserRead | UserWrite | GroupRead | OtherRead;
/// A set of permissions for user owned directories, this is equivalent to 0755
/// on unix-like systems.
pub static UserDir: FilePermission = UserRWX | GroupRead | GroupExecute |
                                     OtherRead | OtherExecute;
/// A set of permissions for user owned executables, this is equivalent to 0755
/// on unix-like systems.
pub static UserExec: FilePermission = UserDir;

/// A mask for all possible permission bits
pub static AllPermissions: FilePermission = 0x1ff;