1 // Copyright 2015 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.
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.
11 //! Traits, helpers, and type definitions for core I/O functionality.
13 #![stable(feature = "rust1", since = "1.0.0")]
16 use rustc_unicode
::str as core_str
;
17 use error
as std_error
;
19 use iter
::{self, Iterator, Extend}
;
21 use ops
::{Drop, FnOnce}
;
22 use option
::Option
::{self, Some, None}
;
23 use result
::Result
::{Ok, Err}
;
29 pub use self::buffered
::{BufReader, BufWriter, BufStream, LineWriter}
;
30 pub use self::buffered
::IntoInnerError
;
31 pub use self::cursor
::Cursor
;
32 pub use self::error
::{Result, Error, ErrorKind}
;
33 pub use self::util
::{copy, sink, Sink, empty, Empty, repeat, Repeat}
;
34 pub use self::stdio
::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr}
;
35 pub use self::stdio
::{StdoutLock, StderrLock, StdinLock}
;
36 #[doc(no_inline, hidden)]
37 pub use self::stdio
::{set_panic, set_print}
;
39 #[macro_use] mod lazy;
49 const DEFAULT_BUF_SIZE
: usize = 64 * 1024;
51 // A few methods below (read_to_string, read_line) will append data into a
52 // `String` buffer, but we need to be pretty careful when doing this. The
53 // implementation will just call `.as_mut_vec()` and then delegate to a
54 // byte-oriented reading method, but we must ensure that when returning we never
55 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
57 // To this end, we use an RAII guard (to protect against panics) which updates
58 // the length of the string when it is dropped. This guard initially truncates
59 // the string to the prior length and only after we've validated that the
60 // new contents are valid UTF-8 do we allow it to set a longer length.
62 // The unsafety in this function is twofold:
64 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
66 // 2. We're passing a raw buffer to the function `f`, and it is expected that
67 // the function only *appends* bytes to the buffer. We'll get undefined
68 // behavior if existing bytes are overwritten to have non-UTF-8 data.
69 fn append_to_string
<F
>(buf
: &mut String
, f
: F
) -> Result
<usize>
70 where F
: FnOnce(&mut Vec
<u8>) -> Result
<usize>
72 struct Guard
<'a
> { s: &'a mut Vec<u8>, len: usize }
73 impl<'a
> Drop
for Guard
<'a
> {
75 unsafe { self.s.set_len(self.len); }
80 let mut g
= Guard { len: buf.len(), s: buf.as_mut_vec() }
;
82 if str::from_utf8(&g
.s
[g
.len
..]).is_err() {
84 Err(Error
::new(ErrorKind
::InvalidInput
,
85 "stream did not contain valid UTF-8"))
94 // This uses an adaptive system to extend the vector when it fills. We want to
95 // avoid paying to allocate and zero a huge chunk of memory if the reader only
96 // has 4 bytes while still making large reads if the reader does have a ton
97 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
98 // time is 4,500 times (!) slower than this if the reader has a very small
99 // amount of data to return.
100 fn read_to_end
<R
: Read
+ ?Sized
>(r
: &mut R
, buf
: &mut Vec
<u8>) -> Result
<usize> {
101 let start_len
= buf
.len();
102 let mut len
= start_len
;
103 let mut new_write_size
= 16;
106 if len
== buf
.len() {
107 if new_write_size
< DEFAULT_BUF_SIZE
{
110 buf
.extend(iter
::repeat(0).take(new_write_size
));
113 match r
.read(&mut buf
[len
..]) {
115 ret
= Ok(len
- start_len
);
119 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
131 /// A trait for objects which are byte-oriented sources.
133 /// Readers are defined by one method, `read`. Each call to `read` will attempt
134 /// to pull bytes from this source into a provided buffer.
136 /// Readers are intended to be composable with one another. Many objects
137 /// throughout the I/O and related libraries take and provide types which
138 /// implement the `Read` trait.
139 #[stable(feature = "rust1", since = "1.0.0")]
141 /// Pull some bytes from this source into the specified buffer, returning
142 /// how many bytes were read.
144 /// This function does not provide any guarantees about whether it blocks
145 /// waiting for data, but if an object needs to block for a read but cannot
146 /// it will typically signal this via an `Err` return value.
148 /// If the return value of this method is `Ok(n)`, then it must be
149 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
150 /// that the buffer `buf` has been filled in with `n` bytes of data from this
151 /// source. If `n` is `0`, then it can indicate one of two scenarios:
153 /// 1. This reader has reached its "end of file" and will likely no longer
154 /// be able to produce bytes. Note that this does not mean that the
155 /// reader will *always* no longer be able to produce bytes.
156 /// 2. The buffer specified was 0 bytes in length.
158 /// No guarantees are provided about the contents of `buf` when this
159 /// function is called, implementations cannot rely on any property of the
160 /// contents of `buf` being true. It is recommended that implementations
161 /// only write data to `buf` instead of reading its contents.
165 /// If this function encounters any form of I/O or other error, an error
166 /// variant will be returned. If an error is returned then it must be
167 /// guaranteed that no bytes were read.
168 #[stable(feature = "rust1", since = "1.0.0")]
169 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize>;
171 /// Read all bytes until EOF in this source, placing them into `buf`.
173 /// All bytes read from this source will be appended to the specified buffer
174 /// `buf`. This function will continuously call `read` to append more data to
175 /// `buf` until `read` returns either `Ok(0)` or an error of
176 /// non-`ErrorKind::Interrupted` kind.
178 /// If successful, this function will return the total number of bytes read.
182 /// If this function encounters an error of the kind
183 /// `ErrorKind::Interrupted` then the error is ignored and the operation
186 /// If any other read error is encountered then this function immediately
187 /// returns. Any bytes which have already been read will be appended to
189 #[stable(feature = "rust1", since = "1.0.0")]
190 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> Result
<usize> {
191 read_to_end(self, buf
)
194 /// Read all bytes until EOF in this source, placing them into `buf`.
196 /// If successful, this function returns the number of bytes which were read
197 /// and appended to `buf`.
201 /// If the data in this stream is *not* valid UTF-8 then an error is
202 /// returned and `buf` is unchanged.
204 /// See `read_to_end` for other error semantics.
205 #[stable(feature = "rust1", since = "1.0.0")]
206 fn read_to_string(&mut self, buf
: &mut String
) -> Result
<usize> {
207 // Note that we do *not* call `.read_to_end()` here. We are passing
208 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
209 // method to fill it up. An arbitrary implementation could overwrite the
210 // entire contents of the vector, not just append to it (which is what
211 // we are expecting).
213 // To prevent extraneously checking the UTF-8-ness of the entire buffer
214 // we pass it to our hardcoded `read_to_end` implementation which we
215 // know is guaranteed to only read data into the end of the buffer.
216 append_to_string(buf
, |b
| read_to_end(self, b
))
219 /// Creates a "by reference" adaptor for this instance of `Read`.
221 /// The returned adaptor also implements `Read` and will simply borrow this
223 #[stable(feature = "rust1", since = "1.0.0")]
224 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
226 /// Transforms this `Read` instance to an `Iterator` over its bytes.
228 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
229 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
230 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
232 #[stable(feature = "rust1", since = "1.0.0")]
233 fn bytes(self) -> Bytes
<Self> where Self: Sized
{
234 Bytes { inner: self }
237 /// Transforms this `Read` instance to an `Iterator` over `char`s.
239 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
240 /// sequence of characters. The returned iterator will return `None` once
241 /// EOF is reached for this reader. Otherwise each element yielded will be a
242 /// `Result<char, E>` where `E` may contain information about what I/O error
243 /// occurred or where decoding failed.
245 /// Currently this adaptor will discard intermediate data read, and should
246 /// be avoided if this is not desired.
247 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
248 of where errors happen is currently \
249 unclear and may change")]
250 fn chars(self) -> Chars
<Self> where Self: Sized
{
251 Chars { inner: self }
254 /// Creates an adaptor which will chain this stream with another.
256 /// The returned `Read` instance will first read all bytes from this object
257 /// until EOF is encountered. Afterwards the output is equivalent to the
258 /// output of `next`.
259 #[stable(feature = "rust1", since = "1.0.0")]
260 fn chain
<R
: Read
>(self, next
: R
) -> Chain
<Self, R
> where Self: Sized
{
261 Chain { first: self, second: next, done_first: false }
264 /// Creates an adaptor which will read at most `limit` bytes from it.
266 /// This function returns a new instance of `Read` which will read at most
267 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
268 /// read errors will not count towards the number of bytes read and future
269 /// calls to `read` may succeed.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 fn take(self, limit
: u64) -> Take
<Self> where Self: Sized
{
272 Take { inner: self, limit: limit }
275 /// Creates a reader adaptor which will write all read data into the given
278 /// Whenever the returned `Read` instance is read it will write the read
279 /// data to `out`. The current semantics of this implementation imply that
280 /// a `write` error will not report how much data was initially read.
281 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
282 of where errors happen is currently \
283 unclear and may change")]
284 fn tee
<W
: Write
>(self, out
: W
) -> Tee
<Self, W
> where Self: Sized
{
285 Tee { reader: self, writer: out }
289 /// A trait for objects which are byte-oriented sinks.
291 /// The `write` method will attempt to write some data into the object,
292 /// returning how many bytes were successfully written.
294 /// The `flush` method is useful for adaptors and explicit buffers themselves
295 /// for ensuring that all buffered data has been pushed out to the "true sink".
297 /// Writers are intended to be composable with one another. Many objects
298 /// throughout the I/O and related libraries take and provide types which
299 /// implement the `Write` trait.
300 #[stable(feature = "rust1", since = "1.0.0")]
302 /// Write a buffer into this object, returning how many bytes were written.
304 /// This function will attempt to write the entire contents of `buf`, but
305 /// the entire write may not succeed, or the write may also generate an
306 /// error. A call to `write` represents *at most one* attempt to write to
307 /// any wrapped object.
309 /// Calls to `write` are not guaranteed to block waiting for data to be
310 /// written, and a write which would otherwise block can indicated through
311 /// an `Err` variant.
313 /// If the return value is `Ok(n)` then it must be guaranteed that
314 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
315 /// underlying object is no longer able to accept bytes and will likely not
316 /// be able to in the future as well, or that the buffer provided is empty.
320 /// Each call to `write` may generate an I/O error indicating that the
321 /// operation could not be completed. If an error is returned then no bytes
322 /// in the buffer were written to this writer.
324 /// It is **not** considered an error if the entire buffer could not be
325 /// written to this writer.
326 #[stable(feature = "rust1", since = "1.0.0")]
327 fn write(&mut self, buf
: &[u8]) -> Result
<usize>;
329 /// Flush this output stream, ensuring that all intermediately buffered
330 /// contents reach their destination.
334 /// It is considered an error if not all bytes could be written due to
335 /// I/O errors or EOF being reached.
336 #[stable(feature = "rust1", since = "1.0.0")]
337 fn flush(&mut self) -> Result
<()>;
339 /// Attempts to write an entire buffer into this write.
341 /// This method will continuously call `write` while there is more data to
342 /// write. This method will not return until the entire buffer has been
343 /// successfully written or an error occurs. The first error generated from
344 /// this method will be returned.
348 /// This function will return the first error that `write` returns.
349 #[stable(feature = "rust1", since = "1.0.0")]
350 fn write_all(&mut self, mut buf
: &[u8]) -> Result
<()> {
351 while !buf
.is_empty() {
352 match self.write(buf
) {
353 Ok(0) => return Err(Error
::new(ErrorKind
::WriteZero
,
354 "failed to write whole buffer")),
355 Ok(n
) => buf
= &buf
[n
..],
356 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
357 Err(e
) => return Err(e
),
363 /// Writes a formatted string into this writer, returning any error
366 /// This method is primarily used to interface with the `format_args!`
367 /// macro, but it is rare that this should explicitly be called. The
368 /// `write!` macro should be favored to invoke this method instead.
370 /// This function internally uses the `write_all` method on this trait and
371 /// hence will continuously write data so long as no errors are received.
372 /// This also means that partial writes are not indicated in this signature.
376 /// This function will return any I/O error reported while formatting.
377 #[stable(feature = "rust1", since = "1.0.0")]
378 fn write_fmt(&mut self, fmt
: fmt
::Arguments
) -> Result
<()> {
379 // Create a shim which translates a Write to a fmt::Write and saves
380 // off I/O errors. instead of discarding them
381 struct Adaptor
<'a
, T
: ?Sized
+ 'a
> {
386 impl<'a
, T
: Write
+ ?Sized
> fmt
::Write
for Adaptor
<'a
, T
> {
387 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
388 match self.inner
.write_all(s
.as_bytes()) {
398 let mut output
= Adaptor { inner: self, error: Ok(()) }
;
399 match fmt
::write(&mut output
, fmt
) {
401 Err(..) => output
.error
405 /// Creates a "by reference" adaptor for this instance of `Write`.
407 /// The returned adaptor also implements `Write` and will simply borrow this
409 #[stable(feature = "rust1", since = "1.0.0")]
410 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
412 /// Creates a new writer which will write all data to both this writer and
415 /// All data written to the returned writer will both be written to `self`
416 /// as well as `other`. Note that the error semantics of the current
417 /// implementation do not precisely track where errors happen. For example
418 /// an error on the second call to `write` will not report that the first
419 /// call to `write` succeeded.
420 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
421 of where errors happen is currently \
422 unclear and may change")]
423 fn broadcast
<W
: Write
>(self, other
: W
) -> Broadcast
<Self, W
>
426 Broadcast { first: self, second: other }
430 /// An object implementing `Seek` internally has some form of cursor which can
431 /// be moved within a stream of bytes.
433 /// The stream typically has a fixed size, allowing seeking relative to either
434 /// end or the current offset.
435 #[stable(feature = "rust1", since = "1.0.0")]
437 /// Seek to an offset, in bytes, in a stream
439 /// A seek beyond the end of a stream is allowed, but seeking before offset
442 /// The behavior when seeking past the end of the stream is implementation
445 /// This method returns the new position within the stream if the seek
446 /// operation completed successfully.
450 /// Seeking to a negative offset is considered an error
451 #[stable(feature = "rust1", since = "1.0.0")]
452 fn seek(&mut self, pos
: SeekFrom
) -> Result
<u64>;
455 /// Enumeration of possible methods to seek within an I/O object.
456 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
457 #[stable(feature = "rust1", since = "1.0.0")]
459 /// Set the offset to the provided number of bytes.
460 #[stable(feature = "rust1", since = "1.0.0")]
463 /// Set the offset to the size of this object plus the specified number of
466 /// It is possible to seek beyond the end of an object, but is an error to
467 /// seek before byte 0.
468 #[stable(feature = "rust1", since = "1.0.0")]
471 /// Set the offset to the current position plus the specified number of
474 /// It is possible to seek beyond the end of an object, but is an error to
475 /// seek before byte 0.
476 #[stable(feature = "rust1", since = "1.0.0")]
480 fn read_until
<R
: BufRead
+ ?Sized
>(r
: &mut R
, delim
: u8, buf
: &mut Vec
<u8>)
485 let available
= match r
.fill_buf() {
487 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> continue,
488 Err(e
) => return Err(e
)
490 match available
.position_elem(&delim
) {
492 buf
.push_all(&available
[..i
+ 1]);
496 buf
.push_all(available
);
497 (false, available
.len())
503 if done
|| used
== 0 {
509 /// A Buffer is a type of reader which has some form of internal buffering to
510 /// allow certain kinds of reading operations to be more optimized than others.
512 /// This type extends the `Read` trait with a few methods that are not
513 /// possible to reasonably implement with purely a read interface.
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub trait BufRead
: Read
{
516 /// Fills the internal buffer of this object, returning the buffer contents.
518 /// None of the contents will be "read" in the sense that later calling
519 /// `read` may return the same contents.
521 /// The `consume` function must be called with the number of bytes that are
522 /// consumed from this buffer returned to ensure that the bytes are never
525 /// An empty buffer returned indicates that the stream has reached EOF.
529 /// This function will return an I/O error if the underlying reader was
530 /// read, but returned an error.
531 #[stable(feature = "rust1", since = "1.0.0")]
532 fn fill_buf(&mut self) -> Result
<&[u8]>;
534 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
535 /// so they should no longer be returned in calls to `read`.
537 /// This function does not perform any I/O, it simply informs this object
538 /// that some amount of its buffer, returned from `fill_buf`, has been
539 /// consumed and should no longer be returned.
541 /// This function is used to tell the buffer how many bytes you've consumed
542 /// from the return value of `fill_buf`, and so may do odd things if
543 /// `fill_buf` isn't called before calling this.
545 /// The `amt` must be `<=` the number of bytes in the buffer returned by `fill_buf`.
546 #[stable(feature = "rust1", since = "1.0.0")]
547 fn consume(&mut self, amt
: usize);
549 /// Read all bytes until the delimiter `byte` is reached.
551 /// This function will continue to read (and buffer) bytes from the
552 /// underlying stream until the delimiter or EOF is found. Once found, all
553 /// bytes up to, and including, the delimiter (if found) will be appended to
556 /// If this buffered reader is currently at EOF, then this function will not
557 /// place any more bytes into `buf` and will return `Ok(n)` where `n` is the
558 /// number of bytes which were read.
562 /// This function will ignore all instances of `ErrorKind::Interrupted` and
563 /// will otherwise return any errors returned by `fill_buf`.
565 /// If an I/O error is encountered then all bytes read so far will be
566 /// present in `buf` and its length will have been adjusted appropriately.
567 #[stable(feature = "rust1", since = "1.0.0")]
568 fn read_until(&mut self, byte
: u8, buf
: &mut Vec
<u8>) -> Result
<usize> {
569 read_until(self, byte
, buf
)
572 /// Read all bytes until a newline byte (the 0xA byte) is reached, and
573 /// append them to the provided buffer.
575 /// This function will continue to read (and buffer) bytes from the
576 /// underlying stream until the newline delimiter (the 0xA byte) or EOF is
577 /// found. Once found, all bytes up to, and including, the delimiter (if
578 /// found) will be appended to `buf`.
580 /// If this reader is currently at EOF then this function will not modify
581 /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
586 /// This function has the same error semantics as `read_until` and will also
587 /// return an error if the read bytes are not valid UTF-8. If an I/O error
588 /// is encountered then `buf` may contain some bytes already read in the
589 /// event that all data read so far was valid UTF-8.
590 #[stable(feature = "rust1", since = "1.0.0")]
591 fn read_line(&mut self, buf
: &mut String
) -> Result
<usize> {
592 // Note that we are not calling the `.read_until` method here, but
593 // rather our hardcoded implementation. For more details as to why, see
594 // the comments in `read_to_end`.
595 append_to_string(buf
, |b
| read_until(self, b'
\n'
, b
))
598 /// Returns an iterator over the contents of this reader split on the byte
601 /// The iterator returned from this function will return instances of
602 /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
603 /// delimiter byte at the end.
605 /// This function will yield errors whenever `read_until` would have also
606 /// yielded an error.
607 #[stable(feature = "rust1", since = "1.0.0")]
608 fn split(self, byte
: u8) -> Split
<Self> where Self: Sized
{
609 Split { buf: self, delim: byte }
612 /// Returns an iterator over the lines of this reader.
614 /// The iterator returned from this function will yield instances of
615 /// `io::Result<String>`. Each string returned will *not* have a newline
616 /// byte (the 0xA byte) at the end.
617 #[stable(feature = "rust1", since = "1.0.0")]
618 fn lines(self) -> Lines
<Self> where Self: Sized
{
623 /// A `Write` adaptor which will write data to multiple locations.
625 /// For more information, see `Write::broadcast`.
626 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")]
627 pub struct Broadcast
<T
, U
> {
632 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")]
633 impl<T
: Write
, U
: Write
> Write
for Broadcast
<T
, U
> {
634 fn write(&mut self, data
: &[u8]) -> Result
<usize> {
635 let n
= try
!(self.first
.write(data
));
636 // FIXME: what if the write fails? (we wrote something)
637 try
!(self.second
.write_all(&data
[..n
]));
641 fn flush(&mut self) -> Result
<()> {
642 self.first
.flush().and(self.second
.flush())
646 /// Adaptor to chain together two instances of `Read`.
648 /// For more information, see `Read::chain`.
649 #[stable(feature = "rust1", since = "1.0.0")]
650 pub struct Chain
<T
, U
> {
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<T
: Read
, U
: Read
> Read
for Chain
<T
, U
> {
658 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
659 if !self.done_first
{
660 match try
!(self.first
.read(buf
)) {
661 0 => { self.done_first = true; }
665 self.second
.read(buf
)
669 /// Reader adaptor which limits the bytes read from an underlying reader.
671 /// For more information, see `Read::take`.
672 #[stable(feature = "rust1", since = "1.0.0")]
678 #[stable(feature = "rust1", since = "1.0.0")]
680 /// Returns the number of bytes that can be read before this instance will
685 /// This instance may reach EOF after reading fewer bytes than indicated by
686 /// this method if the underlying `Read` instance reaches EOF.
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn limit(&self) -> u64 { self.limit }
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T
: Read
> Read
for Take
<T
> {
693 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
694 // Don't call into inner reader at all at EOF because it may still block
699 let max
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
700 let n
= try
!(self.inner
.read(&mut buf
[..max
]));
701 self.limit
-= n
as u64;
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl<T
: BufRead
> BufRead
for Take
<T
> {
708 fn fill_buf(&mut self) -> Result
<&[u8]> {
709 let buf
= try
!(self.inner
.fill_buf());
710 let cap
= cmp
::min(buf
.len() as u64, self.limit
) as usize;
714 fn consume(&mut self, amt
: usize) {
715 // Don't let callers reset the limit by passing an overlarge value
716 let amt
= cmp
::min(amt
as u64, self.limit
) as usize;
717 self.limit
-= amt
as u64;
718 self.inner
.consume(amt
);
722 /// An adaptor which will emit all read data to a specified writer as well.
724 /// For more information see `Read::tee`
725 #[unstable(feature = "io", reason = "awaiting stability of Read::tee")]
726 pub struct Tee
<R
, W
> {
731 #[unstable(feature = "io", reason = "awaiting stability of Read::tee")]
732 impl<R
: Read
, W
: Write
> Read
for Tee
<R
, W
> {
733 fn read(&mut self, buf
: &mut [u8]) -> Result
<usize> {
734 let n
= try
!(self.reader
.read(buf
));
735 // FIXME: what if the write fails? (we read something)
736 try
!(self.writer
.write_all(&buf
[..n
]));
741 /// A bridge from implementations of `Read` to an `Iterator` of `u8`.
743 /// See `Read::bytes` for more information.
744 #[stable(feature = "rust1", since = "1.0.0")]
745 pub struct Bytes
<R
> {
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<R
: Read
> Iterator
for Bytes
<R
> {
751 type Item
= Result
<u8>;
753 fn next(&mut self) -> Option
<Result
<u8>> {
755 match self.inner
.read(&mut buf
) {
757 Ok(..) => Some(Ok(buf
[0])),
758 Err(e
) => Some(Err(e
)),
763 /// A bridge from implementations of `Read` to an `Iterator` of `char`.
765 /// See `Read::chars` for more information.
766 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
767 pub struct Chars
<R
> {
771 /// An enumeration of possible errors that can be generated from the `Chars`
774 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
775 pub enum CharsError
{
776 /// Variant representing that the underlying stream was read successfully
777 /// but it did not contain valid utf8 data.
780 /// Variant representing that an I/O error occurred.
784 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
785 impl<R
: Read
> Iterator
for Chars
<R
> {
786 type Item
= result
::Result
<char, CharsError
>;
788 fn next(&mut self) -> Option
<result
::Result
<char, CharsError
>> {
790 let first_byte
= match self.inner
.read(&mut buf
) {
791 Ok(0) => return None
,
793 Err(e
) => return Some(Err(CharsError
::Other(e
))),
795 let width
= core_str
::utf8_char_width(first_byte
);
796 if width
== 1 { return Some(Ok(first_byte as char)) }
797 if width
== 0 { return Some(Err(CharsError::NotUtf8)) }
798 let mut buf
= [first_byte
, 0, 0, 0];
801 while start
< width
{
802 match self.inner
.read(&mut buf
[start
..width
]) {
803 Ok(0) => return Some(Err(CharsError
::NotUtf8
)),
805 Err(e
) => return Some(Err(CharsError
::Other(e
))),
809 Some(match str::from_utf8(&buf
[..width
]).ok() {
810 Some(s
) => Ok(s
.char_at(0)),
811 None
=> Err(CharsError
::NotUtf8
),
816 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
817 impl std_error
::Error
for CharsError
{
818 fn description(&self) -> &str {
820 CharsError
::NotUtf8
=> "invalid utf8 encoding",
821 CharsError
::Other(ref e
) => std_error
::Error
::description(e
),
824 fn cause(&self) -> Option
<&std_error
::Error
> {
826 CharsError
::NotUtf8
=> None
,
827 CharsError
::Other(ref e
) => e
.cause(),
832 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
833 impl fmt
::Display
for CharsError
{
834 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
836 CharsError
::NotUtf8
=> {
837 "byte stream did not contain valid utf8".fmt(f
)
839 CharsError
::Other(ref e
) => e
.fmt(f
),
844 /// An iterator over the contents of an instance of `BufRead` split on a
847 /// See `BufRead::split` for more information.
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub struct Split
<B
> {
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<B
: BufRead
> Iterator
for Split
<B
> {
856 type Item
= Result
<Vec
<u8>>;
858 fn next(&mut self) -> Option
<Result
<Vec
<u8>>> {
859 let mut buf
= Vec
::new();
860 match self.buf
.read_until(self.delim
, &mut buf
) {
863 if buf
[buf
.len() - 1] == self.delim
{
868 Err(e
) => Some(Err(e
))
873 /// An iterator over the lines of an instance of `BufRead` split on a newline
876 /// See `BufRead::lines` for more information.
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub struct Lines
<B
> {
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<B
: BufRead
> Iterator
for Lines
<B
> {
884 type Item
= Result
<String
>;
886 fn next(&mut self) -> Option
<Result
<String
>> {
887 let mut buf
= String
::new();
888 match self.buf
.read_line(&mut buf
) {
891 if buf
.ends_with("\n") {
896 Err(e
) => Some(Err(e
))
910 let mut buf
= Cursor
::new(&b
"12"[..]);
911 let mut v
= Vec
::new();
912 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 2);
913 assert_eq
!(v
, b
"12");
915 let mut buf
= Cursor
::new(&b
"1233"[..]);
916 let mut v
= Vec
::new();
917 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 3);
918 assert_eq
!(v
, b
"123");
920 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 1);
923 assert_eq
!(buf
.read_until(b'
3'
, &mut v
).unwrap(), 0);
929 let buf
= Cursor
::new(&b
"12"[..]);
930 let mut s
= buf
.split(b'
3'
);
931 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
932 assert
!(s
.next().is_none());
934 let buf
= Cursor
::new(&b
"1233"[..]);
935 let mut s
= buf
.split(b'
3'
);
936 assert_eq
!(s
.next().unwrap().unwrap(), vec
![b'
1'
, b'
2'
]);
937 assert_eq
!(s
.next().unwrap().unwrap(), vec
![]);
938 assert
!(s
.next().is_none());
943 let mut buf
= Cursor
::new(&b
"12"[..]);
944 let mut v
= String
::new();
945 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 2);
948 let mut buf
= Cursor
::new(&b
"12\n\n"[..]);
949 let mut v
= String
::new();
950 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 3);
951 assert_eq
!(v
, "12\n");
953 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 1);
956 assert_eq
!(buf
.read_line(&mut v
).unwrap(), 0);
962 let buf
= Cursor
::new(&b
"12"[..]);
963 let mut s
= buf
.lines();
964 assert_eq
!(s
.next().unwrap().unwrap(), "12".to_string());
965 assert
!(s
.next().is_none());
967 let buf
= Cursor
::new(&b
"12\n\n"[..]);
968 let mut s
= buf
.lines();
969 assert_eq
!(s
.next().unwrap().unwrap(), "12".to_string());
970 assert_eq
!(s
.next().unwrap().unwrap(), "".to_string());
971 assert
!(s
.next().is_none());
976 let mut c
= Cursor
::new(&b
""[..]);
977 let mut v
= Vec
::new();
978 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 0);
981 let mut c
= Cursor
::new(&b
"1"[..]);
982 let mut v
= Vec
::new();
983 assert_eq
!(c
.read_to_end(&mut v
).unwrap(), 1);
988 fn read_to_string() {
989 let mut c
= Cursor
::new(&b
""[..]);
990 let mut v
= String
::new();
991 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 0);
994 let mut c
= Cursor
::new(&b
"1"[..]);
995 let mut v
= String
::new();
996 assert_eq
!(c
.read_to_string(&mut v
).unwrap(), 1);
999 let mut c
= Cursor
::new(&b
"\xff"[..]);
1000 let mut v
= String
::new();
1001 assert
!(c
.read_to_string(&mut v
).is_err());
1009 fn read(&mut self, _
: &mut [u8]) -> io
::Result
<usize> {
1010 Err(io
::Error
::new(io
::ErrorKind
::Other
, ""))
1014 let mut buf
= [0; 1];
1015 assert_eq
!(0, R
.take(0).read(&mut buf
).unwrap());