mod.rs 42.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// 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 29 30 31
    ```rust
    let mut stdin = BufferedReader::new(stdin());
    for line in stdin.lines() {
        print(line);
32
    }
33
    ```
34

35
* Read a complete file
36

37 38 39
    ```rust
    let contents = File::open(&Path::new("message.txt")).read_to_end();
    ```
40 41 42

* Write a line to a file

43 44 45 46
    ```rust
    let mut file = File::create(&Path::new("message.txt"));
    file.write(bytes!("hello, file!\n"));
    ```
47 48 49

* Iterate over the lines of a file

50 51 52 53 54 55 56
    ```rust
    let path = Path::new("message.txt");
    let mut file = BufferedReader::new(File::open(&path));
    for line in file.lines() {
        print(line);
    }
    ```
57

58 59
* Pull the lines of a file into a vector of strings

60 61 62 63 64
    ```rust
    let path = Path::new("message.txt");
    let mut file = BufferedReader::new(File::open(&path));
    let lines: ~[~str] = file.lines().collect();
    ```
65 66

* Make an simple HTTP request
67 68
  XXX This needs more improvement: TcpStream constructor taking &str,
  `write_str` and `write_line` methods.
69

70 71 72 73
    ```rust
    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"));
74
    let response = socket.read_to_end();
75
    ```
76

77 78 79
* 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`.
80
  XXX this is not implemented now.
81

82 83 84
    ```rust
    // connect("tcp://localhost:8080");
    ```
85 86 87

# Terms

B
Brian Anderson 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
* 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`.
* Decorator - A Reader or Writer that composes with others to add additional capabilities
  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
116
callback is run and the code that made the I/O request continues.
B
Brian Anderson 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
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.

For blocking (but possibly more efficient) implementations, look
in the `io::native` module.
147 148 149

# Error Handling

B
Brian Anderson 已提交
150 151 152 153 154 155 156 157 158
I/O is an area where nearly every operation can result in unexpected
errors. It should allow errors to be handled efficiently.
It needs to be convenient to use I/O when you don't care
about dealing with specific errors.

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

* Errors are fatal by default, resulting in task failure
159
* Errors raise the `io_error` condition which provides an opportunity to inspect
B
Brian Anderson 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  an IoError object containing details.
* Return values must have a sensible null or zero value which is returned
  if a condition is handled successfully. This may be an `Option`, an empty
  vector, or other designated error value.
* Common traits are implemented for `Option`, e.g. `impl<R: Reader> Reader for Option<R>`,
  so that nullable values do not have to be 'unwrapped' before use.

These features combine in the API to allow for expressions like
`File::new("diary.txt").write_line("met a girl")` without having to
worry about whether "diary.txt" exists or whether the write
succeeds. As written, if either `new` or `write_line` encounters
an error the task will fail.

If you wanted to handle the error though you might write

    let mut error = None;
    do io_error::cond(|e: IoError| {
        error = Some(e);
    }).in {
        File::new("diary.txt").write_line("met a girl");
    }

    if error.is_some() {
        println("failed to write my diary");
    }

XXX: Need better condition handling syntax

In this case the condition handler will have the opportunity to
inspect the IoError raised by either the call to `new` or the call to
`write_line`, but then execution will continue.

So what actually happens if `new` encounters an error? To understand
that it's important to know that what `new` returns is not a `File`
but an `Option<File>`.  If the file does not open, and the condition
is handled, then `new` will simply return `None`. 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 `Option<File>` and we simply call `write_line` on it.  If `new`
returned a `None` then the followup call to `write_line` will also
raise an error.

## Concerns about this strategy

This structure will encourage a programming style that is prone
to errors similar to null pointer dereferences.
In particular code written to ignore errors and expect conditions to be unhandled
will start passing around null or zero objects when wrapped in a condition handler.

* XXX: How should we use condition handlers that return values?
210
* XXX: Should EOF raise default conditions when EOF is not an error?
B
Brian Anderson 已提交
211

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

214 215 216 217
# Resource management

* `close` vs. RAII

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


221

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

In scope for core

* Url?
227 228 229 230 231 232 233 234

Some I/O things don't belong in core

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

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

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


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

* 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 已提交
250
* Can Port and Chan be implementations of a generic Reader<T>/Writer<T>?
251 252 253 254 255 256 257
* 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 已提交
258
* Using conditions is a big unknown since we don't have much experience with them
259
* Too many uses of OtherIoError
260 261 262

*/

A
Alex Crichton 已提交
263 264
#[allow(missing_doc)];

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

// 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;

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

297 298
/// Synchronous, non-blocking filesystem operations.
pub mod fs;
299

300 301 302 303 304 305
/// Synchronous, in-memory I/O.
pub mod pipe;

/// Child process management.
pub mod process;

306
/// Synchronous, non-blocking network I/O.
307
pub mod net;
308 309 310 311 312 313 314

/// Readers and Writers for memory buffers and strings.
pub mod mem;

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

315 316 317
/// Implementations for Option
mod option;

318 319 320 321 322 323 324
/// Basic stream compression. XXX: Belongs with other flate code
pub mod flate;

/// Interop between byte streams and pipes. Not sure where it belongs
pub mod comm_adapters;

/// Extension traits
325
pub mod extensions;
326

J
Jeff Olson 已提交
327
/// Basic Timer
328
pub mod timer;
J
Jeff Olson 已提交
329

S
Steven Fackler 已提交
330 331 332
/// Buffered I/O wrappers
pub mod buffered;

A
Alex Crichton 已提交
333
pub mod native;
334

335 336 337
/// Signal handling
pub mod signal;

S
Steven Fackler 已提交
338 339 340
/// Utility implementations of Reader and Writer
pub mod util;

341
/// The default buffer size for various I/O operations
342
static DEFAULT_BUF_SIZE: uint = 1024 * 64;
343

344 345
/// The type passed to I/O condition handlers to indicate error
///
B
Tidy  
Brian Anderson 已提交
346
/// # XXX
347 348 349 350 351 352 353 354
///
/// Is something like this sufficient? It's kind of archaic
pub struct IoError {
    kind: IoErrorKind,
    desc: &'static str,
    detail: Option<~str>
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368
// 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
    }
}

369
#[deriving(Eq)]
370
pub enum IoErrorKind {
371 372 373
    PreviousIoError,
    OtherIoError,
    EndOfFile,
374
    FileNotFound,
375
    PermissionDenied,
376 377
    ConnectionFailed,
    Closed,
378
    ConnectionRefused,
B
Brian Anderson 已提交
379
    ConnectionReset,
380
    ConnectionAborted,
K
klutzy 已提交
381
    NotConnected,
382 383 384
    BrokenPipe,
    PathAlreadyExists,
    PathDoesntExist,
385
    MismatchedFileTypeForOperation,
386
    ResourceUnavailable,
387
    IoUnavailable,
388
}
389

390 391 392 393 394 395 396 397 398 399 400 401 402
// FIXME: #8242 implementing manually because deriving doesn't work for some reason
impl ToStr for IoErrorKind {
    fn to_str(&self) -> ~str {
        match *self {
            PreviousIoError => ~"PreviousIoError",
            OtherIoError => ~"OtherIoError",
            EndOfFile => ~"EndOfFile",
            FileNotFound => ~"FileNotFound",
            PermissionDenied => ~"PermissionDenied",
            ConnectionFailed => ~"ConnectionFailed",
            Closed => ~"Closed",
            ConnectionRefused => ~"ConnectionRefused",
            ConnectionReset => ~"ConnectionReset",
K
klutzy 已提交
403
            NotConnected => ~"NotConnected",
404 405 406
            BrokenPipe => ~"BrokenPipe",
            PathAlreadyExists => ~"PathAlreadyExists",
            PathDoesntExist => ~"PathDoesntExist",
407 408
            MismatchedFileTypeForOperation => ~"MismatchedFileTypeForOperation",
            IoUnavailable => ~"IoUnavailable",
409
            ResourceUnavailable => ~"ResourceUnavailable",
410
            ConnectionAborted => ~"ConnectionAborted",
411 412 413 414
        }
    }
}

415
// XXX: Can't put doc comments on macros
416
// Raised by `I/O` operations on error.
417
condition! {
A
Alex Crichton 已提交
418
    pub io_error: IoError -> ();
419 420
}

421 422
/// Helper for wrapper calls where you want to
/// ignore any io_errors that might be raised
423
pub fn ignore_io_error() -> Guard<'static,IoError,()> {
424
    io_error::cond.trap(|_| {
425 426 427
        // just swallow the error.. downstream users
        // who can make a decision based on a None result
        // won't care
428
    }).guard()
429 430
}

431 432 433
/// Helper for catching an I/O error and wrapping it in a Result object. The
/// return result will be the last I/O error that happened or the result of the
/// closure if no error occurred.
434
pub fn result<T>(cb: || -> T) -> Result<T, IoError> {
435
    let mut err = None;
436 437 438 439 440
    let ret = io_error::cond.trap(|e| {
        if err.is_none() {
            err = Some(e);
        }
    }).inside(cb);
441 442 443 444 445 446
    match err {
        Some(e) => Err(e),
        None => Ok(ret),
    }
}

447
pub trait Reader {
448 449 450

    // Only two methods which need to get implemented for this trait

451
    /// Read bytes, up to the length of `buf` and place them in `buf`.
452 453
    /// Returns the number of bytes read. The number of bytes read my
    /// be less than the number requested, even 0. Returns `None` on EOF.
454 455 456
    ///
    /// # Failure
    ///
A
Alex Crichton 已提交
457
    /// Raises the `io_error` condition on error. If the condition
458 459 460
    /// is handled then no guarantee is made about the number of bytes
    /// read and the contents of `buf`. If the condition is handled
    /// returns `None` (XXX see below).
461
    ///
B
Tidy  
Brian Anderson 已提交
462
    /// # XXX
463
    ///
464
    /// * Should raise_default error on eof?
465
    /// * If the condition is handled it should still return the bytes read,
466 467
    ///   in which case there's no need to return Option - but then you *have*
    ///   to install a handler to detect eof.
468
    ///
469 470 471
    /// This doesn't take a `len` argument like the old `read`.
    /// Will people often need to slice their vectors to call this
    /// and will that be annoying?
472
    /// Is it actually possible for 0 bytes to be read successfully?
473
    fn read(&mut self, buf: &mut [u8]) -> Option<uint>;
474

475 476 477 478
    /// Return whether the Reader has reached the end of the stream.
    ///
    /// # Example
    ///
479
    ///     let reader = File::open(&Path::new("foo.txt"))
480 481 482 483
    ///     while !reader.eof() {
    ///         println(reader.read_line());
    ///     }
    ///
H
Huon Wilson 已提交
484
    /// # Failure
485
    ///
486
    /// Returns `true` on failure.
487
    fn eof(&mut self) -> bool;
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

    // Convenient helper methods based on the above methods

    /// Reads a single byte. Returns `None` on EOF.
    ///
    /// # Failure
    ///
    /// Raises the same conditions as the `read` method. Returns
    /// `None` if the condition is handled.
    fn read_byte(&mut self) -> Option<u8> {
        let mut buf = [0];
        match self.read(buf) {
            Some(0) => {
                debug!("read 0 bytes. trying again");
                self.read_byte()
            }
            Some(1) => Some(buf[0]),
            Some(_) => unreachable!(),
            None => None
        }
    }

    /// Reads `len` bytes and appends them to a vector.
    ///
    /// May push fewer than the requested number of bytes on error
    /// or EOF. Returns true on success, false on EOF or error.
    ///
    /// # Failure
    ///
    /// Raises the same conditions as `read`. Additionally raises `io_error`
    /// on EOF. If `io_error` is handled then `push_bytes` may push less
    /// than the requested number of bytes.
    fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) {
        unsafe {
            let start_len = buf.len();
            let mut total_read = 0;

            buf.reserve_additional(len);
            vec::raw::set_len(buf, start_len + len);

528
            (|| {
529 530 531 532 533 534 535 536 537 538 539 540 541
                while total_read < len {
                    let len = buf.len();
                    let slice = buf.mut_slice(start_len + total_read, len);
                    match self.read(slice) {
                        Some(nread) => {
                            total_read += nread;
                        }
                        None => {
                            io_error::cond.raise(standard_error(EndOfFile));
                            break;
                        }
                    }
                }
542
            }).finally(|| vec::raw::set_len(buf, start_len + total_read))
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        }
    }

    /// Reads `len` bytes and gives you back a new vector of length `len`
    ///
    /// # Failure
    ///
    /// Raises the same conditions as `read`. Additionally raises `io_error`
    /// on EOF. If `io_error` is handled then the returned vector may
    /// contain less than the requested number of bytes.
    fn read_bytes(&mut self, len: uint) -> ~[u8] {
        let mut buf = vec::with_capacity(len);
        self.push_bytes(&mut buf, len);
        return buf;
    }

    /// Reads all remaining bytes from the stream.
    ///
    /// # Failure
    ///
563 564
    /// Raises the same conditions as the `read` method except for
    /// `EndOfFile` which is swallowed.
565 566 567
    fn read_to_end(&mut self) -> ~[u8] {
        let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE);
        let mut keep_reading = true;
568
        io_error::cond.trap(|e| {
569 570 571 572 573
            if e.kind == EndOfFile {
                keep_reading = false;
            } else {
                io_error::cond.raise(e)
            }
574
        }).inside(|| {
575 576 577
            while keep_reading {
                self.push_bytes(&mut buf, DEFAULT_BUF_SIZE)
            }
578
        });
579 580 581 582 583 584 585 586 587 588 589
        return buf;
    }

    /// Create an iterator that reads a single byte on
    /// each iteration, until EOF.
    ///
    /// # Failure
    ///
    /// Raises the same conditions as the `read` method, for
    /// each call to its `.next()` method.
    /// Ends the iteration if the condition is handled.
590
    fn bytes<'r>(&'r mut self) -> extensions::ByteIterator<'r, Self> {
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        extensions::ByteIterator::new(self)
    }

    // Byte conversion helpers

    /// Reads `n` little-endian unsigned integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
    fn read_le_uint_n(&mut self, nbytes: uint) -> u64 {
        assert!(nbytes > 0 && nbytes <= 8);

        let mut val = 0u64;
        let mut pos = 0;
        let mut i = nbytes;
        while i > 0 {
            val += (self.read_u8() as u64) << pos;
            pos += 8;
            i -= 1;
        }
        val
    }

    /// Reads `n` little-endian signed integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
    fn read_le_int_n(&mut self, nbytes: uint) -> i64 {
        extend_sign(self.read_le_uint_n(nbytes), nbytes)
    }

    /// Reads `n` big-endian unsigned integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
    fn read_be_uint_n(&mut self, nbytes: uint) -> u64 {
        assert!(nbytes > 0 && nbytes <= 8);

        let mut val = 0u64;
        let mut i = nbytes;
        while i > 0 {
            i -= 1;
            val += (self.read_u8() as u64) << i * 8;
        }
        val
    }

    /// Reads `n` big-endian signed integer bytes.
    ///
    /// `n` must be between 1 and 8, inclusive.
    fn read_be_int_n(&mut self, nbytes: uint) -> i64 {
        extend_sign(self.read_be_uint_n(nbytes), nbytes)
    }

    /// Reads a little-endian unsigned integer.
    ///
    /// The number of bytes returned is system-dependant.
    fn read_le_uint(&mut self) -> uint {
        self.read_le_uint_n(uint::bytes) as uint
    }

    /// Reads a little-endian integer.
    ///
    /// The number of bytes returned is system-dependant.
    fn read_le_int(&mut self) -> int {
        self.read_le_int_n(int::bytes) as int
    }

    /// Reads a big-endian unsigned integer.
    ///
    /// The number of bytes returned is system-dependant.
    fn read_be_uint(&mut self) -> uint {
        self.read_be_uint_n(uint::bytes) as uint
    }

    /// Reads a big-endian integer.
    ///
    /// The number of bytes returned is system-dependant.
    fn read_be_int(&mut self) -> int {
        self.read_be_int_n(int::bytes) as int
    }

    /// Reads a big-endian `u64`.
    ///
    /// `u64`s are 8 bytes long.
    fn read_be_u64(&mut self) -> u64 {
        self.read_be_uint_n(8) as u64
    }

    /// Reads a big-endian `u32`.
    ///
    /// `u32`s are 4 bytes long.
    fn read_be_u32(&mut self) -> u32 {
        self.read_be_uint_n(4) as u32
    }

    /// Reads a big-endian `u16`.
    ///
    /// `u16`s are 2 bytes long.
    fn read_be_u16(&mut self) -> u16 {
        self.read_be_uint_n(2) as u16
    }

    /// Reads a big-endian `i64`.
    ///
    /// `i64`s are 8 bytes long.
    fn read_be_i64(&mut self) -> i64 {
        self.read_be_int_n(8) as i64
    }

    /// Reads a big-endian `i32`.
    ///
    /// `i32`s are 4 bytes long.
    fn read_be_i32(&mut self) -> i32 {
        self.read_be_int_n(4) as i32
    }

    /// Reads a big-endian `i16`.
    ///
    /// `i16`s are 2 bytes long.
    fn read_be_i16(&mut self) -> i16 {
        self.read_be_int_n(2) as i16
    }

    /// Reads a big-endian `f64`.
    ///
    /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
    fn read_be_f64(&mut self) -> f64 {
        unsafe {
            cast::transmute::<u64, f64>(self.read_be_u64())
        }
    }

    /// Reads a big-endian `f32`.
    ///
    /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
    fn read_be_f32(&mut self) -> f32 {
        unsafe {
            cast::transmute::<u32, f32>(self.read_be_u32())
        }
    }

    /// Reads a little-endian `u64`.
    ///
    /// `u64`s are 8 bytes long.
    fn read_le_u64(&mut self) -> u64 {
        self.read_le_uint_n(8) as u64
    }

    /// Reads a little-endian `u32`.
    ///
    /// `u32`s are 4 bytes long.
    fn read_le_u32(&mut self) -> u32 {
        self.read_le_uint_n(4) as u32
    }

    /// Reads a little-endian `u16`.
    ///
    /// `u16`s are 2 bytes long.
    fn read_le_u16(&mut self) -> u16 {
        self.read_le_uint_n(2) as u16
    }

    /// Reads a little-endian `i64`.
    ///
    /// `i64`s are 8 bytes long.
    fn read_le_i64(&mut self) -> i64 {
        self.read_le_int_n(8) as i64
    }

    /// Reads a little-endian `i32`.
    ///
    /// `i32`s are 4 bytes long.
    fn read_le_i32(&mut self) -> i32 {
        self.read_le_int_n(4) as i32
    }

    /// Reads a little-endian `i16`.
    ///
    /// `i16`s are 2 bytes long.
    fn read_le_i16(&mut self) -> i16 {
        self.read_le_int_n(2) as i16
    }

    /// Reads a little-endian `f64`.
    ///
    /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
    fn read_le_f64(&mut self) -> f64 {
        unsafe {
            cast::transmute::<u64, f64>(self.read_le_u64())
        }
    }

    /// Reads a little-endian `f32`.
    ///
    /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
    fn read_le_f32(&mut self) -> f32 {
        unsafe {
            cast::transmute::<u32, f32>(self.read_le_u32())
        }
    }

    /// Read a u8.
    ///
    /// `u8`s are 1 byte.
    fn read_u8(&mut self) -> u8 {
        match self.read_byte() {
            Some(b) => b as u8,
            None => 0
        }
    }

    /// Read an i8.
    ///
    /// `i8`s are 1 byte.
    fn read_i8(&mut self) -> i8 {
        match self.read_byte() {
            Some(b) => b as i8,
            None => 0
        }
    }

810
}
811

812 813 814 815 816
impl Reader for ~Reader {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> { self.read(buf) }
    fn eof(&mut self) -> bool { self.eof() }
}

E
Erik Price 已提交
817
impl<'a> Reader for &'a mut Reader {
818 819 820 821
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> { self.read(buf) }
    fn eof(&mut self) -> bool { self.eof() }
}

822 823 824 825 826
fn extend_sign(val: u64, nbytes: uint) -> i64 {
    let shift = (8 - nbytes) * 8;
    (val << shift) as i64 >> shift
}

827
pub trait Writer {
828 829 830 831
    /// Write the given buffer
    ///
    /// # Failure
    ///
832 833 834
    /// Raises the `io_error` condition on error
    fn write(&mut self, buf: &[u8]);

835 836 837 838 839 840
    /// Flush this output stream, ensuring that all intermediately buffered
    /// contents reach their destination.
    ///
    /// This is by default a no-op and implementors of the `Writer` trait should
    /// decide whether their stream needs to be buffered or not.
    fn flush(&mut self) {}
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

    /// Write the result of passing n through `int::to_str_bytes`.
    fn write_int(&mut self, n: int) {
        int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
    }

    /// Write the result of passing n through `uint::to_str_bytes`.
    fn write_uint(&mut self, n: uint) {
        uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
    }

    /// Write a little-endian uint (number of bytes depends on system).
    fn write_le_uint(&mut self, n: uint) {
        extensions::u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v))
    }

    /// Write a little-endian int (number of bytes depends on system).
    fn write_le_int(&mut self, n: int) {
        extensions::u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v))
    }

    /// Write a big-endian uint (number of bytes depends on system).
    fn write_be_uint(&mut self, n: uint) {
        extensions::u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v))
    }

    /// Write a big-endian int (number of bytes depends on system).
    fn write_be_int(&mut self, n: int) {
        extensions::u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v))
    }

    /// Write a big-endian u64 (8 bytes).
    fn write_be_u64(&mut self, n: u64) {
        extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
    }

    /// Write a big-endian u32 (4 bytes).
    fn write_be_u32(&mut self, n: u32) {
        extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a big-endian u16 (2 bytes).
    fn write_be_u16(&mut self, n: u16) {
        extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a big-endian i64 (8 bytes).
    fn write_be_i64(&mut self, n: i64) {
        extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
    }

    /// Write a big-endian i32 (4 bytes).
    fn write_be_i32(&mut self, n: i32) {
        extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a big-endian i16 (2 bytes).
    fn write_be_i16(&mut self, n: i16) {
        extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
    fn write_be_f64(&mut self, f: f64) {
        unsafe {
            self.write_be_u64(cast::transmute(f))
        }
    }

    /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
    fn write_be_f32(&mut self, f: f32) {
        unsafe {
            self.write_be_u32(cast::transmute(f))
        }
    }

    /// Write a little-endian u64 (8 bytes).
    fn write_le_u64(&mut self, n: u64) {
        extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
    }

    /// Write a little-endian u32 (4 bytes).
    fn write_le_u32(&mut self, n: u32) {
        extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a little-endian u16 (2 bytes).
    fn write_le_u16(&mut self, n: u16) {
        extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a little-endian i64 (8 bytes).
    fn write_le_i64(&mut self, n: i64) {
        extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
    }

    /// Write a little-endian i32 (4 bytes).
    fn write_le_i32(&mut self, n: i32) {
        extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
    }

    /// Write a little-endian i16 (2 bytes).
    fn write_le_i16(&mut self, n: i16) {
        extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
    }

    /// Write a little-endian IEEE754 double-precision floating-point
    /// (8 bytes).
    fn write_le_f64(&mut self, f: f64) {
        unsafe {
            self.write_le_u64(cast::transmute(f))
        }
    }

    /// Write a little-endian IEEE754 single-precision floating-point
    /// (4 bytes).
    fn write_le_f32(&mut self, f: f32) {
        unsafe {
            self.write_le_u32(cast::transmute(f))
        }
    }

    /// Write a u8 (1 byte).
    fn write_u8(&mut self, n: u8) {
        self.write([n])
    }

    /// Write a i8 (1 byte).
    fn write_i8(&mut self, n: i8) {
        self.write([n as u8])
    }
971 972
}

973 974 975 976 977
impl Writer for ~Writer {
    fn write(&mut self, buf: &[u8]) { self.write(buf) }
    fn flush(&mut self) { self.flush() }
}

E
Erik Price 已提交
978
impl<'a> Writer for &'a mut Writer {
979 980 981 982
    fn write(&mut self, buf: &[u8]) { self.write(buf) }
    fn flush(&mut self) { self.flush() }
}

B
Brian Anderson 已提交
983
pub trait Stream: Reader + Writer { }
984

985
impl<T: Reader + Writer> Stream for T {}
986

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
/// An iterator that reads a line on each iteration,
/// until `.read_line()` returns `None`.
///
/// # Notes about the Iteration Protocol
///
/// The `LineIterator` may yield `None` and thus terminate
/// an iteration, but continue to yield elements if iteration
/// is attempted again.
///
/// # Failure
///
/// Raises the same conditions as the `read` method except for `EndOfFile`
/// which is swallowed.
/// Iteration yields `None` if the condition is handled.
struct LineIterator<'r, T> {
    priv buffer: &'r mut T,
}

impl<'r, T: Buffer> Iterator<~str> for LineIterator<'r, T> {
    fn next(&mut self) -> Option<~str> {
        self.buffer.read_line()
    }
}

A
Alex Crichton 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
/// 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.
    ///
    /// # Failure
    ///
    /// This function will raise on the `io_error` condition if a read error is
    /// encountered.
    fn fill<'a>(&'a mut self) -> &'a [u8];

    /// 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);

    /// Reads the next line of input, interpreted as a sequence of utf-8
    /// encoded unicode codepoints. If a newline is encountered, then the
    /// newline is contained in the returned string.
    ///
    /// # Failure
    ///
1040 1041 1042
    /// This function will raise on the `io_error` condition (except for
    /// `EndOfFile` which is swallowed) if a read error is encountered.
    /// The task will also fail if sequence of bytes leading up to
A
Alex Crichton 已提交
1043 1044 1045 1046 1047
    /// the newline character are not valid utf-8.
    fn read_line(&mut self) -> Option<~str> {
        self.read_until('\n' as u8).map(str::from_utf8_owned)
    }

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    /// Create an iterator that reads a line on each iteration until EOF.
    ///
    /// # Failure
    ///
    /// Iterator raises the same conditions as the `read` method
    /// except for `EndOfFile`.
    fn lines<'r>(&'r mut self) -> LineIterator<'r, Self> {
        LineIterator {
            buffer: self,
        }
    }

A
Alex Crichton 已提交
1060 1061 1062 1063 1064 1065 1066
    /// Reads a sequence of bytes leading up to a specified delimeter. Once the
    /// specified byte is encountered, reading ceases and the bytes up to and
    /// including the delimiter are returned.
    ///
    /// # Failure
    ///
    /// This function will raise on the `io_error` condition if a read error is
1067
    /// encountered, except that `EndOfFile` is swallowed.
A
Alex Crichton 已提交
1068 1069
    fn read_until(&mut self, byte: u8) -> Option<~[u8]> {
        let mut res = ~[];
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

        io_error::cond.trap(|e| {
            if e.kind != EndOfFile {
                io_error::cond.raise(e);
            }
        }).inside(|| {
            let mut used;
            loop {
                {
                    let available = self.fill();
                    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 已提交
1090 1091
                    }
                }
1092 1093 1094 1095
                if used == 0 {
                    break
                }
                self.consume(used);
A
Alex Crichton 已提交
1096 1097
            }
            self.consume(used);
1098
        });
A
Alex Crichton 已提交
1099
        return if res.len() == 0 {None} else {Some(res)};
1100

A
Alex Crichton 已提交
1101
    }
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

    /// Reads the next utf8-encoded character from the underlying stream.
    ///
    /// This will return `None` if the following sequence of bytes in the
    /// stream are not a valid utf8-sequence, or if an I/O error is encountered.
    ///
    /// # Failure
    ///
    /// This function will raise on the `io_error` condition if a read error is
    /// encountered.
    fn read_char(&mut self) -> Option<char> {
        let width = {
            let available = self.fill();
            if available.len() == 0 { return None } // read error
            str::utf8_char_width(available[0])
        };
        if width == 0 { return None } // not uf8
        let mut buf = [0, ..4];
        match self.read(buf.mut_slice_to(width)) {
            Some(n) if n == width => {}
A
Alex Crichton 已提交
1122
            Some(..) | None => return None // read error
1123
        }
1124
        match str::from_utf8_opt(buf.slice_to(width)) {
1125 1126 1127 1128
            Some(s) => Some(s.char_at(0)),
            None => None
        }
    }
A
Alex Crichton 已提交
1129 1130
}

1131 1132 1133 1134 1135 1136 1137 1138 1139
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,
}

B
Tidy  
Brian Anderson 已提交
1140
/// # XXX
1141
/// * Are `u64` and `i64` the right choices?
1142
pub trait Seek {
1143
    /// Return position of file cursor in the stream
1144
    fn tell(&self) -> u64;
1145 1146 1147 1148 1149 1150 1151 1152

    /// Seek to an offset in a stream
    ///
    /// A successful seek clears the EOF indicator.
    ///
    /// # XXX
    ///
    /// * What is the behavior when seeking past the end of a stream?
1153 1154 1155
    fn seek(&mut self, pos: i64, style: SeekStyle);
}

1156 1157 1158 1159
/// A listener is a value that can consume itself to start listening for connections.
/// Doing so produces some sort of Acceptor.
pub trait Listener<T, A: Acceptor<T>> {
    /// Spin up the listener and start queueing incoming connections
1160 1161 1162 1163
    ///
    /// # Failure
    ///
    /// Raises `io_error` condition. If the condition is handled,
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    /// then `listen` returns `None`.
    fn listen(self) -> Option<A>;
}

/// An acceptor is a value that presents incoming connections
pub trait Acceptor<T> {
    /// Wait for and accept an incoming connection
    ///
    /// # Failure
    /// Raise `io_error` condition. If the condition is handled,
1174
    /// then `accept` returns `None`.
1175 1176
    fn accept(&mut self) -> Option<T>;

1177
    /// Create an iterator over incoming connection attempts
1178 1179 1180 1181 1182 1183 1184
    fn incoming<'r>(&'r mut self) -> IncomingIterator<'r, Self> {
        IncomingIterator { inc: self }
    }
}

/// An infinite iterator over incoming connection attempts.
/// Calling `next` will block the task until a connection is attempted.
1185 1186 1187 1188 1189
///
/// Since connection attempts can continue forever, this iterator always returns Some.
/// The Some contains another Option representing whether the connection attempt was succesful.
/// A successful connection will be wrapped in Some.
/// A failed connection is represented as a None and raises a condition.
E
Erik Price 已提交
1190 1191
struct IncomingIterator<'a, A> {
    priv inc: &'a mut A,
1192 1193
}

E
Erik Price 已提交
1194
impl<'a, T, A: Acceptor<T>> Iterator<Option<T>> for IncomingIterator<'a, A> {
1195 1196
    fn next(&mut self) -> Option<Option<T>> {
        Some(self.inc.accept())
1197
    }
1198 1199
}

1200 1201 1202 1203 1204 1205
/// Common trait for decorator types.
///
/// Provides accessors to get the inner, 'decorated' values. The I/O library
/// uses decorators to add functionality like compression and encryption to I/O
/// streams.
///
B
Tidy  
Brian Anderson 已提交
1206
/// # XXX
1207 1208 1209 1210 1211
///
/// Is this worth having a trait for? May be overkill
pub trait Decorator<T> {
    /// Destroy the decorator and extract the decorated value
    ///
B
Tidy  
Brian Anderson 已提交
1212
    /// # XXX
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    ///
    /// Because this takes `self' one could never 'undecorate' a Reader/Writer
    /// that has been boxed. Is that ok? This feature is mostly useful for
    /// extracting the buffer from MemWriter
    fn inner(self) -> T;

    /// Take an immutable reference to the decorated value
    fn inner_ref<'a>(&'a self) -> &'a T;

    /// Take a mutable reference to the decorated value
    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut T;
1224
}
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

pub fn standard_error(kind: IoErrorKind) -> IoError {
    match kind {
        PreviousIoError => {
            IoError {
                kind: PreviousIoError,
                desc: "Failing due to a previous I/O error",
                detail: None
            }
        }
1235 1236 1237 1238 1239 1240 1241
        EndOfFile => {
            IoError {
                kind: EndOfFile,
                desc: "End of file",
                detail: None
            }
        }
1242 1243 1244 1245 1246 1247 1248
        IoUnavailable => {
            IoError {
                kind: IoUnavailable,
                desc: "I/O is unavailable",
                detail: None
            }
        }
1249
        _ => fail!()
1250 1251
    }
}
1252 1253 1254 1255 1256 1257 1258

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

1261 1262 1263
/// 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.
1264
pub enum FileMode {
1265
    /// Opens a file positioned at the beginning.
1266
    Open,
1267
    /// Opens a file positioned at EOF.
1268
    Append,
1269
    /// Opens a file, truncating it if it already exists.
1270 1271 1272
    Truncate,
}

1273 1274
/// Access permissions with which the file should be opened. `File`s
/// opened with `Read` will raise an `io_error` condition if written to.
1275 1276 1277
pub enum FileAccess {
    Read,
    Write,
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    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,
1290
}
J
Jeff Olson 已提交
1291 1292

pub struct FileStat {
1293
    /// The path that this stat structure is describing
J
Jeff Olson 已提交
1294
    path: Path,
1295
    /// The size of the file, in bytes
J
Jeff Olson 已提交
1296
    size: u64,
1297 1298 1299 1300 1301
    /// The kind of file this path points to (directory, file, pipe, etc.)
    kind: FileType,
    /// The file permissions currently on the file
    perm: FilePermission,

1302 1303 1304
    // FIXME(#10301): These time fields are pretty useless without an actual
    //                time representation, what are the milliseconds relative
    //                to?
1305 1306 1307

    /// The time that the file was created at, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1308
    created: u64,
1309 1310
    /// The time that this file was last modified, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1311
    modified: u64,
1312 1313
    /// The time that this file was last accessed, in platform-dependent
    /// milliseconds
J
Jeff Olson 已提交
1314
    accessed: u64,
1315

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    /// 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 {
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    device: u64,
    inode: u64,
    rdev: u64,
    nlink: u64,
    uid: u64,
    gid: u64,
    blksize: u64,
    blocks: u64,
    flags: u64,
    gen: u64,
J
Jeff Olson 已提交
1343
}
1344

1345 1346
/// A set of permissions for a file or directory is represented by a set of
/// flags which are or'd together.
1347
pub type FilePermission = u32;
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

// 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;