2014-01-25 01:37:51 -06:00
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
2013-03-13 22:02:48 -05:00
|
|
|
// 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.
|
2014-07-21 17:57:14 -05:00
|
|
|
//
|
|
|
|
// ignore-lexer-test FIXME #15883
|
2013-03-13 22:02:48 -05:00
|
|
|
|
2014-02-22 17:53:54 -06:00
|
|
|
// FIXME: cover these topics:
|
|
|
|
// path, reader, writer, stream, raii (close not needed),
|
|
|
|
// stdio, print!, println!, file access, process spawning,
|
|
|
|
// error handling
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2014-02-22 17:53:54 -06:00
|
|
|
|
|
|
|
/*! I/O, including files, networking, timers, and processes
|
|
|
|
|
|
|
|
`std::io` provides Rust's basic I/O types,
|
|
|
|
for reading and writing to files, TCP, UDP,
|
|
|
|
and other types of sockets and pipes,
|
|
|
|
manipulating the file system, spawning processes and signal handling.
|
2013-04-17 19:55:21 -05:00
|
|
|
|
|
|
|
# Examples
|
|
|
|
|
|
|
|
Some examples of obvious things you might want to do
|
|
|
|
|
|
|
|
* Read lines from stdin
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
```rust
|
2014-02-20 11:11:56 -06:00
|
|
|
use std::io;
|
2013-12-22 15:31:23 -06:00
|
|
|
|
2014-02-20 11:11:56 -06:00
|
|
|
for line in io::stdin().lines() {
|
2014-02-19 20:53:46 -06:00
|
|
|
print!("{}", line.unwrap());
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
2013-12-08 01:12:07 -06:00
|
|
|
```
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
* Read a complete file
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
```rust
|
2013-12-22 15:31:23 -06:00
|
|
|
use std::io::File;
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
let contents = File::open(&Path::new("message.txt")).read_to_end();
|
|
|
|
```
|
2013-04-17 19:55:21 -05:00
|
|
|
|
|
|
|
* Write a line to a file
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
```rust
|
2014-04-14 10:30:31 -05:00
|
|
|
# #![allow(unused_must_use)]
|
2013-12-22 15:31:23 -06:00
|
|
|
use std::io::File;
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
let mut file = File::create(&Path::new("message.txt"));
|
2014-06-18 13:25:36 -05:00
|
|
|
file.write(b"hello, file!\n");
|
2013-12-31 14:43:52 -06:00
|
|
|
# drop(file);
|
|
|
|
# ::std::io::fs::unlink(&Path::new("message.txt"));
|
2013-12-08 01:12:07 -06:00
|
|
|
```
|
2013-04-17 19:55:21 -05:00
|
|
|
|
|
|
|
* Iterate over the lines of a file
|
|
|
|
|
2014-02-19 20:53:46 -06:00
|
|
|
```rust,no_run
|
2014-01-15 15:25:09 -06:00
|
|
|
use std::io::BufferedReader;
|
2013-12-22 15:31:23 -06:00
|
|
|
use std::io::File;
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
let path = Path::new("message.txt");
|
|
|
|
let mut file = BufferedReader::new(File::open(&path));
|
|
|
|
for line in file.lines() {
|
2014-02-19 20:53:46 -06:00
|
|
|
print!("{}", line.unwrap());
|
2013-12-08 01:12:07 -06:00
|
|
|
}
|
|
|
|
```
|
2013-04-19 20:47:31 -05:00
|
|
|
|
2013-04-17 19:55:21 -05:00
|
|
|
* Pull the lines of a file into a vector of strings
|
|
|
|
|
2014-02-19 20:53:46 -06:00
|
|
|
```rust,no_run
|
2014-01-15 15:25:09 -06:00
|
|
|
use std::io::BufferedReader;
|
2013-12-22 15:31:23 -06:00
|
|
|
use std::io::File;
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
let path = Path::new("message.txt");
|
|
|
|
let mut file = BufferedReader::new(File::open(&path));
|
2014-05-22 18:57:53 -05:00
|
|
|
let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
|
2013-12-08 01:12:07 -06:00
|
|
|
```
|
2013-04-19 20:47:31 -05:00
|
|
|
|
2014-02-22 17:53:54 -06:00
|
|
|
* Make a simple TCP client connection and request
|
2013-04-19 20:47:31 -05:00
|
|
|
|
2014-06-09 09:33:04 -05:00
|
|
|
```rust
|
2014-04-14 10:30:31 -05:00
|
|
|
# #![allow(unused_must_use)]
|
2014-06-26 15:22:26 -05:00
|
|
|
use std::io::TcpStream;
|
2013-12-22 15:31:23 -06:00
|
|
|
|
2014-06-09 09:33:04 -05:00
|
|
|
# // connection doesn't fail if a server is running on 8080
|
|
|
|
# // locally, we still want to be type checking this code, so lets
|
|
|
|
# // just stop it running (#11576)
|
|
|
|
# if false {
|
Easier interface for TCP ::connect and ::bind.
Prior to this commit, TcpStream::connect and TcpListener::bind took a
single SocketAddr argument. This worked well enough, but the API felt a
little too "low level" for most simple use cases.
A great example is connecting to rust-lang.org on port 80. Rust users would
need to:
1. resolve the IP address of rust-lang.org using
io::net::addrinfo::get_host_addresses.
2. check for errors
3. if all went well, use the returned IP address and the port number
to construct a SocketAddr
4. pass this SocketAddr to TcpStream::connect.
I'm modifying the type signature of TcpStream::connect and
TcpListener::bind so that the API is a little easier to use.
TcpStream::connect now accepts two arguments: a string describing the
host/IP of the host we wish to connect to, and a u16 representing the
remote port number.
Similarly, TcpListener::bind has been modified to take two arguments:
a string describing the local interface address (e.g. "0.0.0.0" or
"127.0.0.1") and a u16 port number.
Here's how to port your Rust code to use the new TcpStream::connect API:
// old ::connect API
let addr = SocketAddr{ip: Ipv4Addr{127, 0, 0, 1}, port: 8080};
let stream = TcpStream::connect(addr).unwrap()
// new ::connect API (minimal change)
let addr = SocketAddr{ip: Ipv4Addr{127, 0, 0, 1}, port: 8080};
let stream = TcpStream::connect(addr.ip.to_str(), addr.port()).unwrap()
// new ::connect API (more compact)
let stream = TcpStream::connect("127.0.0.1", 8080).unwrap()
// new ::connect API (hostname)
let stream = TcpStream::connect("rust-lang.org", 80)
Similarly, for TcpListener::bind:
// old ::bind API
let addr = SocketAddr{ip: Ipv4Addr{0, 0, 0, 0}, port: 8080};
let mut acceptor = TcpListener::bind(addr).listen();
// new ::bind API (minimal change)
let addr = SocketAddr{ip: Ipv4Addr{0, 0, 0, 0}, port: 8080};
let mut acceptor = TcpListener::bind(addr.ip.to_str(), addr.port()).listen()
// new ::bind API (more compact)
let mut acceptor = TcpListener::bind("0.0.0.0", 8080).listen()
[breaking-change]
2014-05-03 03:12:31 -05:00
|
|
|
let mut socket = TcpStream::connect("127.0.0.1", 8080).unwrap();
|
2014-06-18 13:25:36 -05:00
|
|
|
socket.write(b"GET / HTTP/1.0\n\n");
|
2013-04-19 20:47:31 -05:00
|
|
|
let response = socket.read_to_end();
|
2014-06-09 09:33:04 -05:00
|
|
|
# }
|
2013-12-08 01:12:07 -06:00
|
|
|
```
|
2013-04-19 20:47:31 -05:00
|
|
|
|
2014-02-22 17:53:54 -06:00
|
|
|
* Make a simple TCP server
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
```rust
|
2014-02-22 17:53:54 -06:00
|
|
|
# fn main() { }
|
|
|
|
# fn foo() {
|
2014-04-11 05:18:19 -05:00
|
|
|
# #![allow(dead_code)]
|
|
|
|
use std::io::{TcpListener, TcpStream};
|
2014-02-22 17:53:54 -06:00
|
|
|
use std::io::{Acceptor, Listener};
|
|
|
|
|
Easier interface for TCP ::connect and ::bind.
Prior to this commit, TcpStream::connect and TcpListener::bind took a
single SocketAddr argument. This worked well enough, but the API felt a
little too "low level" for most simple use cases.
A great example is connecting to rust-lang.org on port 80. Rust users would
need to:
1. resolve the IP address of rust-lang.org using
io::net::addrinfo::get_host_addresses.
2. check for errors
3. if all went well, use the returned IP address and the port number
to construct a SocketAddr
4. pass this SocketAddr to TcpStream::connect.
I'm modifying the type signature of TcpStream::connect and
TcpListener::bind so that the API is a little easier to use.
TcpStream::connect now accepts two arguments: a string describing the
host/IP of the host we wish to connect to, and a u16 representing the
remote port number.
Similarly, TcpListener::bind has been modified to take two arguments:
a string describing the local interface address (e.g. "0.0.0.0" or
"127.0.0.1") and a u16 port number.
Here's how to port your Rust code to use the new TcpStream::connect API:
// old ::connect API
let addr = SocketAddr{ip: Ipv4Addr{127, 0, 0, 1}, port: 8080};
let stream = TcpStream::connect(addr).unwrap()
// new ::connect API (minimal change)
let addr = SocketAddr{ip: Ipv4Addr{127, 0, 0, 1}, port: 8080};
let stream = TcpStream::connect(addr.ip.to_str(), addr.port()).unwrap()
// new ::connect API (more compact)
let stream = TcpStream::connect("127.0.0.1", 8080).unwrap()
// new ::connect API (hostname)
let stream = TcpStream::connect("rust-lang.org", 80)
Similarly, for TcpListener::bind:
// old ::bind API
let addr = SocketAddr{ip: Ipv4Addr{0, 0, 0, 0}, port: 8080};
let mut acceptor = TcpListener::bind(addr).listen();
// new ::bind API (minimal change)
let addr = SocketAddr{ip: Ipv4Addr{0, 0, 0, 0}, port: 8080};
let mut acceptor = TcpListener::bind(addr.ip.to_str(), addr.port()).listen()
// new ::bind API (more compact)
let mut acceptor = TcpListener::bind("0.0.0.0", 8080).listen()
[breaking-change]
2014-05-03 03:12:31 -05:00
|
|
|
let listener = TcpListener::bind("127.0.0.1", 80);
|
2014-02-22 17:53:54 -06:00
|
|
|
|
|
|
|
// bind the listener to the specified address
|
|
|
|
let mut acceptor = listener.listen();
|
|
|
|
|
2014-04-11 05:18:19 -05:00
|
|
|
fn handle_client(mut stream: TcpStream) {
|
|
|
|
// ...
|
|
|
|
# &mut stream; // silence unused mutability/variable warning
|
|
|
|
}
|
|
|
|
// accept connections and process them, spawning a new tasks for each one
|
2014-02-22 17:53:54 -06:00
|
|
|
for stream in acceptor.incoming() {
|
2014-04-11 05:18:19 -05:00
|
|
|
match stream {
|
|
|
|
Err(e) => { /* connection failed */ }
|
|
|
|
Ok(stream) => spawn(proc() {
|
|
|
|
// connection succeeded
|
|
|
|
handle_client(stream)
|
|
|
|
})
|
|
|
|
}
|
2014-02-22 17:53:54 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// close the socket server
|
|
|
|
drop(acceptor);
|
|
|
|
# }
|
2013-12-08 01:12:07 -06:00
|
|
|
```
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-04-23 21:21:37 -05:00
|
|
|
|
2013-04-17 19:55:21 -05:00
|
|
|
# Error Handling
|
|
|
|
|
2013-04-23 21:21:37 -05:00
|
|
|
I/O is an area where nearly every operation can result in unexpected
|
2014-01-30 18:55:20 -06:00
|
|
|
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.
|
2013-04-23 21:21:37 -05:00
|
|
|
|
|
|
|
Rust's I/O employs a combination of techniques to reduce boilerplate
|
|
|
|
while still providing feedback about errors. The basic strategy:
|
|
|
|
|
2014-01-30 18:55:20 -06:00
|
|
|
* All I/O operations return `IoResult<T>` which is equivalent to
|
2014-02-22 17:53:54 -06:00
|
|
|
`Result<T, IoError>`. The `Result` type is defined in the `std::result`
|
2014-01-30 18:55:20 -06:00
|
|
|
module.
|
|
|
|
* If the `Result` type goes unused, then the compiler will by default emit a
|
2014-02-22 17:53:54 -06:00
|
|
|
warning about the unused result. This is because `Result` has the
|
|
|
|
`#[must_use]` attribute.
|
2014-01-30 18:55:20 -06:00
|
|
|
* 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.
|
2013-04-23 21:21:37 -05:00
|
|
|
|
|
|
|
These features combine in the API to allow for expressions like
|
2014-06-18 13:25:36 -05:00
|
|
|
`File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")`
|
2014-01-02 06:35:08 -06:00
|
|
|
without having to worry about whether "diary.txt" exists or whether
|
|
|
|
the write succeeds. As written, if either `new` or `write_line`
|
2014-01-30 18:55:20 -06:00
|
|
|
encounters an error then the result of the entire expression will
|
|
|
|
be an error.
|
2014-01-02 06:35:08 -06:00
|
|
|
|
|
|
|
If you wanted to handle the error though you might write:
|
|
|
|
|
|
|
|
```rust
|
2014-04-14 10:30:31 -05:00
|
|
|
# #![allow(unused_must_use)]
|
2014-01-02 06:35:08 -06:00
|
|
|
use std::io::File;
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") {
|
2014-02-22 17:53:54 -06:00
|
|
|
Ok(()) => (), // succeeded
|
2014-01-30 18:55:20 -06:00
|
|
|
Err(e) => println!("failed to write to my diary: {}", e),
|
2014-01-02 06:35:08 -06:00
|
|
|
}
|
2014-01-30 18:55:20 -06:00
|
|
|
|
2014-01-02 06:35:08 -06:00
|
|
|
# ::std::io::fs::unlink(&Path::new("diary.txt"));
|
|
|
|
```
|
2013-04-23 21:21:37 -05:00
|
|
|
|
2014-01-30 18:55:20 -06:00
|
|
|
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.
|
2013-04-23 21:21:37 -05:00
|
|
|
|
2014-03-10 18:30:23 -05:00
|
|
|
## `try!`
|
|
|
|
|
|
|
|
Explicit pattern matching on `IoResult`s can get quite verbose, especially
|
|
|
|
when performing many I/O operations. Some examples (like those above) are
|
|
|
|
alleviated with extra methods implemented on `IoResult`, but others have more
|
|
|
|
complex interdependencies among each I/O operation.
|
|
|
|
|
|
|
|
The `try!` macro from `std::macros` is provided as a method of early-return
|
|
|
|
inside `Result`-returning functions. It expands to an early-return on `Err`
|
|
|
|
and otherwise unwraps the contained `Ok` value.
|
|
|
|
|
|
|
|
If you wanted to read several `u32`s from a file and return their product:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use std::io::{File, IoResult};
|
|
|
|
|
|
|
|
fn file_product(p: &Path) -> IoResult<u32> {
|
|
|
|
let mut f = File::open(p);
|
|
|
|
let x1 = try!(f.read_le_u32());
|
|
|
|
let x2 = try!(f.read_le_u32());
|
|
|
|
|
|
|
|
Ok(x1 * x2)
|
|
|
|
}
|
|
|
|
|
|
|
|
match file_product(&Path::new("numbers.bin")) {
|
|
|
|
Ok(x) => println!("{}", x),
|
|
|
|
Err(e) => println!("Failed to read numbers!")
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
With `try!` in `file_product`, each `read_le_u32` need not be directly
|
|
|
|
concerned with error handling; instead its caller is responsible for
|
|
|
|
responding to errors that may occur while attempting to read the numbers.
|
|
|
|
|
2013-04-17 19:55:21 -05:00
|
|
|
*/
|
|
|
|
|
2014-06-30 19:22:40 -05:00
|
|
|
#![experimental]
|
2014-03-21 20:05:05 -05:00
|
|
|
#![deny(unused_must_use)]
|
2013-11-11 00:46:32 -06:00
|
|
|
|
2014-01-04 07:26:03 -06:00
|
|
|
use char::Char;
|
2014-05-19 13:32:09 -05:00
|
|
|
use collections::Collection;
|
2014-01-29 18:33:57 -06:00
|
|
|
use fmt;
|
2013-10-25 20:08:45 -05:00
|
|
|
use int;
|
2013-11-11 00:46:32 -06:00
|
|
|
use iter::Iterator;
|
2014-03-24 08:39:40 -05:00
|
|
|
use libc;
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
use mem::transmute;
|
2014-05-07 00:54:44 -05:00
|
|
|
use ops::{BitOr, BitAnd, Sub, Not};
|
2013-10-25 19:04:37 -05:00
|
|
|
use option::{Option, Some, None};
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
use os;
|
2014-07-10 16:19:17 -05:00
|
|
|
use boxed::Box;
|
2013-10-25 19:04:37 -05:00
|
|
|
use result::{Ok, Err, Result};
|
2014-06-03 22:09:39 -05:00
|
|
|
use rt::rtio;
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
use slice::{Vector, MutableVector, ImmutableVector};
|
2014-06-21 05:39:03 -05:00
|
|
|
use str::{Str, StrSlice};
|
2014-01-29 18:33:57 -06:00
|
|
|
use str;
|
2014-05-22 18:57:53 -05:00
|
|
|
use string::String;
|
2013-10-25 20:08:45 -05:00
|
|
|
use uint;
|
Add libunicode; move unicode functions from core
- created new crate, libunicode, below libstd
- split Char trait into Char (libcore) and UnicodeChar (libunicode)
- Unicode-aware functions now live in libunicode
- is_alphabetic, is_XID_start, is_XID_continue, is_lowercase,
is_uppercase, is_whitespace, is_alphanumeric, is_control,
is_digit, to_uppercase, to_lowercase
- added width method in UnicodeChar trait
- determines printed width of character in columns, or None if it is
a non-NULL control character
- takes a boolean argument indicating whether the present context is
CJK or not (characters with 'A'mbiguous widths are double-wide in
CJK contexts, single-wide otherwise)
- split StrSlice into StrSlice (libcore) and UnicodeStrSlice
(libunicode)
- functionality formerly in StrSlice that relied upon Unicode
functionality from Char is now in UnicodeStrSlice
- words, is_whitespace, is_alphanumeric, trim, trim_left, trim_right
- also moved Words type alias into libunicode because words method is
in UnicodeStrSlice
- unified Unicode tables from libcollections, libcore, and libregex into
libunicode
- updated unicode.py in src/etc to generate aforementioned tables
- generated new tables based on latest Unicode data
- added UnicodeChar and UnicodeStrSlice traits to prelude
- libunicode is now the collection point for the std::char module,
combining the libunicode functionality with the Char functionality
from libcore
- thus, moved doc comment for char from core::char to unicode::char
- libcollections remains the collection point for std::str
The Unicode-aware functions that previously lived in the Char and
StrSlice traits are no longer available to programs that only use
libcore. To regain use of these methods, include the libunicode crate
and use the UnicodeChar and/or UnicodeStrSlice traits:
extern crate unicode;
use unicode::UnicodeChar;
use unicode::UnicodeStrSlice;
use unicode::Words; // if you want to use the words() method
NOTE: this does *not* impact programs that use libstd, since UnicodeChar
and UnicodeStrSlice have been added to the prelude.
closes #15224
[breaking-change]
2014-06-30 16:04:10 -05:00
|
|
|
use unicode::UnicodeChar;
|
2014-03-26 11:24:16 -05:00
|
|
|
use vec::Vec;
|
2013-04-17 19:55:21 -05:00
|
|
|
|
|
|
|
// 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;
|
|
|
|
|
2013-10-31 17:15:30 -05:00
|
|
|
pub use self::fs::File;
|
2013-07-19 18:03:02 -05:00
|
|
|
pub use self::timer::Timer;
|
2013-04-17 19:55:21 -05:00
|
|
|
pub use self::net::ip::IpAddr;
|
|
|
|
pub use self::net::tcp::TcpListener;
|
|
|
|
pub use self::net::tcp::TcpStream;
|
|
|
|
pub use self::net::udp::UdpStream;
|
2013-09-16 17:28:56 -05:00
|
|
|
pub use self::pipe::PipeStream;
|
2014-05-05 16:33:55 -05:00
|
|
|
pub use self::process::{Process, Command};
|
2014-03-14 13:16:10 -05:00
|
|
|
pub use self::tempfile::TempDir;
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2014-01-15 15:25:09 -06:00
|
|
|
pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
|
|
|
|
pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
|
|
|
|
LineBufferedWriter};
|
2014-03-09 16:58:32 -05:00
|
|
|
pub use self::comm_adapters::{ChanReader, ChanWriter};
|
2014-01-15 15:25:09 -06:00
|
|
|
|
2014-03-14 13:16:10 -05:00
|
|
|
// this comes first to get the iotest! macro
|
2013-12-13 13:30:59 -06:00
|
|
|
pub mod test;
|
2013-12-12 23:38:57 -06:00
|
|
|
|
2014-03-14 13:16:10 -05:00
|
|
|
mod buffered;
|
|
|
|
mod comm_adapters;
|
|
|
|
mod mem;
|
|
|
|
mod result;
|
|
|
|
mod tempfile;
|
|
|
|
pub mod extensions;
|
2013-10-31 17:15:30 -05:00
|
|
|
pub mod fs;
|
2014-03-14 13:16:10 -05:00
|
|
|
pub mod net;
|
2013-09-16 17:28:56 -05:00
|
|
|
pub mod pipe;
|
|
|
|
pub mod process;
|
2014-03-14 13:16:10 -05:00
|
|
|
pub mod signal;
|
2013-04-17 19:55:21 -05:00
|
|
|
pub mod stdio;
|
2013-07-19 18:22:13 -05:00
|
|
|
pub mod timer;
|
2013-12-10 00:53:09 -06:00
|
|
|
pub mod util;
|
|
|
|
|
2013-05-13 18:56:16 -05:00
|
|
|
/// The default buffer size for various I/O operations
|
2014-01-15 15:25:09 -06:00
|
|
|
// libuv recommends 64k buffers to maximize throughput
|
|
|
|
// https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
|
2013-10-15 22:55:50 -05:00
|
|
|
static DEFAULT_BUF_SIZE: uint = 1024 * 64;
|
2013-05-13 18:56:16 -05:00
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A convenient typedef of the return value of any I/O action.
|
2014-01-29 18:33:57 -06:00
|
|
|
pub type IoResult<T> = Result<T, IoError>;
|
|
|
|
|
2013-04-17 19:55:21 -05:00
|
|
|
/// The type passed to I/O condition handlers to indicate error
|
|
|
|
///
|
2014-01-26 02:43:42 -06:00
|
|
|
/// # FIXME
|
2013-04-17 19:55:21 -05:00
|
|
|
///
|
|
|
|
/// Is something like this sufficient? It's kind of archaic
|
2014-07-13 18:28:01 -05:00
|
|
|
#[deriving(PartialEq, Eq, Clone)]
|
2013-04-17 19:55:21 -05:00
|
|
|
pub struct IoError {
|
2014-02-24 02:31:08 -06:00
|
|
|
/// An enumeration which can be matched against for determining the flavor
|
|
|
|
/// of error.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub kind: IoErrorKind,
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A human-readable description about the error
|
2014-03-27 17:09:47 -05:00
|
|
|
pub desc: &'static str,
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Detailed information about this error, not always available
|
2014-05-22 18:57:53 -05:00
|
|
|
pub detail: Option<String>
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
|
|
|
|
2014-03-24 08:39:40 -05:00
|
|
|
impl IoError {
|
|
|
|
/// Convert an `errno` value into an `IoError`.
|
|
|
|
///
|
|
|
|
/// If `detail` is `true`, the `detail` field of the `IoError`
|
|
|
|
/// struct is filled with an allocated string describing the error
|
|
|
|
/// in more detail, retrieved from the operating system.
|
|
|
|
pub fn from_errno(errno: uint, detail: bool) -> IoError {
|
2014-06-03 14:33:18 -05:00
|
|
|
|
2014-03-24 08:39:40 -05:00
|
|
|
#[cfg(windows)]
|
|
|
|
fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
|
|
|
|
match errno {
|
|
|
|
libc::EOF => (EndOfFile, "end of file"),
|
|
|
|
libc::ERROR_NO_DATA => (BrokenPipe, "the pipe is being closed"),
|
|
|
|
libc::ERROR_FILE_NOT_FOUND => (FileNotFound, "file not found"),
|
|
|
|
libc::ERROR_INVALID_NAME => (InvalidInput, "invalid file name"),
|
|
|
|
libc::WSAECONNREFUSED => (ConnectionRefused, "connection refused"),
|
|
|
|
libc::WSAECONNRESET => (ConnectionReset, "connection reset"),
|
2014-06-04 02:01:40 -05:00
|
|
|
libc::ERROR_ACCESS_DENIED | libc::WSAEACCES =>
|
|
|
|
(PermissionDenied, "permission denied"),
|
2014-03-24 08:39:40 -05:00
|
|
|
libc::WSAEWOULDBLOCK => {
|
|
|
|
(ResourceUnavailable, "resource temporarily unavailable")
|
|
|
|
}
|
|
|
|
libc::WSAENOTCONN => (NotConnected, "not connected"),
|
|
|
|
libc::WSAECONNABORTED => (ConnectionAborted, "connection aborted"),
|
|
|
|
libc::WSAEADDRNOTAVAIL => (ConnectionRefused, "address not available"),
|
|
|
|
libc::WSAEADDRINUSE => (ConnectionRefused, "address in use"),
|
|
|
|
libc::ERROR_BROKEN_PIPE => (EndOfFile, "the pipe has ended"),
|
2014-04-27 20:11:49 -05:00
|
|
|
libc::ERROR_OPERATION_ABORTED =>
|
|
|
|
(TimedOut, "operation timed out"),
|
2014-06-03 22:09:39 -05:00
|
|
|
libc::WSAEINVAL => (InvalidInput, "invalid argument"),
|
|
|
|
libc::ERROR_CALL_NOT_IMPLEMENTED =>
|
|
|
|
(IoUnavailable, "function not implemented"),
|
2014-06-04 02:01:40 -05:00
|
|
|
libc::ERROR_INVALID_HANDLE =>
|
2014-06-03 22:09:39 -05:00
|
|
|
(MismatchedFileTypeForOperation,
|
|
|
|
"invalid handle provided to function"),
|
|
|
|
libc::ERROR_NOTHING_TO_TERMINATE =>
|
|
|
|
(InvalidInput, "no process to kill"),
|
2014-03-24 08:39:40 -05:00
|
|
|
|
|
|
|
// libuv maps this error code to EISDIR. we do too. if it is found
|
|
|
|
// to be incorrect, we can add in some more machinery to only
|
|
|
|
// return this message when ERROR_INVALID_FUNCTION after certain
|
|
|
|
// win32 calls.
|
|
|
|
libc::ERROR_INVALID_FUNCTION => (InvalidInput,
|
|
|
|
"illegal operation on a directory"),
|
|
|
|
|
|
|
|
_ => (OtherIoError, "unknown error")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(windows))]
|
|
|
|
fn get_err(errno: i32) -> (IoErrorKind, &'static str) {
|
|
|
|
// FIXME: this should probably be a bit more descriptive...
|
|
|
|
match errno {
|
|
|
|
libc::EOF => (EndOfFile, "end of file"),
|
|
|
|
libc::ECONNREFUSED => (ConnectionRefused, "connection refused"),
|
|
|
|
libc::ECONNRESET => (ConnectionReset, "connection reset"),
|
|
|
|
libc::EPERM | libc::EACCES =>
|
|
|
|
(PermissionDenied, "permission denied"),
|
|
|
|
libc::EPIPE => (BrokenPipe, "broken pipe"),
|
|
|
|
libc::ENOTCONN => (NotConnected, "not connected"),
|
|
|
|
libc::ECONNABORTED => (ConnectionAborted, "connection aborted"),
|
|
|
|
libc::EADDRNOTAVAIL => (ConnectionRefused, "address not available"),
|
|
|
|
libc::EADDRINUSE => (ConnectionRefused, "address in use"),
|
|
|
|
libc::ENOENT => (FileNotFound, "no such file or directory"),
|
|
|
|
libc::EISDIR => (InvalidInput, "illegal operation on a directory"),
|
2014-06-03 22:09:39 -05:00
|
|
|
libc::ENOSYS => (IoUnavailable, "function not implemented"),
|
|
|
|
libc::EINVAL => (InvalidInput, "invalid argument"),
|
|
|
|
libc::ENOTTY =>
|
|
|
|
(MismatchedFileTypeForOperation,
|
|
|
|
"file descriptor is not a TTY"),
|
|
|
|
libc::ETIMEDOUT => (TimedOut, "operation timed out"),
|
|
|
|
libc::ECANCELED => (TimedOut, "operation aborted"),
|
|
|
|
|
|
|
|
// These two constants can have the same value on some systems,
|
|
|
|
// but different values on others, so we can't use a match
|
|
|
|
// clause
|
2014-03-24 08:39:40 -05:00
|
|
|
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
|
|
|
|
(ResourceUnavailable, "resource temporarily unavailable"),
|
|
|
|
|
|
|
|
_ => (OtherIoError, "unknown error")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let (kind, desc) = get_err(errno as i32);
|
|
|
|
IoError {
|
|
|
|
kind: kind,
|
|
|
|
desc: desc,
|
2014-06-03 14:33:18 -05:00
|
|
|
detail: if detail && kind == OtherIoError {
|
|
|
|
Some(os::error_string(errno).as_slice().chars().map(|c| c.to_lowercase()).collect())
|
2014-05-16 12:45:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
2014-03-24 08:39:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieve the last error to occur as a (detailed) IoError.
|
|
|
|
///
|
|
|
|
/// This uses the OS `errno`, and so there should not be any task
|
|
|
|
/// descheduling or migration (other than that performed by the
|
|
|
|
/// operating system) between the call(s) for which errors are
|
|
|
|
/// being checked and the call of this function.
|
|
|
|
pub fn last_error() -> IoError {
|
|
|
|
IoError::from_errno(os::errno() as uint, true)
|
|
|
|
}
|
2014-06-03 22:09:39 -05:00
|
|
|
|
|
|
|
fn from_rtio_error(err: rtio::IoError) -> IoError {
|
|
|
|
let rtio::IoError { code, extra, detail } = err;
|
|
|
|
let mut ioerr = IoError::from_errno(code, false);
|
|
|
|
ioerr.detail = detail;
|
|
|
|
ioerr.kind = match ioerr.kind {
|
|
|
|
TimedOut if extra > 0 => ShortWrite(extra),
|
|
|
|
k => k,
|
|
|
|
};
|
|
|
|
return ioerr;
|
|
|
|
}
|
2014-03-24 08:39:40 -05:00
|
|
|
}
|
|
|
|
|
2014-02-01 13:24:42 -06:00
|
|
|
impl fmt::Show for IoError {
|
2014-02-05 06:55:13 -06:00
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
2014-06-03 14:33:18 -05:00
|
|
|
match *self {
|
|
|
|
IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
|
|
|
|
write!(fmt, "{}", detail),
|
|
|
|
IoError { detail: None, desc, .. } =>
|
|
|
|
write!(fmt, "{}", desc),
|
|
|
|
IoError { detail: Some(ref detail), desc, .. } =>
|
|
|
|
write!(fmt, "{} ({})", desc, detail)
|
2014-01-29 18:33:57 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A list specifying general categories of I/O error.
|
2014-07-13 18:28:01 -05:00
|
|
|
#[deriving(PartialEq, Eq, Clone, Show)]
|
2013-04-17 19:55:21 -05:00
|
|
|
pub enum IoErrorKind {
|
2014-03-16 17:59:04 -05:00
|
|
|
/// Any I/O error not part of this list.
|
2013-04-24 22:20:03 -05:00
|
|
|
OtherIoError,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The operation could not complete because end of file was reached.
|
2013-04-24 22:20:03 -05:00
|
|
|
EndOfFile,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The file was not found.
|
2013-04-17 19:55:21 -05:00
|
|
|
FileNotFound,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The file permissions disallowed access to this file.
|
2013-04-24 22:20:03 -05:00
|
|
|
PermissionDenied,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A network connection failed for some reason not specified in this list.
|
2013-04-17 19:55:21 -05:00
|
|
|
ConnectionFailed,
|
2014-05-22 07:50:31 -05:00
|
|
|
/// The network operation failed because the network connection was closed.
|
2013-04-17 19:55:21 -05:00
|
|
|
Closed,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The connection was refused by the remote server.
|
2013-04-24 22:20:03 -05:00
|
|
|
ConnectionRefused,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The connection was reset by the remote server.
|
2013-05-14 23:18:47 -05:00
|
|
|
ConnectionReset,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The connection was aborted (terminated) by the remote server.
|
2013-10-26 18:04:05 -05:00
|
|
|
ConnectionAborted,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The network operation failed because it was not connected yet.
|
2013-10-04 16:10:02 -05:00
|
|
|
NotConnected,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The operation failed because a pipe was closed.
|
2013-09-15 14:23:53 -05:00
|
|
|
BrokenPipe,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A file already existed with that name.
|
2013-09-15 14:23:53 -05:00
|
|
|
PathAlreadyExists,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// No file exists at that location.
|
2013-09-15 14:23:53 -05:00
|
|
|
PathDoesntExist,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The path did not specify the type of file that this operation required. For example,
|
|
|
|
/// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
|
2013-10-16 19:05:28 -05:00
|
|
|
MismatchedFileTypeForOperation,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The operation temporarily failed (for example, because a signal was received), and retrying
|
|
|
|
/// may succeed.
|
2013-10-17 19:04:51 -05:00
|
|
|
ResourceUnavailable,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// No I/O functionality is available for this task.
|
2013-10-16 19:05:28 -05:00
|
|
|
IoUnavailable,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A parameter was incorrect in a way that caused an I/O error not part of this list.
|
2013-12-08 13:12:25 -06:00
|
|
|
InvalidInput,
|
2014-04-18 15:23:56 -05:00
|
|
|
/// The I/O operation's timeout expired, causing it to be canceled.
|
|
|
|
TimedOut,
|
2014-04-25 22:47:49 -05:00
|
|
|
/// This write operation failed to write all of its data.
|
|
|
|
///
|
|
|
|
/// Normally the write() method on a Writer guarantees that all of its data
|
|
|
|
/// has been written, but some operations may be terminated after only
|
|
|
|
/// partially writing some data. An example of this is a timed out write
|
|
|
|
/// which successfully wrote a known number of bytes, but bailed out after
|
|
|
|
/// doing so.
|
|
|
|
///
|
|
|
|
/// The payload contained as part of this variant is the number of bytes
|
|
|
|
/// which are known to have been successfully written.
|
|
|
|
ShortWrite(uint),
|
2014-03-25 01:22:23 -05:00
|
|
|
/// The Reader returned 0 bytes from `read()` too many times.
|
|
|
|
NoProgress,
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
2013-03-13 22:02:48 -05:00
|
|
|
|
2014-06-03 14:33:18 -05:00
|
|
|
/// A trait that lets you add a `detail` to an IoError easily
|
|
|
|
trait UpdateIoError<T> {
|
|
|
|
/// Returns an IoError with updated description and detail
|
|
|
|
fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> Self;
|
|
|
|
|
|
|
|
/// Returns an IoError with updated detail
|
|
|
|
fn update_detail(self, detail: |&IoError| -> String) -> Self;
|
|
|
|
|
|
|
|
/// Returns an IoError with update description
|
|
|
|
fn update_desc(self, desc: &'static str) -> Self;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> UpdateIoError<T> for IoResult<T> {
|
|
|
|
fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> IoResult<T> {
|
|
|
|
self.map_err(|mut e| {
|
|
|
|
let detail = detail(&e);
|
|
|
|
e.desc = desc;
|
|
|
|
e.detail = Some(detail);
|
|
|
|
e
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn update_detail(self, detail: |&IoError| -> String) -> IoResult<T> {
|
|
|
|
self.map_err(|mut e| { e.detail = Some(detail(&e)); e })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn update_desc(self, desc: &'static str) -> IoResult<T> {
|
|
|
|
self.map_err(|mut e| { e.desc = desc; e })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-25 01:22:23 -05:00
|
|
|
static NO_PROGRESS_LIMIT: uint = 1000;
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A trait for objects which are byte-oriented streams. Readers are defined by
|
|
|
|
/// one method, `read`. This function will block until data is available,
|
|
|
|
/// filling in the provided buffer with any data read.
|
|
|
|
///
|
|
|
|
/// Readers are intended to be composable with one another. Many objects
|
|
|
|
/// throughout the I/O and related libraries take and provide types which
|
|
|
|
/// implement the `Reader` trait.
|
2013-04-17 19:55:21 -05:00
|
|
|
pub trait Reader {
|
2013-10-25 20:08:45 -05:00
|
|
|
|
2014-01-30 18:55:20 -06:00
|
|
|
// Only method which need to get implemented for this trait
|
2013-10-25 20:08:45 -05:00
|
|
|
|
2013-04-17 19:55:21 -05:00
|
|
|
/// Read bytes, up to the length of `buf` and place them in `buf`.
|
2014-03-25 01:22:23 -05:00
|
|
|
/// Returns the number of bytes read. The number of bytes read may
|
2014-01-30 18:55:20 -06:00
|
|
|
/// be less than the number requested, even 0. Returns `Err` on EOF.
|
2013-03-13 22:02:48 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-04-17 19:55:21 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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
|
2014-03-25 01:22:23 -05:00
|
|
|
///
|
2014-05-22 07:50:31 -05:00
|
|
|
/// # Implementation Note
|
2014-03-25 01:22:23 -05:00
|
|
|
///
|
|
|
|
/// When implementing this method on a new Reader, you are strongly encouraged
|
|
|
|
/// not to return 0 if you can avoid it.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
|
2013-03-13 22:02:48 -05:00
|
|
|
|
2013-10-25 20:08:45 -05:00
|
|
|
// Convenient helper methods based on the above methods
|
|
|
|
|
2014-03-25 01:22:23 -05:00
|
|
|
/// Reads at least `min` bytes and places them in `buf`.
|
|
|
|
/// Returns the number of bytes read.
|
2014-03-20 20:52:00 -05:00
|
|
|
///
|
2014-03-25 01:22:23 -05:00
|
|
|
/// This will continue to call `read` until at least `min` bytes have been
|
|
|
|
/// read. If `read` returns 0 too many times, `NoProgress` will be
|
|
|
|
/// returned.
|
2014-03-20 20:52:00 -05:00
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
|
|
|
/// If an error occurs at any point, that error is returned, and no further
|
|
|
|
/// bytes are read.
|
2014-03-25 01:22:23 -05:00
|
|
|
fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
|
|
|
|
if min > buf.len() {
|
2014-05-16 12:45:16 -05:00
|
|
|
return Err(IoError {
|
2014-06-21 05:39:03 -05:00
|
|
|
detail: Some(String::from_str("the buffer is too short")),
|
2014-05-16 12:45:16 -05:00
|
|
|
..standard_error(InvalidInput)
|
|
|
|
});
|
2014-03-25 01:22:23 -05:00
|
|
|
}
|
2014-03-20 20:52:00 -05:00
|
|
|
let mut read = 0;
|
2014-03-25 01:22:23 -05:00
|
|
|
while read < min {
|
|
|
|
let mut zeroes = 0;
|
|
|
|
loop {
|
|
|
|
match self.read(buf.mut_slice_from(read)) {
|
|
|
|
Ok(0) => {
|
|
|
|
zeroes += 1;
|
|
|
|
if zeroes >= NO_PROGRESS_LIMIT {
|
|
|
|
return Err(standard_error(NoProgress));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(n) => {
|
|
|
|
read += n;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
err@Err(_) => return err
|
|
|
|
}
|
|
|
|
}
|
2014-03-20 20:52:00 -05:00
|
|
|
}
|
2014-03-25 01:22:23 -05:00
|
|
|
Ok(read)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a single byte. Returns `Err` on EOF.
|
|
|
|
fn read_byte(&mut self) -> IoResult<u8> {
|
|
|
|
let mut buf = [0];
|
|
|
|
try!(self.read_at_least(1, buf));
|
|
|
|
Ok(buf[0])
|
2014-03-20 20:52:00 -05:00
|
|
|
}
|
|
|
|
|
2014-03-25 01:22:23 -05:00
|
|
|
/// Reads up to `len` bytes and appends them to a vector.
|
|
|
|
/// Returns the number of bytes read. The number of bytes read may be
|
|
|
|
/// less than the number requested, even 0. Returns Err on EOF.
|
|
|
|
///
|
|
|
|
/// # Error
|
2013-10-25 20:08:45 -05:00
|
|
|
///
|
2014-03-25 01:22:23 -05:00
|
|
|
/// If an error occurs during this I/O operation, then it is returned
|
|
|
|
/// as `Err(IoError)`. See `read()` for more details.
|
|
|
|
fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
|
|
|
|
let start_len = buf.len();
|
|
|
|
buf.reserve_additional(len);
|
|
|
|
|
|
|
|
let n = {
|
|
|
|
let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
|
|
|
|
try!(self.read(s))
|
|
|
|
};
|
|
|
|
unsafe { buf.set_len(start_len + n) };
|
|
|
|
Ok(n)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads at least `min` bytes, but no more than `len`, and appends them to
|
|
|
|
/// a vector.
|
|
|
|
/// Returns the number of bytes read.
|
|
|
|
///
|
|
|
|
/// This will continue to call `read` until at least `min` bytes have been
|
|
|
|
/// read. If `read` returns 0 too many times, `NoProgress` will be
|
|
|
|
/// returned.
|
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
|
|
|
/// If an error occurs at any point, that error is returned, and no further
|
|
|
|
/// bytes are read.
|
|
|
|
fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
|
|
|
|
if min > len {
|
2014-05-16 12:45:16 -05:00
|
|
|
return Err(IoError {
|
2014-06-21 05:39:03 -05:00
|
|
|
detail: Some(String::from_str("the buffer is too short")),
|
2014-05-16 12:45:16 -05:00
|
|
|
..standard_error(InvalidInput)
|
|
|
|
});
|
2014-02-07 05:33:11 -06:00
|
|
|
}
|
|
|
|
|
2014-01-29 18:33:57 -06:00
|
|
|
let start_len = buf.len();
|
2014-03-25 01:22:23 -05:00
|
|
|
buf.reserve_additional(len);
|
|
|
|
|
|
|
|
// we can't just use self.read_at_least(min, slice) because we need to push
|
|
|
|
// successful reads onto the vector before any returned errors.
|
|
|
|
|
|
|
|
let mut read = 0;
|
|
|
|
while read < min {
|
|
|
|
read += {
|
|
|
|
let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
|
|
|
|
try!(self.read_at_least(1, s))
|
|
|
|
};
|
|
|
|
unsafe { buf.set_len(start_len + read) };
|
|
|
|
}
|
|
|
|
Ok(read)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
2014-03-15 00:42:24 -05:00
|
|
|
/// Reads exactly `len` bytes and gives you back a new vector of length
|
|
|
|
/// `len`
|
2013-10-25 20:08:45 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-10-25 20:08:45 -05:00
|
|
|
///
|
2014-03-06 01:35:12 -06:00
|
|
|
/// Fails with the same conditions as `read`. Additionally returns error
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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
|
2014-03-25 01:22:23 -05:00
|
|
|
/// recommended to use the `push_at_least` or `read` methods.
|
2014-03-26 11:24:16 -05:00
|
|
|
fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
|
|
|
|
let mut buf = Vec::with_capacity(len);
|
2014-03-25 01:22:23 -05:00
|
|
|
match self.push_at_least(len, len, &mut buf) {
|
|
|
|
Ok(_) => Ok(buf),
|
2014-01-30 18:55:20 -06:00
|
|
|
Err(e) => Err(e),
|
|
|
|
}
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads all remaining bytes from the stream.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
|
|
|
///
|
|
|
|
/// Returns any non-EOF error immediately. Previously read bytes are
|
|
|
|
/// discarded when an error is returned.
|
2013-10-25 20:08:45 -05:00
|
|
|
///
|
2014-02-01 13:24:42 -06:00
|
|
|
/// When EOF is encountered, all bytes read up to that point are returned.
|
2014-03-26 11:24:16 -05:00
|
|
|
fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
|
|
|
|
let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
|
2014-01-29 18:33:57 -06:00
|
|
|
loop {
|
2014-03-25 01:22:23 -05:00
|
|
|
match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
|
|
|
|
Ok(_) => {}
|
2014-02-01 13:24:42 -06:00
|
|
|
Err(ref e) if e.kind == EndOfFile => break,
|
2014-01-29 18:33:57 -06:00
|
|
|
Err(e) => return Err(e)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
2014-01-29 18:33:57 -06:00
|
|
|
}
|
|
|
|
return Ok(buf);
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
2013-12-08 13:12:25 -06:00
|
|
|
/// Reads all of the remaining bytes of this stream, interpreting them as a
|
|
|
|
/// UTF-8 encoded stream. The corresponding string is returned.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-12-08 13:12:25 -06:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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.
|
2014-06-21 05:39:03 -05:00
|
|
|
fn read_to_string(&mut self) -> IoResult<String> {
|
2014-01-29 18:33:57 -06:00
|
|
|
self.read_to_end().and_then(|s| {
|
2014-03-26 11:24:16 -05:00
|
|
|
match str::from_utf8(s.as_slice()) {
|
2014-06-21 05:39:03 -05:00
|
|
|
Some(s) => Ok(String::from_str(s)),
|
2014-01-29 18:33:57 -06:00
|
|
|
None => Err(standard_error(InvalidInput)),
|
2013-12-08 13:12:25 -06:00
|
|
|
}
|
2014-01-29 18:33:57 -06:00
|
|
|
})
|
2013-12-08 13:12:25 -06:00
|
|
|
}
|
|
|
|
|
2013-10-25 20:08:45 -05:00
|
|
|
/// Create an iterator that reads a single byte on
|
|
|
|
/// each iteration, until EOF.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-10-25 20:08:45 -05:00
|
|
|
///
|
2014-02-19 20:53:46 -06:00
|
|
|
/// Any error other than `EndOfFile` that is produced by the underlying Reader
|
|
|
|
/// is returned by the iterator and should be handled by the caller.
|
2014-01-14 21:32:24 -06:00
|
|
|
fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self> {
|
|
|
|
extensions::Bytes::new(self)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Byte conversion helpers
|
|
|
|
|
|
|
|
/// Reads `n` little-endian unsigned integer bytes.
|
|
|
|
///
|
|
|
|
/// `n` must be between 1 and 8, inclusive.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
|
2013-10-25 20:08:45 -05:00
|
|
|
assert!(nbytes > 0 && nbytes <= 8);
|
|
|
|
|
|
|
|
let mut val = 0u64;
|
|
|
|
let mut pos = 0;
|
|
|
|
let mut i = nbytes;
|
|
|
|
while i > 0 {
|
2014-02-19 12:07:49 -06:00
|
|
|
val += (try!(self.read_u8()) as u64) << pos;
|
2013-10-25 20:08:45 -05:00
|
|
|
pos += 8;
|
|
|
|
i -= 1;
|
|
|
|
}
|
2014-01-29 18:33:57 -06:00
|
|
|
Ok(val)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads `n` little-endian signed integer bytes.
|
|
|
|
///
|
|
|
|
/// `n` must be between 1 and 8, inclusive.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
|
|
|
|
self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads `n` big-endian unsigned integer bytes.
|
|
|
|
///
|
|
|
|
/// `n` must be between 1 and 8, inclusive.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
|
2013-10-25 20:08:45 -05:00
|
|
|
assert!(nbytes > 0 && nbytes <= 8);
|
|
|
|
|
|
|
|
let mut val = 0u64;
|
|
|
|
let mut i = nbytes;
|
|
|
|
while i > 0 {
|
|
|
|
i -= 1;
|
2014-02-19 12:07:49 -06:00
|
|
|
val += (try!(self.read_u8()) as u64) << i * 8;
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
2014-01-29 18:33:57 -06:00
|
|
|
Ok(val)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads `n` big-endian signed integer bytes.
|
|
|
|
///
|
|
|
|
/// `n` must be between 1 and 8, inclusive.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
|
|
|
|
self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian unsigned integer.
|
|
|
|
///
|
2014-04-06 21:51:59 -05:00
|
|
|
/// The number of bytes returned is system-dependent.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_uint(&mut self) -> IoResult<uint> {
|
|
|
|
self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian integer.
|
|
|
|
///
|
2014-04-06 21:51:59 -05:00
|
|
|
/// The number of bytes returned is system-dependent.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_int(&mut self) -> IoResult<int> {
|
|
|
|
self.read_le_int_n(int::BYTES).map(|i| i as int)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian unsigned integer.
|
|
|
|
///
|
2014-04-06 21:51:59 -05:00
|
|
|
/// The number of bytes returned is system-dependent.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_uint(&mut self) -> IoResult<uint> {
|
|
|
|
self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian integer.
|
|
|
|
///
|
2014-04-06 21:51:59 -05:00
|
|
|
/// The number of bytes returned is system-dependent.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_int(&mut self) -> IoResult<int> {
|
|
|
|
self.read_be_int_n(int::BYTES).map(|i| i as int)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `u64`.
|
|
|
|
///
|
|
|
|
/// `u64`s are 8 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_u64(&mut self) -> IoResult<u64> {
|
2013-12-24 17:53:05 -06:00
|
|
|
self.read_be_uint_n(8)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `u32`.
|
|
|
|
///
|
|
|
|
/// `u32`s are 4 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_u32(&mut self) -> IoResult<u32> {
|
|
|
|
self.read_be_uint_n(4).map(|i| i as u32)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `u16`.
|
|
|
|
///
|
|
|
|
/// `u16`s are 2 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_u16(&mut self) -> IoResult<u16> {
|
|
|
|
self.read_be_uint_n(2).map(|i| i as u16)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `i64`.
|
|
|
|
///
|
|
|
|
/// `i64`s are 8 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_i64(&mut self) -> IoResult<i64> {
|
2013-12-24 17:53:05 -06:00
|
|
|
self.read_be_int_n(8)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `i32`.
|
|
|
|
///
|
|
|
|
/// `i32`s are 4 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_i32(&mut self) -> IoResult<i32> {
|
|
|
|
self.read_be_int_n(4).map(|i| i as i32)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `i16`.
|
|
|
|
///
|
|
|
|
/// `i16`s are 2 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_i16(&mut self) -> IoResult<i16> {
|
|
|
|
self.read_be_int_n(2).map(|i| i as i16)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `f64`.
|
|
|
|
///
|
|
|
|
/// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_f64(&mut self) -> IoResult<f64> {
|
|
|
|
self.read_be_u64().map(|i| unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
transmute::<u64, f64>(i)
|
2014-01-29 18:33:57 -06:00
|
|
|
})
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a big-endian `f32`.
|
|
|
|
///
|
|
|
|
/// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_be_f32(&mut self) -> IoResult<f32> {
|
|
|
|
self.read_be_u32().map(|i| unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
transmute::<u32, f32>(i)
|
2014-01-29 18:33:57 -06:00
|
|
|
})
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `u64`.
|
|
|
|
///
|
|
|
|
/// `u64`s are 8 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_u64(&mut self) -> IoResult<u64> {
|
2013-12-24 17:53:05 -06:00
|
|
|
self.read_le_uint_n(8)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `u32`.
|
|
|
|
///
|
|
|
|
/// `u32`s are 4 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_u32(&mut self) -> IoResult<u32> {
|
|
|
|
self.read_le_uint_n(4).map(|i| i as u32)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `u16`.
|
|
|
|
///
|
|
|
|
/// `u16`s are 2 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_u16(&mut self) -> IoResult<u16> {
|
|
|
|
self.read_le_uint_n(2).map(|i| i as u16)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `i64`.
|
|
|
|
///
|
|
|
|
/// `i64`s are 8 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_i64(&mut self) -> IoResult<i64> {
|
2013-12-24 17:53:05 -06:00
|
|
|
self.read_le_int_n(8)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `i32`.
|
|
|
|
///
|
|
|
|
/// `i32`s are 4 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_i32(&mut self) -> IoResult<i32> {
|
|
|
|
self.read_le_int_n(4).map(|i| i as i32)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `i16`.
|
|
|
|
///
|
|
|
|
/// `i16`s are 2 bytes long.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_i16(&mut self) -> IoResult<i16> {
|
|
|
|
self.read_le_int_n(2).map(|i| i as i16)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `f64`.
|
|
|
|
///
|
|
|
|
/// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_f64(&mut self) -> IoResult<f64> {
|
|
|
|
self.read_le_u64().map(|i| unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
transmute::<u64, f64>(i)
|
2014-01-29 18:33:57 -06:00
|
|
|
})
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Reads a little-endian `f32`.
|
|
|
|
///
|
|
|
|
/// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_le_f32(&mut self) -> IoResult<f32> {
|
|
|
|
self.read_le_u32().map(|i| unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
transmute::<u32, f32>(i)
|
2014-01-29 18:33:57 -06:00
|
|
|
})
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Read a u8.
|
|
|
|
///
|
|
|
|
/// `u8`s are 1 byte.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_u8(&mut self) -> IoResult<u8> {
|
|
|
|
self.read_byte()
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Read an i8.
|
|
|
|
///
|
|
|
|
/// `i8`s are 1 byte.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_i8(&mut self) -> IoResult<i8> {
|
|
|
|
self.read_byte().map(|i| i as i8)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
2014-02-13 22:27:53 -06:00
|
|
|
/// Creates a wrapper around a mutable reference to the reader.
|
|
|
|
///
|
|
|
|
/// This is useful to allow applying adaptors while still
|
|
|
|
/// retaining ownership of the original value.
|
|
|
|
fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self> {
|
|
|
|
RefReader { inner: self }
|
|
|
|
}
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
2013-03-13 22:02:48 -05:00
|
|
|
|
2014-05-05 20:56:44 -05:00
|
|
|
impl Reader for Box<Reader> {
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
|
2013-10-06 18:08:56 -05:00
|
|
|
}
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
impl<'a> Reader for &'a mut Reader {
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
|
2013-10-06 18:08:56 -05:00
|
|
|
}
|
|
|
|
|
2014-03-25 01:22:23 -05:00
|
|
|
/// Returns a slice of `v` between `start` and `end`.
|
|
|
|
///
|
2014-06-08 12:22:49 -05:00
|
|
|
/// Similar to `slice()` except this function only bounds the slice on the
|
2014-03-25 01:22:23 -05:00
|
|
|
/// capacity of `v`, not the length.
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Fails when `start` or `end` point outside the capacity of `v`, or when
|
|
|
|
/// `start` > `end`.
|
|
|
|
// Private function here because we aren't sure if we want to expose this as
|
|
|
|
// API yet. If so, it should be a method on Vec.
|
|
|
|
unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
|
|
|
|
use raw::Slice;
|
|
|
|
use ptr::RawPtr;
|
|
|
|
|
|
|
|
assert!(start <= end);
|
|
|
|
assert!(end <= v.capacity());
|
|
|
|
transmute(Slice {
|
|
|
|
data: v.as_ptr().offset(start as int),
|
|
|
|
len: end - start
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A `RefReader` is a struct implementing `Reader` which contains a reference
|
|
|
|
/// to another reader. This is often useful when composing streams.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # fn main() {}
|
|
|
|
/// # fn process_input<R: Reader>(r: R) {}
|
|
|
|
/// # fn foo() {
|
|
|
|
/// use std::io;
|
|
|
|
/// use std::io::util::LimitReader;
|
|
|
|
///
|
|
|
|
/// let mut stream = io::stdin();
|
|
|
|
///
|
|
|
|
/// // Only allow the function to process at most one kilobyte of input
|
|
|
|
/// {
|
|
|
|
/// let stream = LimitReader::new(stream.by_ref(), 1024);
|
|
|
|
/// process_input(stream);
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// // 'stream' is still available for use here
|
|
|
|
///
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2014-02-13 22:27:53 -06:00
|
|
|
pub struct RefReader<'a, R> {
|
2014-02-24 02:31:08 -06:00
|
|
|
/// The underlying reader which this is referencing
|
|
|
|
inner: &'a mut R
|
2014-02-13 22:27:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, R: Reader> Reader for RefReader<'a, R> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
|
|
|
|
}
|
|
|
|
|
2014-05-06 01:50:07 -05:00
|
|
|
impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
|
|
|
|
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { self.inner.fill_buf() }
|
|
|
|
fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
|
|
|
|
}
|
|
|
|
|
2013-10-25 20:08:45 -05:00
|
|
|
fn extend_sign(val: u64, nbytes: uint) -> i64 {
|
|
|
|
let shift = (8 - nbytes) * 8;
|
|
|
|
(val << shift) as i64 >> shift
|
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A trait for objects which are byte-oriented streams. Writers are defined by
|
|
|
|
/// one method, `write`. This function will block until the provided buffer of
|
2014-05-22 07:50:31 -05:00
|
|
|
/// bytes has been entirely written, and it will return any failures which occur.
|
2014-02-24 02:31:08 -06:00
|
|
|
///
|
2014-05-22 07:50:31 -05:00
|
|
|
/// Another commonly overridden method is the `flush` method for writers such as
|
2014-02-24 02:31:08 -06:00
|
|
|
/// buffered writers.
|
|
|
|
///
|
|
|
|
/// Writers are intended to be composable with one another. Many objects
|
|
|
|
/// throughout the I/O and related libraries take and provide types which
|
|
|
|
/// implement the `Writer` trait.
|
2013-04-17 19:55:21 -05:00
|
|
|
pub trait Writer {
|
2014-01-30 18:55:20 -06:00
|
|
|
/// Write the entirety of a given buffer
|
2013-03-13 22:02:48 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Errors
|
2013-03-13 22:02:48 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write(&mut self, buf: &[u8]) -> IoResult<()>;
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-10-30 17:10:32 -05:00
|
|
|
/// Flush this output stream, ensuring that all intermediately buffered
|
|
|
|
/// contents reach their destination.
|
|
|
|
///
|
2013-12-14 23:26:09 -06:00
|
|
|
/// This is by default a no-op and implementers of the `Writer` trait should
|
2013-10-30 17:10:32 -05:00
|
|
|
/// decide whether their stream needs to be buffered or not.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn flush(&mut self) -> IoResult<()> { Ok(()) }
|
2013-10-25 20:08:45 -05:00
|
|
|
|
2014-05-10 15:52:26 -05:00
|
|
|
/// Writes a formatted string into this writer, returning any error
|
|
|
|
/// encountered.
|
|
|
|
///
|
|
|
|
/// This method is primarily used to interface with the `format_args!`
|
|
|
|
/// macro, but it is rare that this should explicitly be called. The
|
|
|
|
/// `write!` macro should be favored to invoke this method instead.
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// This function will return any I/O error reported while formatting.
|
|
|
|
fn write_fmt(&mut self, fmt: &fmt::Arguments) -> IoResult<()> {
|
|
|
|
// Create a shim which translates a Writer to a FormatWriter and saves
|
|
|
|
// off I/O errors. instead of discarding them
|
|
|
|
struct Adaptor<'a, T> {
|
|
|
|
inner: &'a mut T,
|
|
|
|
error: IoResult<()>,
|
|
|
|
}
|
|
|
|
impl<'a, T: Writer> fmt::FormatWriter for Adaptor<'a, T> {
|
|
|
|
fn write(&mut self, bytes: &[u8]) -> fmt::Result {
|
|
|
|
match self.inner.write(bytes) {
|
|
|
|
Ok(()) => Ok(()),
|
|
|
|
Err(e) => {
|
|
|
|
self.error = Err(e);
|
|
|
|
Err(fmt::WriteError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut output = Adaptor { inner: self, error: Ok(()) };
|
|
|
|
match fmt::write(&mut output, fmt) {
|
|
|
|
Ok(()) => Ok(()),
|
|
|
|
Err(..) => output.error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-08 13:12:25 -06:00
|
|
|
/// 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.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_str(&mut self, s: &str) -> IoResult<()> {
|
|
|
|
self.write(s.as_bytes())
|
2013-12-08 13:12:25 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_line(&mut self, s: &str) -> IoResult<()> {
|
|
|
|
self.write_str(s).and_then(|()| self.write(['\n' as u8]))
|
2013-12-08 13:12:25 -06:00
|
|
|
}
|
|
|
|
|
2014-01-04 07:26:03 -06:00
|
|
|
/// Write a single char, encoded as UTF-8.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_char(&mut self, c: char) -> IoResult<()> {
|
2014-01-04 07:26:03 -06:00
|
|
|
let mut buf = [0u8, ..4];
|
|
|
|
let n = c.encode_utf8(buf.as_mut_slice());
|
2014-01-29 18:33:57 -06:00
|
|
|
self.write(buf.slice_to(n))
|
2014-01-04 07:26:03 -06:00
|
|
|
}
|
|
|
|
|
2013-10-25 20:08:45 -05:00
|
|
|
/// Write the result of passing n through `int::to_str_bytes`.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_int(&mut self, n: int) -> IoResult<()> {
|
2014-02-21 10:53:18 -06:00
|
|
|
write!(self, "{:d}", n)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write the result of passing n through `uint::to_str_bytes`.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_uint(&mut self, n: uint) -> IoResult<()> {
|
2014-02-21 10:53:18 -06:00
|
|
|
write!(self, "{:u}", n)
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian uint (number of bytes depends on system).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
|
2014-01-25 01:37:51 -06:00
|
|
|
extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian int (number of bytes depends on system).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_int(&mut self, n: int) -> IoResult<()> {
|
2014-01-25 01:37:51 -06:00
|
|
|
extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian uint (number of bytes depends on system).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
|
2014-01-25 01:37:51 -06:00
|
|
|
extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian int (number of bytes depends on system).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_int(&mut self, n: int) -> IoResult<()> {
|
2014-01-25 01:37:51 -06:00
|
|
|
extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian u64 (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian u32 (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian u16 (2 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian i64 (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian i32 (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian i16 (2 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
self.write_be_u64(transmute(f))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
self.write_be_u32(transmute(f))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian u64 (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian u32 (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian u16 (2 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian i64 (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian i32 (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian i16 (2 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian IEEE754 double-precision floating-point
|
|
|
|
/// (8 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
self.write_le_u64(transmute(f))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a little-endian IEEE754 single-precision floating-point
|
|
|
|
/// (4 bytes).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
unsafe {
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
self.write_le_u32(transmute(f))
|
2013-10-25 20:08:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Write a u8 (1 byte).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_u8(&mut self, n: u8) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
self.write([n])
|
|
|
|
}
|
|
|
|
|
2014-05-01 20:02:11 -05:00
|
|
|
/// Write an i8 (1 byte).
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write_i8(&mut self, n: i8) -> IoResult<()> {
|
2013-10-25 20:08:45 -05:00
|
|
|
self.write([n as u8])
|
|
|
|
}
|
2014-02-13 22:27:53 -06:00
|
|
|
|
|
|
|
/// Creates a wrapper around a mutable reference to the writer.
|
|
|
|
///
|
|
|
|
/// This is useful to allow applying wrappers while still
|
|
|
|
/// retaining ownership of the original value.
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-02-13 22:27:53 -06:00
|
|
|
fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self> {
|
|
|
|
RefWriter { inner: self }
|
|
|
|
}
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
|
|
|
|
2014-05-05 20:56:44 -05:00
|
|
|
impl Writer for Box<Writer> {
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
|
2014-06-20 22:05:42 -05:00
|
|
|
|
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn flush(&mut self) -> IoResult<()> { self.flush() }
|
2013-10-06 18:08:56 -05:00
|
|
|
}
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
impl<'a> Writer for &'a mut Writer {
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) }
|
2014-06-20 22:05:42 -05:00
|
|
|
|
|
|
|
#[inline]
|
2014-01-29 18:33:57 -06:00
|
|
|
fn flush(&mut self) -> IoResult<()> { self.flush() }
|
2013-10-06 18:08:56 -05:00
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A `RefWriter` is a struct implementing `Writer` which contains a reference
|
|
|
|
/// to another writer. This is often useful when composing streams.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # fn main() {}
|
|
|
|
/// # fn process_input<R: Reader>(r: R) {}
|
|
|
|
/// # fn foo () {
|
|
|
|
/// use std::io::util::TeeReader;
|
|
|
|
/// use std::io::{stdin, MemWriter};
|
|
|
|
///
|
|
|
|
/// let mut output = MemWriter::new();
|
|
|
|
///
|
|
|
|
/// {
|
|
|
|
/// // Don't give ownership of 'output' to the 'tee'. Instead we keep a
|
|
|
|
/// // handle to it in the outer scope
|
|
|
|
/// let mut tee = TeeReader::new(stdin(), output.by_ref());
|
|
|
|
/// process_input(tee);
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// println!("input processed: {}", output.unwrap());
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2014-02-13 22:27:53 -06:00
|
|
|
pub struct RefWriter<'a, W> {
|
2014-02-24 02:31:08 -06:00
|
|
|
/// The underlying writer which this is referencing
|
2014-02-13 22:27:53 -06:00
|
|
|
inner: &'a mut W
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, W: Writer> Writer for RefWriter<'a, W> {
|
2014-06-20 22:05:42 -05:00
|
|
|
#[inline]
|
2014-02-13 22:27:53 -06:00
|
|
|
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
|
2014-06-20 22:05:42 -05:00
|
|
|
|
|
|
|
#[inline]
|
2014-02-13 22:27:53 -06:00
|
|
|
fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A Stream is a readable and a writable object. Data written is typically
|
|
|
|
/// received by the object which reads receive data from.
|
2013-04-24 20:26:49 -05:00
|
|
|
pub trait Stream: Reader + Writer { }
|
2013-04-17 19:55:21 -05:00
|
|
|
|
2013-09-19 14:09:52 -05:00
|
|
|
impl<T: Reader + Writer> Stream for T {}
|
2013-09-04 19:52:18 -05:00
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
/// An iterator that reads a line on each iteration,
|
2014-02-19 20:53:46 -06:00
|
|
|
/// until `.read_line()` encounters `EndOfFile`.
|
2013-12-08 01:12:07 -06:00
|
|
|
///
|
|
|
|
/// # Notes about the Iteration Protocol
|
|
|
|
///
|
2014-01-14 21:32:24 -06:00
|
|
|
/// The `Lines` may yield `None` and thus terminate
|
2013-12-08 01:12:07 -06:00
|
|
|
/// an iteration, but continue to yield elements if iteration
|
|
|
|
/// is attempted again.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-12-08 01:12:07 -06:00
|
|
|
///
|
2014-02-19 20:53:46 -06:00
|
|
|
/// Any error other than `EndOfFile` that is produced by the underlying Reader
|
|
|
|
/// is returned by the iterator and should be handled by the caller.
|
2014-01-14 21:32:24 -06:00
|
|
|
pub struct Lines<'r, T> {
|
2014-03-27 17:09:47 -05:00
|
|
|
buffer: &'r mut T,
|
2013-12-08 01:12:07 -06:00
|
|
|
}
|
|
|
|
|
2014-05-22 18:57:53 -05:00
|
|
|
impl<'r, T: Buffer> Iterator<IoResult<String>> for Lines<'r, T> {
|
|
|
|
fn next(&mut self) -> Option<IoResult<String>> {
|
2014-02-19 20:53:46 -06:00
|
|
|
match self.buffer.read_line() {
|
|
|
|
Ok(x) => Some(Ok(x)),
|
|
|
|
Err(IoError { kind: EndOfFile, ..}) => None,
|
|
|
|
Err(y) => Some(Err(y))
|
|
|
|
}
|
2013-12-08 01:12:07 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-08 23:40:38 -06:00
|
|
|
/// An iterator that reads a utf8-encoded character on each iteration,
|
2014-02-19 20:53:46 -06:00
|
|
|
/// until `.read_char()` encounters `EndOfFile`.
|
2014-02-08 23:40:38 -06:00
|
|
|
///
|
|
|
|
/// # Notes about the Iteration Protocol
|
|
|
|
///
|
|
|
|
/// The `Chars` may yield `None` and thus terminate
|
|
|
|
/// an iteration, but continue to yield elements if iteration
|
|
|
|
/// is attempted again.
|
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
2014-02-19 20:53:46 -06:00
|
|
|
/// Any error other than `EndOfFile` that is produced by the underlying Reader
|
|
|
|
/// is returned by the iterator and should be handled by the caller.
|
2014-02-08 23:40:38 -06:00
|
|
|
pub struct Chars<'r, T> {
|
2014-03-27 17:09:47 -05:00
|
|
|
buffer: &'r mut T
|
2014-02-08 23:40:38 -06:00
|
|
|
}
|
|
|
|
|
2014-02-19 20:53:46 -06:00
|
|
|
impl<'r, T: Buffer> Iterator<IoResult<char>> for Chars<'r, T> {
|
|
|
|
fn next(&mut self) -> Option<IoResult<char>> {
|
|
|
|
match self.buffer.read_char() {
|
|
|
|
Ok(x) => Some(Ok(x)),
|
|
|
|
Err(IoError { kind: EndOfFile, ..}) => None,
|
|
|
|
Err(y) => Some(Err(y))
|
|
|
|
}
|
2014-02-08 23:40:38 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-11-13 13:17:58 -06:00
|
|
|
/// 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.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-11-13 13:17:58 -06:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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.
|
2014-03-20 20:52:00 -05:00
|
|
|
fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
|
2013-11-13 13:17:58 -06:00
|
|
|
|
|
|
|
/// Tells this buffer that `amt` bytes have been consumed from the buffer,
|
2014-03-25 01:22:23 -05:00
|
|
|
/// so they should no longer be returned in calls to `read`.
|
2013-11-13 13:17:58 -06:00
|
|
|
fn consume(&mut self, amt: uint);
|
|
|
|
|
2013-12-08 13:12:25 -06:00
|
|
|
/// Reads the next line of input, interpreted as a sequence of UTF-8
|
2013-11-13 13:17:58 -06:00
|
|
|
/// encoded unicode codepoints. If a newline is encountered, then the
|
|
|
|
/// newline is contained in the returned string.
|
|
|
|
///
|
2014-01-02 06:35:08 -06:00
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2014-02-20 11:11:56 -06:00
|
|
|
/// use std::io;
|
2014-01-02 06:35:08 -06:00
|
|
|
///
|
2014-02-20 11:11:56 -06:00
|
|
|
/// let mut reader = io::stdin();
|
2014-05-25 05:10:11 -05:00
|
|
|
/// let input = reader.read_line().ok().unwrap_or("nothing".to_string());
|
2014-01-02 06:35:08 -06:00
|
|
|
/// ```
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # 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
|
2013-11-13 13:17:58 -06:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// Additionally, this function can fail if the line of input read is not a
|
|
|
|
/// valid UTF-8 sequence of bytes.
|
2014-05-22 18:57:53 -05:00
|
|
|
fn read_line(&mut self) -> IoResult<String> {
|
2014-01-30 18:55:20 -06:00
|
|
|
self.read_until('\n' as u8).and_then(|line|
|
2014-03-26 11:24:16 -05:00
|
|
|
match str::from_utf8(line.as_slice()) {
|
2014-06-21 05:39:03 -05:00
|
|
|
Some(s) => Ok(String::from_str(s)),
|
2014-01-30 18:55:20 -06:00
|
|
|
None => Err(standard_error(InvalidInput)),
|
|
|
|
}
|
|
|
|
)
|
2013-11-13 13:17:58 -06:00
|
|
|
}
|
|
|
|
|
2013-12-08 01:12:07 -06:00
|
|
|
/// Create an iterator that reads a line on each iteration until EOF.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-12-08 01:12:07 -06:00
|
|
|
///
|
2014-02-19 20:53:46 -06:00
|
|
|
/// Any error other than `EndOfFile` that is produced by the underlying Reader
|
|
|
|
/// is returned by the iterator and should be handled by the caller.
|
2014-01-14 21:32:24 -06:00
|
|
|
fn lines<'r>(&'r mut self) -> Lines<'r, Self> {
|
2014-01-30 18:55:20 -06:00
|
|
|
Lines { buffer: self }
|
2013-12-08 01:12:07 -06:00
|
|
|
}
|
|
|
|
|
2013-12-14 23:26:09 -06:00
|
|
|
/// Reads a sequence of bytes leading up to a specified delimiter. Once the
|
2013-11-13 13:17:58 -06:00
|
|
|
/// specified byte is encountered, reading ceases and the bytes up to and
|
|
|
|
/// including the delimiter are returned.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-11-13 13:17:58 -06:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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.
|
2014-03-26 11:24:16 -05:00
|
|
|
fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
|
|
|
|
let mut res = Vec::new();
|
2013-12-08 01:12:07 -06:00
|
|
|
|
2014-01-29 18:33:57 -06:00
|
|
|
let mut used;
|
|
|
|
loop {
|
|
|
|
{
|
2014-03-20 20:52:00 -05:00
|
|
|
let available = match self.fill_buf() {
|
2014-01-30 18:55:20 -06:00
|
|
|
Ok(n) => n,
|
|
|
|
Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
|
|
|
|
used = 0;
|
|
|
|
break
|
|
|
|
}
|
|
|
|
Err(e) => return Err(e)
|
|
|
|
};
|
2014-01-29 18:33:57 -06:00
|
|
|
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();
|
2013-11-13 13:17:58 -06:00
|
|
|
}
|
|
|
|
}
|
2014-01-29 18:33:57 -06:00
|
|
|
}
|
2013-11-13 13:17:58 -06:00
|
|
|
self.consume(used);
|
2014-01-29 18:33:57 -06:00
|
|
|
}
|
|
|
|
self.consume(used);
|
|
|
|
Ok(res)
|
2013-11-13 13:17:58 -06:00
|
|
|
}
|
2013-11-13 13:36:21 -06:00
|
|
|
|
|
|
|
/// Reads the next utf8-encoded character from the underlying stream.
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-11-13 13:36:21 -06:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// 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.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn read_char(&mut self) -> IoResult<char> {
|
2014-02-19 12:07:49 -06:00
|
|
|
let first_byte = try!(self.read_byte());
|
2014-01-30 16:10:53 -06:00
|
|
|
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];
|
2014-01-07 10:48:44 -06:00
|
|
|
{
|
2014-01-30 16:10:53 -06:00
|
|
|
let mut start = 1;
|
|
|
|
while start < width {
|
2014-02-19 12:07:49 -06:00
|
|
|
match try!(self.read(buf.mut_slice(start, width))) {
|
2014-01-29 18:33:57 -06:00
|
|
|
n if n == width - start => break,
|
|
|
|
n if n < width - start => { start += n; }
|
|
|
|
_ => return Err(standard_error(InvalidInput)),
|
2014-01-07 10:48:44 -06:00
|
|
|
}
|
|
|
|
}
|
2013-11-13 13:36:21 -06:00
|
|
|
}
|
2013-12-23 10:30:49 -06:00
|
|
|
match str::from_utf8(buf.slice_to(width)) {
|
2014-01-29 18:33:57 -06:00
|
|
|
Some(s) => Ok(s.char_at(0)),
|
|
|
|
None => Err(standard_error(InvalidInput))
|
2013-11-13 13:36:21 -06:00
|
|
|
}
|
|
|
|
}
|
2014-02-08 23:40:38 -06:00
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Create an iterator that reads a utf8-encoded character on each iteration
|
|
|
|
/// until EOF.
|
2014-02-08 23:40:38 -06:00
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
2014-02-19 20:53:46 -06:00
|
|
|
/// Any error other than `EndOfFile` that is produced by the underlying Reader
|
|
|
|
/// is returned by the iterator and should be handled by the caller.
|
2014-02-08 23:40:38 -06:00
|
|
|
fn chars<'r>(&'r mut self) -> Chars<'r, Self> {
|
|
|
|
Chars { buffer: self }
|
|
|
|
}
|
2013-11-13 13:17:58 -06:00
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// When seeking, the resulting cursor is offset from a base by the offset given
|
|
|
|
/// to the `seek` function. The base used is specified by this enumeration.
|
2013-04-17 19:55:21 -05:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// An object implementing `Seek` internally has some form of cursor which can
|
|
|
|
/// be moved within a stream of bytes. The stream typically has a fixed size,
|
|
|
|
/// allowing seeking relative to either end.
|
2013-04-19 16:58:21 -05:00
|
|
|
pub trait Seek {
|
2013-08-20 17:38:41 -05:00
|
|
|
/// Return position of file cursor in the stream
|
2014-01-29 18:33:57 -06:00
|
|
|
fn tell(&self) -> IoResult<u64>;
|
2013-04-20 19:25:00 -05:00
|
|
|
|
|
|
|
/// Seek to an offset in a stream
|
|
|
|
///
|
2014-02-11 22:13:46 -06:00
|
|
|
/// A successful seek clears the EOF indicator. Seeking beyond EOF is
|
|
|
|
/// allowed, but seeking before position 0 is not allowed.
|
2013-04-20 19:25:00 -05:00
|
|
|
///
|
2014-02-11 22:13:46 -06:00
|
|
|
/// # Errors
|
2013-04-20 19:25:00 -05:00
|
|
|
///
|
2014-02-11 22:13:46 -06:00
|
|
|
/// * Seeking to a negative offset is considered an error
|
|
|
|
/// * Seeking past the end of the stream does not modify the underlying
|
|
|
|
/// stream, but the next write may cause the previous data to be filled in
|
|
|
|
/// with a bit pattern.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
|
2013-04-17 19:55:21 -05:00
|
|
|
}
|
|
|
|
|
2014-01-30 18:55:20 -06:00
|
|
|
/// A listener is a value that can consume itself to start listening for
|
|
|
|
/// connections.
|
|
|
|
///
|
2013-08-27 12:01:17 -05:00
|
|
|
/// Doing so produces some sort of Acceptor.
|
|
|
|
pub trait Listener<T, A: Acceptor<T>> {
|
2013-12-14 23:26:09 -06:00
|
|
|
/// Spin up the listener and start queuing incoming connections
|
2013-04-22 15:26:37 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
2013-04-22 15:26:37 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// Returns `Err` if this listener could not be bound to listen for
|
|
|
|
/// connections. In all cases, this listener is consumed.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn listen(self) -> IoResult<A>;
|
2013-08-27 12:01:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// An acceptor is a value that presents incoming connections
|
|
|
|
pub trait Acceptor<T> {
|
|
|
|
/// Wait for and accept an incoming connection
|
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// # Error
|
|
|
|
///
|
|
|
|
/// Returns `Err` if an I/O error is encountered.
|
2014-01-29 18:33:57 -06:00
|
|
|
fn accept(&mut self) -> IoResult<T>;
|
2013-08-27 12:01:17 -05:00
|
|
|
|
2014-01-30 18:55:20 -06:00
|
|
|
/// Create an iterator over incoming connection attempts.
|
|
|
|
///
|
|
|
|
/// Note that I/O errors will be yielded by the iterator itself.
|
2014-01-14 21:32:24 -06:00
|
|
|
fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
|
|
|
|
IncomingConnections { inc: self }
|
2013-08-27 12:01:17 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// An infinite iterator over incoming connection attempts.
|
|
|
|
/// Calling `next` will block the task until a connection is attempted.
|
2013-09-05 18:49:38 -05:00
|
|
|
///
|
2014-01-30 18:55:20 -06:00
|
|
|
/// Since connection attempts can continue forever, this iterator always returns
|
|
|
|
/// `Some`. The `Some` contains the `IoResult` representing whether the
|
2014-02-17 05:53:45 -06:00
|
|
|
/// connection attempt was successful. A successful connection will be wrapped
|
2014-01-30 18:55:20 -06:00
|
|
|
/// in `Ok`. A failed connection is represented as an `Err`.
|
2014-01-25 20:25:02 -06:00
|
|
|
pub struct IncomingConnections<'a, A> {
|
2014-03-27 17:09:47 -05:00
|
|
|
inc: &'a mut A,
|
2013-08-27 12:01:17 -05:00
|
|
|
}
|
|
|
|
|
2014-01-29 18:33:57 -06:00
|
|
|
impl<'a, T, A: Acceptor<T>> Iterator<IoResult<T>> for IncomingConnections<'a, A> {
|
|
|
|
fn next(&mut self) -> Option<IoResult<T>> {
|
2013-09-05 18:49:38 -05:00
|
|
|
Some(self.inc.accept())
|
2013-08-27 12:01:17 -05:00
|
|
|
}
|
2013-04-22 15:26:37 -05:00
|
|
|
}
|
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Creates a standard error for a commonly used flavor of error. The `detail`
|
|
|
|
/// field of the returned error will always be `None`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::io;
|
|
|
|
///
|
|
|
|
/// let eof = io::standard_error(io::EndOfFile);
|
|
|
|
/// let einval = io::standard_error(io::InvalidInput);
|
|
|
|
/// ```
|
2013-04-22 16:52:40 -05:00
|
|
|
pub fn standard_error(kind: IoErrorKind) -> IoError {
|
2013-12-08 13:12:25 -06:00
|
|
|
let desc = match kind {
|
|
|
|
EndOfFile => "end of file",
|
|
|
|
IoUnavailable => "I/O is unavailable",
|
|
|
|
InvalidInput => "invalid input",
|
2014-04-27 07:45:28 -05:00
|
|
|
OtherIoError => "unknown I/O error",
|
|
|
|
FileNotFound => "file not found",
|
|
|
|
PermissionDenied => "permission denied",
|
|
|
|
ConnectionFailed => "connection failed",
|
|
|
|
Closed => "stream is closed",
|
|
|
|
ConnectionRefused => "connection refused",
|
|
|
|
ConnectionReset => "connection reset",
|
|
|
|
ConnectionAborted => "connection aborted",
|
|
|
|
NotConnected => "not connected",
|
|
|
|
BrokenPipe => "broken pipe",
|
2014-06-03 14:33:18 -05:00
|
|
|
PathAlreadyExists => "file already exists",
|
2014-04-27 07:45:28 -05:00
|
|
|
PathDoesntExist => "no such file",
|
|
|
|
MismatchedFileTypeForOperation => "mismatched file type",
|
|
|
|
ResourceUnavailable => "resource unavailable",
|
2014-04-25 22:47:49 -05:00
|
|
|
TimedOut => "operation timed out",
|
|
|
|
ShortWrite(..) => "short write",
|
2014-03-25 01:22:23 -05:00
|
|
|
NoProgress => "no progress",
|
2013-12-08 13:12:25 -06:00
|
|
|
};
|
|
|
|
IoError {
|
|
|
|
kind: kind,
|
|
|
|
desc: desc,
|
|
|
|
detail: None,
|
2013-04-22 16:52:40 -05:00
|
|
|
}
|
|
|
|
}
|
2013-05-09 19:37:31 -05:00
|
|
|
|
2013-10-30 01:31:07 -05:00
|
|
|
/// 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.
|
2013-08-22 18:31:23 -05:00
|
|
|
pub enum FileMode {
|
2013-10-30 01:31:07 -05:00
|
|
|
/// Opens a file positioned at the beginning.
|
2013-08-22 18:31:23 -05:00
|
|
|
Open,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// Opens a file positioned at EOF.
|
2013-08-22 18:31:23 -05:00
|
|
|
Append,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// Opens a file, truncating it if it already exists.
|
2013-08-22 18:31:23 -05:00
|
|
|
Truncate,
|
|
|
|
}
|
|
|
|
|
2013-10-30 01:31:07 -05:00
|
|
|
/// Access permissions with which the file should be opened. `File`s
|
2014-01-30 18:55:20 -06:00
|
|
|
/// opened with `Read` will return an error if written to.
|
2013-08-22 18:31:23 -05:00
|
|
|
pub enum FileAccess {
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Read-only access, requests to write will result in an error
|
2013-08-22 18:31:23 -05:00
|
|
|
Read,
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Write-only access, requests to read will result in an error
|
2013-08-22 18:31:23 -05:00
|
|
|
Write,
|
2014-02-24 02:31:08 -06:00
|
|
|
/// Read-write access, no requests are denied by default
|
2013-10-30 01:31:07 -05:00
|
|
|
ReadWrite,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Different kinds of files which can be identified by a call to stat
|
2014-05-29 19:45:07 -05:00
|
|
|
#[deriving(PartialEq, Show, Hash)]
|
2013-10-30 01:31:07 -05:00
|
|
|
pub enum FileType {
|
2014-02-24 02:31:08 -06:00
|
|
|
/// This is a normal file, corresponding to `S_IFREG`
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeFile,
|
2014-02-24 02:31:08 -06:00
|
|
|
|
|
|
|
/// This file is a directory, corresponding to `S_IFDIR`
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeDirectory,
|
2014-02-24 02:31:08 -06:00
|
|
|
|
|
|
|
/// This file is a named pipe, corresponding to `S_IFIFO`
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeNamedPipe,
|
2014-02-24 02:31:08 -06:00
|
|
|
|
|
|
|
/// This file is a block device, corresponding to `S_IFBLK`
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeBlockSpecial,
|
2014-02-24 02:31:08 -06:00
|
|
|
|
|
|
|
/// This file is a symbolic link to another file, corresponding to `S_IFLNK`
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeSymlink,
|
2014-02-24 02:31:08 -06:00
|
|
|
|
|
|
|
/// The type of this file is not recognized as one of the other categories
|
2013-10-30 01:31:07 -05:00
|
|
|
TypeUnknown,
|
2013-08-22 18:31:23 -05:00
|
|
|
}
|
2013-08-26 09:24:10 -05:00
|
|
|
|
2014-02-24 02:31:08 -06:00
|
|
|
/// A structure used to describe metadata information about a file. This
|
|
|
|
/// structure is created through the `stat` method on a `Path`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # fn main() {}
|
|
|
|
/// # fn foo() {
|
|
|
|
/// let info = match Path::new("foo.txt").stat() {
|
|
|
|
/// Ok(stat) => stat,
|
|
|
|
/// Err(e) => fail!("couldn't read foo.txt: {}", e),
|
|
|
|
/// };
|
|
|
|
///
|
|
|
|
/// println!("byte size: {}", info.size);
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2014-03-10 22:47:25 -05:00
|
|
|
#[deriving(Hash)]
|
2013-08-26 09:24:10 -05:00
|
|
|
pub struct FileStat {
|
2013-10-30 01:31:07 -05:00
|
|
|
/// The size of the file, in bytes
|
2014-03-27 17:09:47 -05:00
|
|
|
pub size: u64,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// The kind of file this path points to (directory, file, pipe, etc.)
|
2014-03-27 17:09:47 -05:00
|
|
|
pub kind: FileType,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// The file permissions currently on the file
|
2014-03-27 17:09:47 -05:00
|
|
|
pub perm: FilePermission,
|
2013-10-30 01:31:07 -05:00
|
|
|
|
2013-11-05 17:48:27 -06:00
|
|
|
// FIXME(#10301): These time fields are pretty useless without an actual
|
|
|
|
// time representation, what are the milliseconds relative
|
|
|
|
// to?
|
2013-10-30 01:31:07 -05:00
|
|
|
|
|
|
|
/// The time that the file was created at, in platform-dependent
|
|
|
|
/// milliseconds
|
2014-03-27 17:09:47 -05:00
|
|
|
pub created: u64,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// The time that this file was last modified, in platform-dependent
|
|
|
|
/// milliseconds
|
2014-03-27 17:09:47 -05:00
|
|
|
pub modified: u64,
|
2013-10-30 01:31:07 -05:00
|
|
|
/// The time that this file was last accessed, in platform-dependent
|
|
|
|
/// milliseconds
|
2014-03-27 17:09:47 -05:00
|
|
|
pub accessed: u64,
|
2013-10-30 01:31:07 -05:00
|
|
|
|
2013-10-31 17:15:30 -05:00
|
|
|
/// 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]
|
2014-03-27 17:09:47 -05:00
|
|
|
pub unstable: UnstableFileStat,
|
2013-10-31 17:15:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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]
|
2014-03-10 22:47:25 -05:00
|
|
|
#[deriving(Hash)]
|
2013-10-31 17:15:30 -05:00
|
|
|
pub struct UnstableFileStat {
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The ID of the device containing the file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub device: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The file serial number.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub inode: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The device ID.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub rdev: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The number of hard links to this file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub nlink: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The user ID of the file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub uid: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The group ID of the file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub gid: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The optimal block size for I/O.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub blksize: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The blocks allocated for this file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub blocks: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// User-defined flags for the file.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub flags: u64,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The file generation number.
|
2014-03-27 17:09:47 -05:00
|
|
|
pub gen: u64,
|
2013-08-26 09:24:10 -05:00
|
|
|
}
|
2013-10-25 19:04:37 -05:00
|
|
|
|
2014-05-02 12:56:26 -05:00
|
|
|
bitflags!(
|
|
|
|
#[doc="A set of permissions for a file or directory is represented
|
|
|
|
by a set of flags which are or'd together."]
|
|
|
|
#[deriving(Hash)]
|
|
|
|
#[deriving(Show)]
|
|
|
|
flags FilePermission: u32 {
|
|
|
|
static UserRead = 0o400,
|
|
|
|
static UserWrite = 0o200,
|
|
|
|
static UserExecute = 0o100,
|
|
|
|
static GroupRead = 0o040,
|
|
|
|
static GroupWrite = 0o020,
|
|
|
|
static GroupExecute = 0o010,
|
|
|
|
static OtherRead = 0o004,
|
|
|
|
static OtherWrite = 0o002,
|
|
|
|
static OtherExecute = 0o001,
|
|
|
|
|
|
|
|
static UserRWX = UserRead.bits | UserWrite.bits | UserExecute.bits,
|
|
|
|
static GroupRWX = GroupRead.bits | GroupWrite.bits | GroupExecute.bits,
|
|
|
|
static OtherRWX = OtherRead.bits | OtherWrite.bits | OtherExecute.bits,
|
|
|
|
|
|
|
|
#[doc="Permissions for user owned files, equivalent to 0644 on
|
|
|
|
unix-like systems."]
|
|
|
|
static UserFile = UserRead.bits | UserWrite.bits | GroupRead.bits | OtherRead.bits,
|
|
|
|
|
|
|
|
#[doc="Permissions for user owned directories, equivalent to 0755 on
|
|
|
|
unix-like systems."]
|
|
|
|
static UserDir = UserRWX.bits | GroupRead.bits | GroupExecute.bits |
|
|
|
|
OtherRead.bits | OtherExecute.bits,
|
|
|
|
|
|
|
|
#[doc="Permissions for user owned executables, equivalent to 0755
|
|
|
|
on unix-like systems."]
|
|
|
|
static UserExec = UserDir.bits,
|
|
|
|
|
|
|
|
#[doc="All possible permissions enabled."]
|
|
|
|
static AllPermissions = UserRWX.bits | GroupRWX.bits | OtherRWX.bits
|
|
|
|
}
|
|
|
|
)
|
2014-03-25 01:22:23 -05:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput};
|
|
|
|
use prelude::*;
|
|
|
|
use uint;
|
|
|
|
|
2014-05-29 19:45:07 -05:00
|
|
|
#[deriving(Clone, PartialEq, Show)]
|
2014-03-25 01:22:23 -05:00
|
|
|
enum BadReaderBehavior {
|
|
|
|
GoodBehavior(uint),
|
|
|
|
BadBehavior(uint)
|
|
|
|
}
|
|
|
|
|
|
|
|
struct BadReader<T> {
|
|
|
|
r: T,
|
|
|
|
behavior: Vec<BadReaderBehavior>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Reader> BadReader<T> {
|
|
|
|
fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
|
|
|
|
BadReader { behavior: behavior, r: r }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Reader> Reader for BadReader<T> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
|
|
|
|
let BadReader { ref mut behavior, ref mut r } = *self;
|
|
|
|
loop {
|
|
|
|
if behavior.is_empty() {
|
|
|
|
// fall back on good
|
|
|
|
return r.read(buf);
|
|
|
|
}
|
|
|
|
match behavior.as_mut_slice()[0] {
|
|
|
|
GoodBehavior(0) => (),
|
|
|
|
GoodBehavior(ref mut x) => {
|
|
|
|
*x -= 1;
|
|
|
|
return r.read(buf);
|
|
|
|
}
|
|
|
|
BadBehavior(0) => (),
|
|
|
|
BadBehavior(ref mut x) => {
|
|
|
|
*x -= 1;
|
|
|
|
return Ok(0);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
behavior.shift();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_read_at_least() {
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([GoodBehavior(uint::MAX)]));
|
|
|
|
let mut buf = [0u8, ..5];
|
|
|
|
assert!(r.read_at_least(1, buf).unwrap() >= 1);
|
|
|
|
assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
|
|
|
|
assert!(r.read_at_least(0, buf).is_ok());
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
|
|
|
|
assert!(r.read_at_least(1, buf).unwrap() >= 1);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(1), GoodBehavior(1),
|
|
|
|
BadBehavior(50), GoodBehavior(uint::MAX)]));
|
|
|
|
assert!(r.read_at_least(1, buf).unwrap() >= 1);
|
|
|
|
assert!(r.read_at_least(1, buf).unwrap() >= 1);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(uint::MAX)]));
|
|
|
|
assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
|
2014-03-25 01:22:23 -05:00
|
|
|
assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
|
|
|
|
assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_push_at_least() {
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([GoodBehavior(uint::MAX)]));
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
|
|
|
|
assert!(r.push_at_least(0, 5, &mut buf).is_ok());
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
|
|
|
|
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(1), GoodBehavior(1),
|
|
|
|
BadBehavior(50), GoodBehavior(uint::MAX)]));
|
|
|
|
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
|
|
|
|
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
|
2014-03-25 01:22:23 -05:00
|
|
|
Vec::from_slice([BadBehavior(uint::MAX)]));
|
|
|
|
assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
|
|
|
|
|
2014-06-18 13:25:36 -05:00
|
|
|
let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
|
2014-03-25 01:22:23 -05:00
|
|
|
assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
|
|
|
|
}
|
|
|
|
}
|