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