]> git.proxmox.com Git - rustc.git/blob - src/libstd/io/mod.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / libstd / io / mod.rs
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.
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 //! Traits, helpers, and type definitions for core I/O functionality.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use cmp;
16 use rustc_unicode::str as core_str;
17 use error as std_error;
18 use fmt;
19 use iter::{self, Iterator, Extend};
20 use marker::Sized;
21 use ops::{Drop, FnOnce};
22 use option::Option::{self, Some, None};
23 use result::Result::{Ok, Err};
24 use result;
25 use string::String;
26 use str;
27 use vec::Vec;
28
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};
38
39 #[macro_use] mod lazy;
40
41 pub mod prelude;
42 mod buffered;
43 mod cursor;
44 mod error;
45 mod impls;
46 mod util;
47 mod stdio;
48
49 const DEFAULT_BUF_SIZE: usize = 64 * 1024;
50
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.
56 //
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.
61 //
62 // The unsafety in this function is twofold:
63 //
64 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
65 // checks.
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>
71 {
72 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
73 impl<'a> Drop for Guard<'a> {
74 fn drop(&mut self) {
75 unsafe { self.s.set_len(self.len); }
76 }
77 }
78
79 unsafe {
80 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
81 let ret = f(g.s);
82 if str::from_utf8(&g.s[g.len..]).is_err() {
83 ret.and_then(|_| {
84 Err(Error::new(ErrorKind::InvalidInput,
85 "stream did not contain valid UTF-8"))
86 })
87 } else {
88 g.len = g.s.len();
89 ret
90 }
91 }
92 }
93
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;
104 let ret;
105 loop {
106 if len == buf.len() {
107 if new_write_size < DEFAULT_BUF_SIZE {
108 new_write_size *= 2;
109 }
110 buf.extend(iter::repeat(0).take(new_write_size));
111 }
112
113 match r.read(&mut buf[len..]) {
114 Ok(0) => {
115 ret = Ok(len - start_len);
116 break;
117 }
118 Ok(n) => len += n,
119 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
120 Err(e) => {
121 ret = Err(e);
122 break;
123 }
124 }
125 }
126
127 buf.truncate(len);
128 ret
129 }
130
131 /// A trait for objects which are byte-oriented sources.
132 ///
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.
135 ///
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")]
140 pub trait Read {
141 /// Pull some bytes from this source into the specified buffer, returning
142 /// how many bytes were read.
143 ///
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.
147 ///
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:
152 ///
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.
157 ///
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.
162 ///
163 /// # Errors
164 ///
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>;
170
171 /// Read all bytes until EOF in this source, placing them into `buf`.
172 ///
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.
177 ///
178 /// If successful, this function will return the total number of bytes read.
179 ///
180 /// # Errors
181 ///
182 /// If this function encounters an error of the kind
183 /// `ErrorKind::Interrupted` then the error is ignored and the operation
184 /// will continue.
185 ///
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
188 /// `buf`.
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)
192 }
193
194 /// Read all bytes until EOF in this source, placing them into `buf`.
195 ///
196 /// If successful, this function returns the number of bytes which were read
197 /// and appended to `buf`.
198 ///
199 /// # Errors
200 ///
201 /// If the data in this stream is *not* valid UTF-8 then an error is
202 /// returned and `buf` is unchanged.
203 ///
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).
212 //
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))
217 }
218
219 /// Creates a "by reference" adaptor for this instance of `Read`.
220 ///
221 /// The returned adaptor also implements `Read` and will simply borrow this
222 /// current reader.
223 #[stable(feature = "rust1", since = "1.0.0")]
224 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
225
226 /// Transforms this `Read` instance to an `Iterator` over its bytes.
227 ///
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
231 /// this iterator.
232 #[stable(feature = "rust1", since = "1.0.0")]
233 fn bytes(self) -> Bytes<Self> where Self: Sized {
234 Bytes { inner: self }
235 }
236
237 /// Transforms this `Read` instance to an `Iterator` over `char`s.
238 ///
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.
244 ///
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 }
252 }
253
254 /// Creates an adaptor which will chain this stream with another.
255 ///
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 }
262 }
263
264 /// Creates an adaptor which will read at most `limit` bytes from it.
265 ///
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 }
273 }
274
275 /// Creates a reader adaptor which will write all read data into the given
276 /// output stream.
277 ///
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 }
286 }
287 }
288
289 /// A trait for objects which are byte-oriented sinks.
290 ///
291 /// The `write` method will attempt to write some data into the object,
292 /// returning how many bytes were successfully written.
293 ///
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".
296 ///
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")]
301 pub trait Write {
302 /// Write a buffer into this object, returning how many bytes were written.
303 ///
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.
308 ///
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.
312 ///
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.
317 ///
318 /// # Errors
319 ///
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.
323 ///
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>;
328
329 /// Flush this output stream, ensuring that all intermediately buffered
330 /// contents reach their destination.
331 ///
332 /// # Errors
333 ///
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<()>;
338
339 /// Attempts to write an entire buffer into this write.
340 ///
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.
345 ///
346 /// # Errors
347 ///
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),
358 }
359 }
360 Ok(())
361 }
362
363 /// Writes a formatted string into this writer, returning any error
364 /// encountered.
365 ///
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.
369 ///
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.
373 ///
374 /// # Errors
375 ///
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> {
382 inner: &'a mut T,
383 error: Result<()>,
384 }
385
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()) {
389 Ok(()) => Ok(()),
390 Err(e) => {
391 self.error = Err(e);
392 Err(fmt::Error)
393 }
394 }
395 }
396 }
397
398 let mut output = Adaptor { inner: self, error: Ok(()) };
399 match fmt::write(&mut output, fmt) {
400 Ok(()) => Ok(()),
401 Err(..) => output.error
402 }
403 }
404
405 /// Creates a "by reference" adaptor for this instance of `Write`.
406 ///
407 /// The returned adaptor also implements `Write` and will simply borrow this
408 /// current writer.
409 #[stable(feature = "rust1", since = "1.0.0")]
410 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
411
412 /// Creates a new writer which will write all data to both this writer and
413 /// another writer.
414 ///
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>
424 where Self: Sized
425 {
426 Broadcast { first: self, second: other }
427 }
428 }
429
430 /// An object implementing `Seek` internally has some form of cursor which can
431 /// be moved within a stream of bytes.
432 ///
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")]
436 pub trait Seek {
437 /// Seek to an offset, in bytes, in a stream
438 ///
439 /// A seek beyond the end of a stream is allowed, but seeking before offset
440 /// 0 is an error.
441 ///
442 /// The behavior when seeking past the end of the stream is implementation
443 /// defined.
444 ///
445 /// This method returns the new position within the stream if the seek
446 /// operation completed successfully.
447 ///
448 /// # Errors
449 ///
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>;
453 }
454
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")]
458 pub enum SeekFrom {
459 /// Set the offset to the provided number of bytes.
460 #[stable(feature = "rust1", since = "1.0.0")]
461 Start(u64),
462
463 /// Set the offset to the size of this object plus the specified number of
464 /// bytes.
465 ///
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")]
469 End(i64),
470
471 /// Set the offset to the current position plus the specified number of
472 /// bytes.
473 ///
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")]
477 Current(i64),
478 }
479
480 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
481 -> Result<usize> {
482 let mut read = 0;
483 loop {
484 let (done, used) = {
485 let available = match r.fill_buf() {
486 Ok(n) => n,
487 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
488 Err(e) => return Err(e)
489 };
490 match available.position_elem(&delim) {
491 Some(i) => {
492 buf.push_all(&available[..i + 1]);
493 (true, i + 1)
494 }
495 None => {
496 buf.push_all(available);
497 (false, available.len())
498 }
499 }
500 };
501 r.consume(used);
502 read += used;
503 if done || used == 0 {
504 return Ok(read);
505 }
506 }
507 }
508
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.
511 ///
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.
517 ///
518 /// None of the contents will be "read" in the sense that later calling
519 /// `read` may return the same contents.
520 ///
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
523 /// returned twice.
524 ///
525 /// An empty buffer returned indicates that the stream has reached EOF.
526 ///
527 /// # Errors
528 ///
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]>;
533
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`.
536 ///
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.
540 ///
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.
544 ///
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);
548
549 /// Read all bytes until the delimiter `byte` is reached.
550 ///
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
554 /// `buf`.
555 ///
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.
559 ///
560 /// # Errors
561 ///
562 /// This function will ignore all instances of `ErrorKind::Interrupted` and
563 /// will otherwise return any errors returned by `fill_buf`.
564 ///
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)
570 }
571
572 /// Read all bytes until a newline byte (the 0xA byte) is reached, and
573 /// append them to the provided buffer.
574 ///
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`.
579 ///
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
582 /// were read.
583 ///
584 /// # Errors
585 ///
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))
596 }
597
598 /// Returns an iterator over the contents of this reader split on the byte
599 /// `byte`.
600 ///
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.
604 ///
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 }
610 }
611
612 /// Returns an iterator over the lines of this reader.
613 ///
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 {
619 Lines { buf: self }
620 }
621 }
622
623 /// A `Write` adaptor which will write data to multiple locations.
624 ///
625 /// For more information, see `Write::broadcast`.
626 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")]
627 pub struct Broadcast<T, U> {
628 first: T,
629 second: U,
630 }
631
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]));
638 Ok(n)
639 }
640
641 fn flush(&mut self) -> Result<()> {
642 self.first.flush().and(self.second.flush())
643 }
644 }
645
646 /// Adaptor to chain together two instances of `Read`.
647 ///
648 /// For more information, see `Read::chain`.
649 #[stable(feature = "rust1", since = "1.0.0")]
650 pub struct Chain<T, U> {
651 first: T,
652 second: U,
653 done_first: bool,
654 }
655
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; }
662 n => return Ok(n),
663 }
664 }
665 self.second.read(buf)
666 }
667 }
668
669 /// Reader adaptor which limits the bytes read from an underlying reader.
670 ///
671 /// For more information, see `Read::take`.
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub struct Take<T> {
674 inner: T,
675 limit: u64,
676 }
677
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T> Take<T> {
680 /// Returns the number of bytes that can be read before this instance will
681 /// return EOF.
682 ///
683 /// # Note
684 ///
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 }
689 }
690
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
695 if self.limit == 0 {
696 return Ok(0);
697 }
698
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;
702 Ok(n)
703 }
704 }
705
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;
711 Ok(&buf[..cap])
712 }
713
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);
719 }
720 }
721
722 /// An adaptor which will emit all read data to a specified writer as well.
723 ///
724 /// For more information see `Read::tee`
725 #[unstable(feature = "io", reason = "awaiting stability of Read::tee")]
726 pub struct Tee<R, W> {
727 reader: R,
728 writer: W,
729 }
730
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]));
737 Ok(n)
738 }
739 }
740
741 /// A bridge from implementations of `Read` to an `Iterator` of `u8`.
742 ///
743 /// See `Read::bytes` for more information.
744 #[stable(feature = "rust1", since = "1.0.0")]
745 pub struct Bytes<R> {
746 inner: R,
747 }
748
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<R: Read> Iterator for Bytes<R> {
751 type Item = Result<u8>;
752
753 fn next(&mut self) -> Option<Result<u8>> {
754 let mut buf = [0];
755 match self.inner.read(&mut buf) {
756 Ok(0) => None,
757 Ok(..) => Some(Ok(buf[0])),
758 Err(e) => Some(Err(e)),
759 }
760 }
761 }
762
763 /// A bridge from implementations of `Read` to an `Iterator` of `char`.
764 ///
765 /// See `Read::chars` for more information.
766 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
767 pub struct Chars<R> {
768 inner: R,
769 }
770
771 /// An enumeration of possible errors that can be generated from the `Chars`
772 /// adapter.
773 #[derive(Debug)]
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.
778 NotUtf8,
779
780 /// Variant representing that an I/O error occurred.
781 Other(Error),
782 }
783
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>;
787
788 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
789 let mut buf = [0];
790 let first_byte = match self.inner.read(&mut buf) {
791 Ok(0) => return None,
792 Ok(..) => buf[0],
793 Err(e) => return Some(Err(CharsError::Other(e))),
794 };
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];
799 {
800 let mut start = 1;
801 while start < width {
802 match self.inner.read(&mut buf[start..width]) {
803 Ok(0) => return Some(Err(CharsError::NotUtf8)),
804 Ok(n) => start += n,
805 Err(e) => return Some(Err(CharsError::Other(e))),
806 }
807 }
808 }
809 Some(match str::from_utf8(&buf[..width]).ok() {
810 Some(s) => Ok(s.char_at(0)),
811 None => Err(CharsError::NotUtf8),
812 })
813 }
814 }
815
816 #[unstable(feature = "io", reason = "awaiting stability of Read::chars")]
817 impl std_error::Error for CharsError {
818 fn description(&self) -> &str {
819 match *self {
820 CharsError::NotUtf8 => "invalid utf8 encoding",
821 CharsError::Other(ref e) => std_error::Error::description(e),
822 }
823 }
824 fn cause(&self) -> Option<&std_error::Error> {
825 match *self {
826 CharsError::NotUtf8 => None,
827 CharsError::Other(ref e) => e.cause(),
828 }
829 }
830 }
831
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 {
835 match *self {
836 CharsError::NotUtf8 => {
837 "byte stream did not contain valid utf8".fmt(f)
838 }
839 CharsError::Other(ref e) => e.fmt(f),
840 }
841 }
842 }
843
844 /// An iterator over the contents of an instance of `BufRead` split on a
845 /// particular byte.
846 ///
847 /// See `BufRead::split` for more information.
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub struct Split<B> {
850 buf: B,
851 delim: u8,
852 }
853
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<B: BufRead> Iterator for Split<B> {
856 type Item = Result<Vec<u8>>;
857
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) {
861 Ok(0) => None,
862 Ok(_n) => {
863 if buf[buf.len() - 1] == self.delim {
864 buf.pop();
865 }
866 Some(Ok(buf))
867 }
868 Err(e) => Some(Err(e))
869 }
870 }
871 }
872
873 /// An iterator over the lines of an instance of `BufRead` split on a newline
874 /// byte.
875 ///
876 /// See `BufRead::lines` for more information.
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub struct Lines<B> {
879 buf: B,
880 }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<B: BufRead> Iterator for Lines<B> {
884 type Item = Result<String>;
885
886 fn next(&mut self) -> Option<Result<String>> {
887 let mut buf = String::new();
888 match self.buf.read_line(&mut buf) {
889 Ok(0) => None,
890 Ok(_n) => {
891 if buf.ends_with("\n") {
892 buf.pop();
893 }
894 Some(Ok(buf))
895 }
896 Err(e) => Some(Err(e))
897 }
898 }
899 }
900
901 #[cfg(test)]
902 mod tests {
903 use prelude::v1::*;
904 use io::prelude::*;
905 use io;
906 use super::Cursor;
907
908 #[test]
909 fn read_until() {
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");
914
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");
919 v.truncate(0);
920 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
921 assert_eq!(v, b"3");
922 v.truncate(0);
923 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
924 assert_eq!(v, []);
925 }
926
927 #[test]
928 fn split() {
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());
933
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());
939 }
940
941 #[test]
942 fn read_line() {
943 let mut buf = Cursor::new(&b"12"[..]);
944 let mut v = String::new();
945 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
946 assert_eq!(v, "12");
947
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");
952 v.truncate(0);
953 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
954 assert_eq!(v, "\n");
955 v.truncate(0);
956 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
957 assert_eq!(v, "");
958 }
959
960 #[test]
961 fn lines() {
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());
966
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());
972 }
973
974 #[test]
975 fn read_to_end() {
976 let mut c = Cursor::new(&b""[..]);
977 let mut v = Vec::new();
978 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
979 assert_eq!(v, []);
980
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);
984 assert_eq!(v, b"1");
985 }
986
987 #[test]
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);
992 assert_eq!(v, "");
993
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);
997 assert_eq!(v, "1");
998
999 let mut c = Cursor::new(&b"\xff"[..]);
1000 let mut v = String::new();
1001 assert!(c.read_to_string(&mut v).is_err());
1002 }
1003
1004 #[test]
1005 fn take_eof() {
1006 struct R;
1007
1008 impl Read for R {
1009 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1010 Err(io::Error::new(io::ErrorKind::Other, ""))
1011 }
1012 }
1013
1014 let mut buf = [0; 1];
1015 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1016 }
1017 }