portable_io/
lib.rs

1//! Traits, helpers, and type definitions for core I/O functionality.
2//! A subset from Rust `std::io` functionality supported for `no-std`.
3//!
4//! **MSRV:**
5//! - stable: `1.81.0`
6//! - nightly: `nightly-2022-08-24`
7//!
8//! NOTE: unstable configuration `--cfg portable_io_unstable_all` in Rust flags is required for Rust nightly
9//! pre-`2024-06-09` to enable `error_in_core` feature directive (stabilized in June 2024).
10//!
11//! ## Features
12//!
13//! - `alloc` (enabled by default) - mandatory feature - for alloc-related functionality
14//! - `os-error` (unstable feature) - support raw OS errors - with some KNOWN PANICS due to MISSING FUNCTIONALITY
15//! - `unix-iovec` (unstable feature) - use `iovec` from `libc` for data stored in IoSlice & IoSliceMut
16//!
17//! ## CFG options
18//!
19//! - `portable_io_unstable_all` - enable all unstable option(s):
20//!   - size hint optimization for Read iterator - uses Rust unstable `min_specialization` feature
21//!
22//! To enable: use `--cfg portable_io_unstable_all` in Rust flags, set `RUSTFLAGS` env variable
23//! when running `cargo build` or `cargo test` for example.
24//!
25//! <!-- DOC TODO: INCLUDE & ADAPT MORE DOC COMMENTS FROM RUST STD IO LIBRARY CODE -->
26//! <!-- DOC TODO: CLEANUP AS MANY CARGO DOC WARNINGS AS POSSIBLE & CHECK THIS IN CI -->
27
28#![no_std]
29// ---
30// NEEDED to allow `error_in_core` & `mixed_integer_ops` feature directives, which were stabilized in June & September 2024
31#![allow(stable_features)]
32// ---
33// TODO: FIX documentation of notable traits as noted by TODO comments below - requires Rust unstable doc_notable_trait feature
34// ---
35#![cfg_attr(
36    portable_io_unstable_all,
37    feature(allocator_api, min_specialization, error_in_core, mixed_integer_ops)
38)]
39
40#[cfg(test)]
41mod tests;
42
43use core::cmp;
44#[cfg(portable_io_unstable_all)] // for unstable feature: size hint optimization
45use core::convert::TryInto;
46use core::fmt;
47use core::mem::replace;
48use core::ops::{Deref, DerefMut};
49use core::slice;
50use core::str;
51
52extern crate alloc;
53#[cfg(portable_io_unstable_all)] // for unstable feature: size hint optimization
54use alloc::boxed::Box;
55use alloc::string::String;
56use alloc::vec::Vec;
57
58// TODO: port & export more items from Rust std::io
59pub use self::cursor::Cursor;
60pub use self::error::{Error, ErrorKind, Result};
61pub use self::readbuf::ReadBuf;
62
63mod cursor;
64mod error;
65mod impls;
66pub mod prelude;
67mod readbuf;
68
69mod sys;
70
71// TODO: support limited features with no use of `alloc` crate
72#[cfg(not(any(doc, feature = "alloc")))]
73compile_error!("`alloc` feature is currently required for this library to build");
74
75#[cfg(all(feature = "unix-iovec", not(unix)))]
76compile_error!("`unix-iovec` feature requires a Unix platform");
77
78struct Guard<'a> {
79    buf: &'a mut Vec<u8>,
80    len: usize,
81}
82
83impl Drop for Guard<'_> {
84    fn drop(&mut self) {
85        unsafe {
86            self.buf.set_len(self.len);
87        }
88    }
89}
90
91// Several `read_to_string` and `read_line` methods in the standard library will
92// append data into a `String` buffer, but we need to be pretty careful when
93// doing this. The implementation will just call `.as_mut_vec()` and then
94// delegate to a byte-oriented reading method, but we must ensure that when
95// returning we never leave `buf` in a state such that it contains invalid UTF-8
96// in its bounds.
97//
98// To this end, we use an RAII guard (to protect against panics) which updates
99// the length of the string when it is dropped. This guard initially truncates
100// the string to the prior length and only after we've validated that the
101// new contents are valid UTF-8 do we allow it to set a longer length.
102//
103// The unsafety in this function is twofold:
104//
105// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
106//    checks.
107// 2. We're passing a raw buffer to the function `f`, and it is expected that
108//    the function only *appends* bytes to the buffer. We'll get undefined
109//    behavior if existing bytes are overwritten to have non-UTF-8 data.
110pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
111where
112    F: FnOnce(&mut Vec<u8>) -> Result<usize>,
113{
114    let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
115    let ret = f(g.buf);
116    if str::from_utf8(&g.buf[g.len..]).is_err() {
117        ret.and_then(|_| {
118            Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
119        })
120    } else {
121        g.len = g.buf.len();
122        ret
123    }
124}
125
126// This uses an adaptive system to extend the vector when it fills. We want to
127// avoid paying to allocate and zero a huge chunk of memory if the reader only
128// has 4 bytes while still making large reads if the reader does have a ton
129// of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
130// time is 4,500 times (!) slower than a default reservation size of 32 if the
131// reader has a very small amount of data to return.
132pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
133    let start_len = buf.len();
134    let start_cap = buf.capacity();
135
136    let mut initialized = 0; // Extra initialized bytes from previous loop iteration
137    loop {
138        if buf.len() == buf.capacity() {
139            buf.reserve(32); // buf is full, need more space
140        }
141
142        let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
143
144        // SAFETY: These bytes were initialized but not filled in the previous loop
145        unsafe {
146            read_buf.assume_init(initialized);
147        }
148
149        match r.read_buf(&mut read_buf) {
150            Ok(()) => {}
151            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
152            Err(e) => return Err(e),
153        }
154
155        if read_buf.filled_len() == 0 {
156            return Ok(buf.len() - start_len);
157        }
158
159        // store how much was initialized but not filled
160        initialized = read_buf.initialized_len() - read_buf.filled_len();
161        let new_len = read_buf.filled_len() + buf.len();
162
163        // SAFETY: ReadBuf's invariants mean this much memory is init
164        unsafe {
165            buf.set_len(new_len);
166        }
167
168        if buf.len() == buf.capacity() && buf.capacity() == start_cap {
169            // The buffer might be an exact fit. Let's read into a probe buffer
170            // and see if it returns `Ok(0)`. If so, we've avoided an
171            // unnecessary doubling of the capacity. But if not, append the
172            // probe buffer to the primary buffer and let its capacity grow.
173            let mut probe = [0u8; 32];
174
175            loop {
176                match r.read(&mut probe) {
177                    Ok(0) => return Ok(buf.len() - start_len),
178                    Ok(n) => {
179                        buf.extend_from_slice(&probe[..n]);
180                        break;
181                    }
182                    Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
183                    Err(e) => return Err(e),
184                }
185            }
186        }
187    }
188}
189
190pub(crate) fn default_read_to_string<R: Read + ?Sized>(
191    r: &mut R,
192    buf: &mut String,
193) -> Result<usize> {
194    // Note that we do *not* call `r.read_to_end()` here. We are passing
195    // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
196    // method to fill it up. An arbitrary implementation could overwrite the
197    // entire contents of the vector, not just append to it (which is what
198    // we are expecting).
199    //
200    // To prevent extraneously checking the UTF-8-ness of the entire buffer
201    // we pass it to our hardcoded `default_read_to_end` implementation which
202    // we know is guaranteed to only read data into the end of the buffer.
203    unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
204}
205
206pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
207where
208    F: FnOnce(&mut [u8]) -> Result<usize>,
209{
210    let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
211    read(buf)
212}
213
214pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
215where
216    F: FnOnce(&[u8]) -> Result<usize>,
217{
218    let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
219    write(buf)
220}
221
222pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
223    while !buf.is_empty() {
224        match this.read(buf) {
225            Ok(0) => break,
226            Ok(n) => {
227                let tmp = buf;
228                buf = &mut tmp[n..];
229            }
230            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
231            Err(e) => return Err(e),
232        }
233    }
234    if !buf.is_empty() {
235        Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
236    } else {
237        Ok(())
238    }
239}
240
241pub(crate) fn default_read_buf<F>(read: F, buf: &mut ReadBuf<'_>) -> Result<()>
242where
243    F: FnOnce(&mut [u8]) -> Result<usize>,
244{
245    let n = read(buf.initialize_unfilled())?;
246    buf.add_filled(n);
247    Ok(())
248}
249
250/// The `Read` trait allows for reading bytes from a source.
251///
252/// Implementors of the `Read` trait are called 'readers'.
253///
254/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
255/// will attempt to pull bytes from this source into a provided buffer. A
256/// number of other methods are implemented in terms of [`read()`], giving
257/// implementors a number of ways to read bytes while only needing to implement
258/// a single method.
259///
260/// Readers are intended to be composable with one another. Many implementors
261/// throughout [`std::io`] take and provide types which implement the `Read`
262/// trait.
263///
264/// Please note that each call to [`read()`] may involve a system call, and
265/// therefore, using something that implements [`BufRead`], such as
266/// [`BufReader`], will be more efficient.
267///
268/// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
269/// # Example code
270///
271/// Read from [`&str`] - possible because [`&[u8]`][prim@slice] is enhanced with impl of `Read`:
272///
273/// ```no_run
274/// use portable_io::{self as io, Read};
275///
276/// fn main() -> io::Result<()> {
277///     let mut b = "This string will be read".as_bytes();
278///     let mut buffer = [0; 10];
279///
280///     // read up to 10 bytes
281///     b.read(&mut buffer)?;
282///
283///     // etc... it works exactly as a File does!
284///     Ok(())
285/// }
286/// ```
287///
288/// [`&str`]: prim@str
289// TODO: add cfg_attr to document as notable trait
290pub trait Read {
291    /// Pull some bytes from this source into the specified buffer, returning
292    /// how many bytes were read.
293    ///
294    /// This function does not provide any guarantees about whether it blocks
295    /// waiting for data, but if an object needs to block for a read and cannot,
296    /// it will typically signal this via an [`Err`] return value.
297    ///
298    /// If the return value of this method is [`Ok(n)`], then implementations must
299    /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
300    /// that the buffer `buf` has been filled in with `n` bytes of data from this
301    /// source. If `n` is `0`, then it can indicate one of two scenarios:
302    ///
303    /// 1. This reader has reached its "end of file" and will likely no longer
304    ///    be able to produce bytes. Note that this does not mean that the
305    ///    reader will *always* no longer be able to produce bytes. As an example,
306    ///    on Linux, this method will call the `recv` syscall for a [`TcpStream`],
307    ///    where returning zero indicates the connection was shut down correctly. While
308    ///    for [`File`], it is possible to reach the end of file and get zero as result,
309    ///    but if more data is appended to the file, future calls to `read` will return
310    ///    more data.
311    /// 2. The buffer specified was 0 bytes in length.
312    ///
313    /// It is not an error if the returned value `n` is smaller than the buffer size,
314    /// even when the reader is not at the end of the stream yet.
315    /// This may happen for example because fewer bytes are actually available right now
316    /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
317    ///
318    /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
319    /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
320    /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
321    /// `n > buf.len()`.
322    ///
323    /// No guarantees are provided about the contents of `buf` when this
324    /// function is called, implementations cannot rely on any property of the
325    /// contents of `buf` being true. It is recommended that *implementations*
326    /// only write data to `buf` instead of reading its contents.
327    ///
328    /// Correspondingly, however, *callers* of this method must not assume any guarantees
329    /// about how the implementation uses `buf`. The trait is safe to implement,
330    /// so it is possible that the code that's supposed to write to the buffer might also read
331    /// from it. It is your responsibility to make sure that `buf` is initialized
332    /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
333    /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
334    ///
335    /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
336    ///
337    /// # Errors
338    ///
339    /// If this function encounters any form of I/O or other error, an error
340    /// variant will be returned. If an error is returned then it must be
341    /// guaranteed that no bytes were read.
342    ///
343    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
344    /// operation should be retried if there is nothing else to do.
345    ///
346    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
347    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
348
349    /// Like `read`, except that it reads into a slice of buffers.
350    ///
351    /// Data is copied to fill each buffer in order, with the final buffer
352    /// written to possibly being only partially filled. This method must
353    /// behave equivalently to a single call to `read` with concatenated
354    /// buffers.
355    ///
356    /// The default implementation calls `read` with either the first nonempty
357    /// buffer provided, or an empty one if none exists.
358    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
359        default_read_vectored(|b| self.read(b), bufs)
360    }
361
362    /// Determines if this `Read`er has an efficient `read_vectored`
363    /// implementation.
364    ///
365    /// If a `Read`er does not override the default `read_vectored`
366    /// implementation, code using it may want to avoid the method all together
367    /// and coalesce writes into a single buffer for higher performance.
368    ///
369    /// The default implementation returns `false`.
370    fn is_read_vectored(&self) -> bool {
371        false
372    }
373
374    /// Read all bytes until EOF in this source, placing them into `buf`.
375    ///
376    /// All bytes read from this source will be appended to the specified buffer
377    /// `buf`. This function will continuously call [`read()`] to append more data to
378    /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
379    /// non-[`ErrorKind::Interrupted`] kind.
380    ///
381    /// If successful, this function will return the total number of bytes read.
382    ///
383    /// # Errors
384    ///
385    /// If this function encounters an error of the kind
386    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
387    /// will continue.
388    ///
389    /// If any other read error is encountered then this function immediately
390    /// returns. Any bytes which have already been read will be appended to
391    /// `buf`.
392    ///
393    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
394    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
395        default_read_to_end(self, buf)
396    }
397
398    /// Read all bytes until EOF in this source, appending them to `buf`.
399    ///
400    /// If successful, this function returns the number of bytes which were read
401    /// and appended to `buf`.
402    ///
403    /// # Errors
404    ///
405    /// If the data in this stream is *not* valid UTF-8 then an error is
406    /// returned and `buf` is unchanged.
407    ///
408    /// See [`read_to_end`] for other error semantics.
409    ///
410    /// [`read_to_end`]: Read::read_to_end
411    ///
412    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
413    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
414        default_read_to_string(self, buf)
415    }
416
417    /// Read the exact number of bytes required to fill `buf`.
418    ///
419    /// This function reads as many bytes as necessary to completely fill the
420    /// specified buffer `buf`.
421    ///
422    /// No guarantees are provided about the contents of `buf` when this
423    /// function is called, implementations cannot rely on any property of the
424    /// contents of `buf` being true. It is recommended that implementations
425    /// only write data to `buf` instead of reading its contents. The
426    /// documentation on [`read`] has a more detailed explanation on this
427    /// subject.
428    ///
429    /// # Errors
430    ///
431    /// If this function encounters an error of the kind
432    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
433    /// will continue.
434    ///
435    /// If this function encounters an "end of file" before completely filling
436    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
437    /// The contents of `buf` are unspecified in this case.
438    ///
439    /// If any other read error is encountered then this function immediately
440    /// returns. The contents of `buf` are unspecified in this case.
441    ///
442    /// If this function returns an error, it is unspecified how many bytes it
443    /// has read, but it will never read more than would be necessary to
444    /// completely fill the buffer.
445    ///
446    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
447    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
448        default_read_exact(self, buf)
449    }
450
451    /// Pull some bytes from this source into the specified buffer.
452    ///
453    /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
454    /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
455    ///
456    /// The default implementation delegates to `read`.
457    fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
458        default_read_buf(|b| self.read(b), buf)
459    }
460
461    /// Read the exact number of bytes required to fill `buf`.
462    ///
463    /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
464    /// allow use with uninitialized buffers.
465    fn read_buf_exact(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
466        while buf.remaining() > 0 {
467            let prev_filled = buf.filled().len();
468            match self.read_buf(buf) {
469                Ok(()) => {}
470                Err(e) if e.kind() == ErrorKind::Interrupted => continue,
471                Err(e) => return Err(e),
472            }
473
474            if buf.filled().len() == prev_filled {
475                return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
476            }
477        }
478
479        Ok(())
480    }
481
482    /// Creates a "by reference" adaptor for this instance of `Read`.
483    ///
484    /// The returned adapter also implements `Read` and will simply borrow this
485    /// current reader.
486    ///
487    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
488    fn by_ref(&mut self) -> &mut Self
489    where
490        Self: Sized,
491    {
492        self
493    }
494
495    /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
496    ///
497    /// The returned type implements [`Iterator`] where the [`Item`] is
498    /// <code>[Result]<[u8], [io::Error]></code>.
499    /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
500    /// otherwise. EOF is mapped to returning [`None`] from this iterator.
501    ///
502    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
503    fn bytes(self) -> Bytes<Self>
504    where
505        Self: Sized,
506    {
507        Bytes { inner: self }
508    }
509
510    /// Creates an adapter which will chain this stream with another.
511    ///
512    /// The returned `Read` instance will first read all bytes from this object
513    /// until EOF is encountered. Afterwards the output is equivalent to the
514    /// output of `next`.
515    ///
516    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
517    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
518    where
519        Self: Sized,
520    {
521        Chain { first: self, second: next, done_first: false }
522    }
523
524    /// Creates an adapter which will read at most `limit` bytes from it.
525    ///
526    /// This function returns a new instance of `Read` which will read at most
527    /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
528    /// read errors will not count towards the number of bytes read and future
529    /// calls to [`read()`] may succeed.
530    ///
531    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
532    fn take(self, limit: u64) -> Take<Self>
533    where
534        Self: Sized,
535    {
536        Take { inner: self, limit }
537    }
538}
539
540/// Read all bytes from a [reader][Read] into a new [`String`].
541///
542/// This is a convenience function for [`Read::read_to_string`]. Using this
543/// function avoids having to create a variable first and provides more type
544/// safety since you can only get the buffer out if there were no errors. (If you
545/// use [`Read::read_to_string`] you have to remember to check whether the read
546/// succeeded because otherwise your buffer will be empty or only partially full.)
547///
548/// # Performance
549///
550/// The downside of this function's increased ease of use and type safety is
551/// that it gives you less control over performance. For example, you can't
552/// pre-allocate memory like you can using [`String::with_capacity`] and
553/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
554/// occurs while reading.
555///
556/// In many cases, this function's performance will be adequate and the ease of use
557/// and type safety tradeoffs will be worth it. However, there are cases where you
558/// need more control over performance, and in those cases you should definitely use
559/// [`Read::read_to_string`] directly.
560///
561/// Note that in some special cases, such as when reading files, this function will
562/// pre-allocate memory based on the size of the input it is reading. In those
563/// cases, the performance should be as good as if you had used
564/// [`Read::read_to_string`] with a manually pre-allocated buffer.
565///
566/// # Errors
567///
568/// This function forces you to handle errors because the output (the `String`)
569/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
570/// that can occur. If any error occurs, you will get an [`Err`], so you
571/// don't have to worry about your buffer being empty or partially full.
572///
573/// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE STDIN -->
574pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
575    let mut buf = String::new();
576    reader.read_to_string(&mut buf)?;
577    Ok(buf)
578}
579
580/// A buffer type used with `Read::read_vectored`.
581///
582/// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
583/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
584/// Windows.
585#[repr(transparent)]
586pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
587
588unsafe impl<'a> Send for IoSliceMut<'a> {}
589
590unsafe impl<'a> Sync for IoSliceMut<'a> {}
591
592impl<'a> fmt::Debug for IoSliceMut<'a> {
593    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
594        fmt::Debug::fmt(self.0.as_slice(), fmt)
595    }
596}
597
598impl<'a> IoSliceMut<'a> {
599    /// Creates a new `IoSliceMut` wrapping a byte slice.
600    ///
601    /// # Panics
602    ///
603    /// Panics on Windows if the slice is larger than 4GB.
604    #[inline]
605    pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
606        IoSliceMut(sys::io::IoSliceMut::new(buf))
607    }
608
609    /// Advance the internal cursor of the slice.
610    ///
611    /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
612    /// multiple buffers.
613    ///
614    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
615    /// # Example code
616    ///
617    /// ```
618    /// use core::ops::Deref;
619    /// use portable_io::IoSliceMut;
620    ///
621    /// let mut data = [1; 8];
622    /// let mut buf = IoSliceMut::new(&mut data);
623    ///
624    /// // Mark 3 bytes as read.
625    /// buf.advance(3);
626    /// assert_eq!(buf.deref(), [1; 5].as_ref());
627    /// ```
628    #[inline]
629    pub fn advance(&mut self, n: usize) {
630        self.0.advance(n)
631    }
632
633    /// Advance the internal cursor of the slices.
634    ///
635    /// # Notes
636    ///
637    /// Elements in the slice may be modified if the cursor is not advanced to
638    /// the end of the slice. For example if we have a slice of buffers with 2
639    /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
640    /// the first `IoSliceMut` will be untouched however the second will be
641    /// modified to remove the first 2 bytes (10 - 8).
642    ///
643    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
644    /// # Example code
645    ///
646    /// ```
647    /// use core::ops::Deref;
648    /// use portable_io::IoSliceMut;
649    ///
650    /// let mut buf1 = [1; 8];
651    /// let mut buf2 = [2; 16];
652    /// let mut buf3 = [3; 8];
653    /// let mut bufs = &mut [
654    ///     IoSliceMut::new(&mut buf1),
655    ///     IoSliceMut::new(&mut buf2),
656    ///     IoSliceMut::new(&mut buf3),
657    /// ][..];
658    ///
659    /// // Mark 10 bytes as read.
660    /// IoSliceMut::advance_slices(&mut bufs, 10);
661    /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
662    /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
663    /// ```
664    #[inline]
665    pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
666        // Number of buffers to remove.
667        let mut remove = 0;
668        // Total length of all the to be removed buffers.
669        let mut accumulated_len = 0;
670        for buf in bufs.iter() {
671            if accumulated_len + buf.len() > n {
672                break;
673            } else {
674                accumulated_len += buf.len();
675                remove += 1;
676            }
677        }
678
679        *bufs = &mut replace(bufs, &mut [])[remove..];
680        if !bufs.is_empty() {
681            bufs[0].advance(n - accumulated_len)
682        }
683    }
684}
685
686impl<'a> Deref for IoSliceMut<'a> {
687    type Target = [u8];
688
689    #[inline]
690    fn deref(&self) -> &[u8] {
691        self.0.as_slice()
692    }
693}
694
695impl<'a> DerefMut for IoSliceMut<'a> {
696    #[inline]
697    fn deref_mut(&mut self) -> &mut [u8] {
698        self.0.as_mut_slice()
699    }
700}
701
702/// A buffer type used with `Write::write_vectored`.
703///
704/// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
705/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
706/// Windows.
707#[derive(Copy, Clone)]
708#[repr(transparent)]
709pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
710
711unsafe impl<'a> Send for IoSlice<'a> {}
712
713unsafe impl<'a> Sync for IoSlice<'a> {}
714
715impl<'a> fmt::Debug for IoSlice<'a> {
716    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
717        fmt::Debug::fmt(self.0.as_slice(), fmt)
718    }
719}
720
721impl<'a> IoSlice<'a> {
722    /// Creates a new `IoSlice` wrapping a byte slice.
723    ///
724    /// # Panics
725    ///
726    /// Panics on Windows if the slice is larger than 4GB.
727    #[must_use]
728    #[inline]
729    pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
730        IoSlice(sys::io::IoSlice::new(buf))
731    }
732
733    /// Advance the internal cursor of the slice.
734    ///
735    /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
736    /// buffers.
737    ///
738    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
739    /// # Example code
740    ///
741    /// ```
742    /// use core::ops::Deref;
743    /// use portable_io::IoSlice;
744    ///
745    /// let mut data = [1; 8];
746    /// let mut buf = IoSlice::new(&mut data);
747    ///
748    /// // Mark 3 bytes as read.
749    /// buf.advance(3);
750    /// assert_eq!(buf.deref(), [1; 5].as_ref());
751    /// ```
752    #[inline]
753    pub fn advance(&mut self, n: usize) {
754        self.0.advance(n)
755    }
756
757    /// Advance the internal cursor of the slices.
758    ///
759    /// # Notes
760    ///
761    /// Elements in the slice may be modified if the cursor is not advanced to
762    /// the end of the slice. For example if we have a slice of buffers with 2
763    /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
764    /// first `IoSlice` will be untouched however the second will be modified to
765    /// remove the first 2 bytes (10 - 8).
766    ///
767    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
768    /// # Example code
769    ///
770    /// ```
771    /// use core::ops::Deref;
772    /// use portable_io::IoSlice;
773    ///
774    /// let buf1 = [1; 8];
775    /// let buf2 = [2; 16];
776    /// let buf3 = [3; 8];
777    /// let mut bufs = &mut [
778    ///     IoSlice::new(&buf1),
779    ///     IoSlice::new(&buf2),
780    ///     IoSlice::new(&buf3),
781    /// ][..];
782    ///
783    /// // Mark 10 bytes as written.
784    /// IoSlice::advance_slices(&mut bufs, 10);
785    /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
786    /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
787    #[inline]
788    pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
789        // Number of buffers to remove.
790        let mut remove = 0;
791        // Total length of all the to be removed buffers.
792        let mut accumulated_len = 0;
793        for buf in bufs.iter() {
794            if accumulated_len + buf.len() > n {
795                break;
796            } else {
797                accumulated_len += buf.len();
798                remove += 1;
799            }
800        }
801
802        *bufs = &mut replace(bufs, &mut [])[remove..];
803        if !bufs.is_empty() {
804            bufs[0].advance(n - accumulated_len)
805        }
806    }
807}
808
809impl<'a> Deref for IoSlice<'a> {
810    type Target = [u8];
811
812    #[inline]
813    fn deref(&self) -> &[u8] {
814        self.0.as_slice()
815    }
816}
817
818/// A trait for objects which are byte-oriented sinks.
819///
820/// Implementors of the `Write` trait are sometimes called 'writers'.
821///
822/// Writers are defined by two required methods, [`write`] and [`flush`]:
823///
824/// * The [`write`] method will attempt to write some data into the object,
825///   returning how many bytes were successfully written.
826///
827/// * The [`flush`] method is useful for adapters and explicit buffers
828///   themselves for ensuring that all buffered data has been pushed out to the
829///   'true sink'.
830///
831/// Writers are intended to be composable with one another. Many implementors
832/// throughout [`std::io`] take and provide types which implement the `Write`
833/// trait.
834///
835/// [`write`]: Write::write
836/// [`flush`]: Write::flush
837/// [`std::io`]: self
838///
839/// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
840///
841/// The trait also provides convenience methods like [`write_all`], which calls
842/// `write` in a loop until its entire input has been written.
843///
844/// [`write_all`]: Write::write_all
845// TODO: add cfg_attr to document as notable trait
846pub trait Write {
847    /// Write a buffer into this writer, returning how many bytes were written.
848    ///
849    /// This function will attempt to write the entire contents of `buf`, but
850    /// the entire write might not succeed, or the write may also generate an
851    /// error. A call to `write` represents *at most one* attempt to write to
852    /// any wrapped object.
853    ///
854    /// Calls to `write` are not guaranteed to block waiting for data to be
855    /// written, and a write which would otherwise block can be indicated through
856    /// an [`Err`] variant.
857    ///
858    /// If the return value is [`Ok(n)`] then it must be guaranteed that
859    /// `n <= buf.len()`. A return value of `0` typically means that the
860    /// underlying object is no longer able to accept bytes and will likely not
861    /// be able to in the future as well, or that the buffer provided is empty.
862    ///
863    /// # Errors
864    ///
865    /// Each call to `write` may generate an I/O error indicating that the
866    /// operation could not be completed. If an error is returned then no bytes
867    /// in the buffer were written to this writer.
868    ///
869    /// It is **not** considered an error if the entire buffer could not be
870    /// written to this writer.
871    ///
872    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
873    /// write operation should be retried if there is nothing else to do.
874    ///
875    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
876    ///
877    /// [`Ok(n)`]: Ok
878    fn write(&mut self, buf: &[u8]) -> Result<usize>;
879
880    /// Like [`write`], except that it writes from a slice of buffers.
881    ///
882    /// Data is copied from each buffer in order, with the final buffer
883    /// read from possibly being only partially consumed. This method must
884    /// behave as a call to [`write`] with the buffers concatenated would.
885    ///
886    /// The default implementation calls [`write`] with either the first nonempty
887    /// buffer provided, or an empty one if none exists.
888    ///
889    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
890    ///
891    /// [`write`]: Write::write
892    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
893        default_write_vectored(|b| self.write(b), bufs)
894    }
895
896    /// Determines if this `Write`r has an efficient [`write_vectored`]
897    /// implementation.
898    ///
899    /// If a `Write`r does not override the default [`write_vectored`]
900    /// implementation, code using it may want to avoid the method all together
901    /// and coalesce writes into a single buffer for higher performance.
902    ///
903    /// The default implementation returns `false`.
904    ///
905    /// [`write_vectored`]: Write::write_vectored
906    fn is_write_vectored(&self) -> bool {
907        false
908    }
909
910    /// Flush this output stream, ensuring that all intermediately buffered
911    /// contents reach their destination.
912    ///
913    /// # Errors
914    ///
915    /// It is considered an error if not all bytes could be written due to
916    /// I/O errors or EOF being reached.
917    ///
918    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
919    fn flush(&mut self) -> Result<()>;
920
921    /// Attempts to write an entire buffer into this writer.
922    ///
923    /// This method will continuously call [`write`] until there is no more data
924    /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
925    /// returned. This method will not return until the entire buffer has been
926    /// successfully written or such an error occurs. The first error that is
927    /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
928    /// returned.
929    ///
930    /// If the buffer contains no data, this will never call [`write`].
931    ///
932    /// # Errors
933    ///
934    /// This function will return the first error of
935    /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
936    ///
937    /// [`write`]: Write::write
938    ///
939    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
940    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
941        while !buf.is_empty() {
942            match self.write(buf) {
943                Ok(0) => {
944                    return Err(Error::new_const(
945                        ErrorKind::WriteZero,
946                        &"failed to write whole buffer",
947                    ));
948                }
949                Ok(n) => buf = &buf[n..],
950                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
951                Err(e) => return Err(e),
952            }
953        }
954        Ok(())
955    }
956
957    /// Attempts to write multiple buffers into this writer.
958    ///
959    /// This method will continuously call [`write_vectored`] until there is no
960    /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
961    /// kind is returned. This method will not return until all buffers have
962    /// been successfully written or such an error occurs. The first error that
963    /// is not of [`ErrorKind::Interrupted`] kind generated from this method
964    /// will be returned.
965    ///
966    /// If the buffer contains no data, this will never call [`write_vectored`].
967    ///
968    /// # Notes
969    ///
970    /// Unlike [`write_vectored`], this takes a *mutable* reference to
971    /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
972    /// modify the slice to keep track of the bytes already written.
973    ///
974    /// Once this function returns, the contents of `bufs` are unspecified, as
975    /// this depends on how many calls to [`write_vectored`] were necessary. It is
976    /// best to understand this function as taking ownership of `bufs` and to
977    /// not use `bufs` afterwards. The underlying buffers, to which the
978    /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
979    /// can be reused.
980    ///
981    /// [`write_vectored`]: Write::write_vectored
982    ///
983    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
984    /// # Example code
985    ///
986    /// ```
987    /// # fn main() -> portable_io::Result<()> {
988    ///
989    /// use portable_io::{Write, IoSlice};
990    ///
991    /// let mut writer = Vec::new();
992    /// let bufs = &mut [
993    ///     IoSlice::new(&[1]),
994    ///     IoSlice::new(&[2, 3]),
995    ///     IoSlice::new(&[4, 5, 6]),
996    /// ];
997    ///
998    /// writer.write_all_vectored(bufs)?;
999    /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1000    ///
1001    /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1002    /// # Ok(()) }
1003    /// ```
1004    fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1005        // Guarantee that bufs is empty if it contains no data,
1006        // to avoid calling write_vectored if there is no data to be written.
1007        IoSlice::advance_slices(&mut bufs, 0);
1008        while !bufs.is_empty() {
1009            match self.write_vectored(bufs) {
1010                Ok(0) => {
1011                    return Err(Error::new_const(
1012                        ErrorKind::WriteZero,
1013                        &"failed to write whole buffer",
1014                    ));
1015                }
1016                Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1017                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1018                Err(e) => return Err(e),
1019            }
1020        }
1021        Ok(())
1022    }
1023
1024    /// Writes a formatted string into this writer, returning any error
1025    /// encountered.
1026    ///
1027    /// This method is primarily used to interface with the
1028    /// [`format_args!()`] macro, and it is rare that this should
1029    /// explicitly be called. The [`write!()`] macro should be favored to
1030    /// invoke this method instead.
1031    ///
1032    /// This function internally uses the [`write_all`] method on
1033    /// this trait and hence will continuously write data so long as no errors
1034    /// are received. This also means that partial writes are not indicated in
1035    /// this signature.
1036    ///
1037    /// [`write_all`]: Write::write_all
1038    ///
1039    /// # Errors
1040    ///
1041    /// This function will return any I/O error reported while formatting.
1042    ///
1043    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1044    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1045        // Create a shim which translates a Write to a fmt::Write and saves
1046        // off I/O errors. instead of discarding them
1047        struct Adapter<'a, T: ?Sized + 'a> {
1048            inner: &'a mut T,
1049            error: Result<()>,
1050        }
1051
1052        impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1053            fn write_str(&mut self, s: &str) -> fmt::Result {
1054                match self.inner.write_all(s.as_bytes()) {
1055                    Ok(()) => Ok(()),
1056                    Err(e) => {
1057                        self.error = Err(e);
1058                        Err(fmt::Error)
1059                    }
1060                }
1061            }
1062        }
1063
1064        let mut output = Adapter { inner: self, error: Ok(()) };
1065        match fmt::write(&mut output, fmt) {
1066            Ok(()) => Ok(()),
1067            Err(..) => {
1068                // check if the error came from the underlying `Write` or not
1069                if output.error.is_err() {
1070                    output.error
1071                } else {
1072                    Err(Error::new_const(ErrorKind::Uncategorized, &"formatter error"))
1073                }
1074            }
1075        }
1076    }
1077
1078    /// Creates a "by reference" adapter for this instance of `Write`.
1079    ///
1080    /// The returned adapter also implements `Write` and will simply borrow this
1081    /// current writer.
1082    ///
1083    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1084    fn by_ref(&mut self) -> &mut Self
1085    where
1086        Self: Sized,
1087    {
1088        self
1089    }
1090}
1091
1092/// The `Seek` trait provides a cursor which can be moved within a stream of
1093/// bytes.
1094///
1095/// The stream typically has a fixed size, allowing seeking relative to either
1096/// end or the current offset.
1097///
1098/// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1099pub trait Seek {
1100    /// Seek to an offset, in bytes, in a stream.
1101    ///
1102    /// A seek beyond the end of a stream is allowed, but behavior is defined
1103    /// by the implementation.
1104    ///
1105    /// If the seek operation completed successfully,
1106    /// this method returns the new position from the start of the stream.
1107    /// That position can be used later with [`SeekFrom::Start`].
1108    ///
1109    /// # Errors
1110    ///
1111    /// Seeking can fail, for example because it might involve flushing a buffer.
1112    ///
1113    /// Seeking to a negative offset is considered an error.
1114    fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1115
1116    /// Rewind to the beginning of a stream.
1117    ///
1118    /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1119    ///
1120    /// # Errors
1121    ///
1122    /// Rewinding can fail, for example because it might involve flushing a buffer.
1123    ///
1124    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1125    fn rewind(&mut self) -> Result<()> {
1126        self.seek(SeekFrom::Start(0))?;
1127        Ok(())
1128    }
1129
1130    /// Returns the length of this stream (in bytes).
1131    ///
1132    /// This method is implemented using up to three seek operations. If this
1133    /// method returns successfully, the seek position is unchanged (i.e. the
1134    /// position before calling this method is the same as afterwards).
1135    /// However, if this method returns an error, the seek position is
1136    /// unspecified.
1137    ///
1138    /// If you need to obtain the length of *many* streams and you don't care
1139    /// about the seek position afterwards, you can reduce the number of seek
1140    /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1141    /// return value (it is also the stream length).
1142    ///
1143    /// Note that length of a stream can change over time (for example, when
1144    /// data is appended to a file). So calling this method multiple times does
1145    /// not necessarily return the same length each time.
1146    ///
1147    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1148    fn stream_len(&mut self) -> Result<u64> {
1149        let old_pos = self.stream_position()?;
1150        let len = self.seek(SeekFrom::End(0))?;
1151
1152        // Avoid seeking a third time when we were already at the end of the
1153        // stream. The branch is usually way cheaper than a seek operation.
1154        if old_pos != len {
1155            self.seek(SeekFrom::Start(old_pos))?;
1156        }
1157
1158        Ok(len)
1159    }
1160
1161    /// Returns the current seek position from the start of the stream.
1162    ///
1163    /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1164    ///
1165    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1166    fn stream_position(&mut self) -> Result<u64> {
1167        self.seek(SeekFrom::Current(0))
1168    }
1169}
1170
1171/// Enumeration of possible methods to seek within an I/O object.
1172///
1173/// It is used by the [`Seek`] trait.
1174#[derive(Copy, PartialEq, Eq, Clone, Debug)]
1175pub enum SeekFrom {
1176    /// Sets the offset to the provided number of bytes.
1177    Start(u64),
1178
1179    /// Sets the offset to the size of this object plus the specified number of
1180    /// bytes.
1181    ///
1182    /// It is possible to seek beyond the end of an object, but it's an error to
1183    /// seek before byte 0.
1184    End(i64),
1185
1186    /// Sets the offset to the current position plus the specified number of
1187    /// bytes.
1188    ///
1189    /// It is possible to seek beyond the end of an object, but it's an error to
1190    /// seek before byte 0.
1191    Current(i64),
1192}
1193
1194fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1195    let mut read = 0;
1196    loop {
1197        let (done, used) = {
1198            let available = match r.fill_buf() {
1199                Ok(n) => n,
1200                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1201                Err(e) => return Err(e),
1202            };
1203            match memchr::memchr(delim, available) {
1204                Some(i) => {
1205                    buf.extend_from_slice(&available[..=i]);
1206                    (true, i + 1)
1207                }
1208                None => {
1209                    buf.extend_from_slice(available);
1210                    (false, available.len())
1211                }
1212            }
1213        };
1214        r.consume(used);
1215        read += used;
1216        if done || used == 0 {
1217            return Ok(read);
1218        }
1219    }
1220}
1221
1222/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1223/// to perform extra ways of reading.
1224///
1225/// For example, reading line-by-line is inefficient without using a buffer, so
1226/// if you want to read by line, you'll need `BufRead`, which includes a
1227/// [`read_line`] method as well as a [`lines`] iterator.
1228///
1229/// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1230///
1231/// If you have something that implements [`Read`], you can use the [`BufReader`
1232/// type][`BufReader`] to turn it into a `BufRead`.
1233///
1234/// <!-- TODO ADD EXAMPLE THAT DOES NOT USE FS -->
1235pub trait BufRead: Read {
1236    /// Returns the contents of the internal buffer, filling it with more data
1237    /// from the inner reader if it is empty.
1238    ///
1239    /// This function is a lower-level call. It needs to be paired with the
1240    /// [`consume`] method to function properly. When calling this
1241    /// method, none of the contents will be "read" in the sense that later
1242    /// calling `read` may return the same contents. As such, [`consume`] must
1243    /// be called with the number of bytes that are consumed from this buffer to
1244    /// ensure that the bytes are never returned twice.
1245    ///
1246    /// [`consume`]: BufRead::consume
1247    ///
1248    /// An empty buffer returned indicates that the stream has reached EOF.
1249    ///
1250    /// # Errors
1251    ///
1252    /// This function will return an I/O error if the underlying reader was
1253    /// read, but returned an error.
1254    ///
1255    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE STDIN -->
1256    fn fill_buf(&mut self) -> Result<&[u8]>;
1257
1258    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1259    /// so they should no longer be returned in calls to `read`.
1260    ///
1261    /// This function is a lower-level call. It needs to be paired with the
1262    /// [`fill_buf`] method to function properly. This function does
1263    /// not perform any I/O, it simply informs this object that some amount of
1264    /// its buffer, returned from [`fill_buf`], has been consumed and should
1265    /// no longer be returned. As such, this function may do odd things if
1266    /// [`fill_buf`] isn't called before calling it.
1267    ///
1268    /// The `amt` must be `<=` the number of bytes in the buffer returned by
1269    /// [`fill_buf`].
1270    ///
1271    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
1272    /// # Example code
1273    ///
1274    /// Since `consume()` is meant to be used with [`fill_buf`],
1275    /// that method's example includes an example of `consume()`.
1276    ///
1277    /// [`fill_buf`]: BufRead::fill_buf
1278    fn consume(&mut self, amt: usize);
1279
1280    /// Check if the underlying `Read` has any data left to be read.
1281    ///
1282    /// This function may fill the buffer to check for data,
1283    /// so this functions returns `Result<bool>`, not `bool`.
1284    ///
1285    /// Default implementation calls `fill_buf` and checks that
1286    /// returned slice is empty (which means that there is no data left,
1287    /// since EOF is reached).
1288    ///
1289    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE STDIN -->
1290    fn has_data_left(&mut self) -> Result<bool> {
1291        self.fill_buf().map(|b| !b.is_empty())
1292    }
1293
1294    /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1295    ///
1296    /// This function will read bytes from the underlying stream until the
1297    /// delimiter or EOF is found. Once found, all bytes up to, and including,
1298    /// the delimiter (if found) will be appended to `buf`.
1299    ///
1300    /// If successful, this function will return the total number of bytes read.
1301    ///
1302    /// This function is blocking and should be used carefully: it is possible for
1303    /// an attacker to continuously send bytes without ever sending the delimiter
1304    /// or EOF.
1305    ///
1306    /// # Errors
1307    ///
1308    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1309    /// will otherwise return any errors returned by [`fill_buf`].
1310    ///
1311    /// If an I/O error is encountered then all bytes read so far will be
1312    /// present in `buf` and its length will have been adjusted appropriately.
1313    ///
1314    /// [`fill_buf`]: BufRead::fill_buf
1315    ///
1316    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
1317    /// # Example code
1318    ///
1319    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1320    /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1321    /// in hyphen delimited segments:
1322    ///
1323    /// ```
1324    /// use portable_io::{self as io, BufRead};
1325    ///
1326    /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1327    /// let mut buf = vec![];
1328    ///
1329    /// // cursor is at 'l'
1330    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1331    ///     .expect("reading from cursor won't fail");
1332    /// assert_eq!(num_bytes, 6);
1333    /// assert_eq!(buf, b"lorem-");
1334    /// buf.clear();
1335    ///
1336    /// // cursor is at 'i'
1337    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1338    ///     .expect("reading from cursor won't fail");
1339    /// assert_eq!(num_bytes, 5);
1340    /// assert_eq!(buf, b"ipsum");
1341    /// buf.clear();
1342    ///
1343    /// // cursor is at EOF
1344    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1345    ///     .expect("reading from cursor won't fail");
1346    /// assert_eq!(num_bytes, 0);
1347    /// assert_eq!(buf, b"");
1348    /// ```
1349    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1350        read_until(self, byte, buf)
1351    }
1352
1353    /// Read all bytes until a newline (the `0xA` byte) is reached, and append
1354    /// them to the provided buffer.
1355    ///
1356    /// This function will read bytes from the underlying stream until the
1357    /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1358    /// up to, and including, the delimiter (if found) will be appended to
1359    /// `buf`.
1360    ///
1361    /// If successful, this function will return the total number of bytes read.
1362    ///
1363    /// If this function returns [`Ok(0)`], the stream has reached EOF.
1364    ///
1365    /// This function is blocking and should be used carefully: it is possible for
1366    /// an attacker to continuously send bytes without ever sending a newline
1367    /// or EOF.
1368    ///
1369    /// [`Ok(0)`]: Ok
1370    ///
1371    /// # Errors
1372    ///
1373    /// This function has the same error semantics as [`read_until`] and will
1374    /// also return an error if the read bytes are not valid UTF-8. If an I/O
1375    /// error is encountered then `buf` may contain some bytes already read in
1376    /// the event that all data read so far was valid UTF-8.
1377    ///
1378    /// [`read_until`]: BufRead::read_until
1379    ///
1380    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
1381    /// # Example code
1382    ///
1383    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1384    /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1385    ///
1386    /// ```
1387    /// use portable_io::{self as io, BufRead};
1388    ///
1389    /// let mut cursor = io::Cursor::new(b"foo\nbar");
1390    /// let mut buf = String::new();
1391    ///
1392    /// // cursor is at 'f'
1393    /// let num_bytes = cursor.read_line(&mut buf)
1394    ///     .expect("reading from cursor won't fail");
1395    /// assert_eq!(num_bytes, 4);
1396    /// assert_eq!(buf, "foo\n");
1397    /// buf.clear();
1398    ///
1399    /// // cursor is at 'b'
1400    /// let num_bytes = cursor.read_line(&mut buf)
1401    ///     .expect("reading from cursor won't fail");
1402    /// assert_eq!(num_bytes, 3);
1403    /// assert_eq!(buf, "bar");
1404    /// buf.clear();
1405    ///
1406    /// // cursor is at EOF
1407    /// let num_bytes = cursor.read_line(&mut buf)
1408    ///     .expect("reading from cursor won't fail");
1409    /// assert_eq!(num_bytes, 0);
1410    /// assert_eq!(buf, "");
1411    /// ```
1412    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1413        // Note that we are not calling the `.read_until` method here, but
1414        // rather our hardcoded implementation. For more details as to why, see
1415        // the comments in `read_to_end`.
1416        unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
1417    }
1418
1419    /// Returns an iterator over the contents of this reader split on the byte
1420    /// `byte`.
1421    ///
1422    /// The iterator returned from this function will return instances of
1423    /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
1424    /// the delimiter byte at the end.
1425    ///
1426    /// This function will yield errors whenever [`read_until`] would have
1427    /// also yielded an error.
1428    ///
1429    /// [io::Result]: self::Result "io::Result"
1430    /// [`read_until`]: BufRead::read_until
1431    ///
1432    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
1433    /// # Example code
1434    ///
1435    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1436    /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1437    /// segments in a byte slice
1438    ///
1439    /// ```
1440    /// use portable_io::{self as io, BufRead};
1441    ///
1442    /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1443    ///
1444    /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1445    /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1446    /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1447    /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1448    /// assert_eq!(split_iter.next(), None);
1449    /// ```
1450    fn split(self, byte: u8) -> Split<Self>
1451    where
1452        Self: Sized,
1453    {
1454        Split { buf: self, delim: byte }
1455    }
1456
1457    /// Returns an iterator over the lines of this reader.
1458    ///
1459    /// The iterator returned from this function will yield instances of
1460    /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
1461    /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
1462    ///
1463    /// [io::Result]: self::Result "io::Result"
1464    ///
1465    /// <!-- UPDATED TITLE in this fork to avoid singular vs plural issue - TODO PROPOSE UPDATE IN UPSTREAM RUST -->
1466    /// # Example code
1467    ///
1468    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1469    /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1470    /// slice.
1471    ///
1472    /// ```
1473    /// use portable_io::{self as io, BufRead};
1474    ///
1475    /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1476    ///
1477    /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1478    /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1479    /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1480    /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1481    /// assert_eq!(lines_iter.next(), None);
1482    /// ```
1483    ///
1484    /// # Errors
1485    ///
1486    /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1487    fn lines(self) -> Lines<Self>
1488    where
1489        Self: Sized,
1490    {
1491        Lines { buf: self }
1492    }
1493}
1494
1495/// Adapter to chain together two readers.
1496///
1497/// This struct is generally created by calling [`chain`] on a reader.
1498/// Please see the documentation of [`chain`] for more details.
1499///
1500/// [`chain`]: Read::chain
1501#[derive(Debug)]
1502pub struct Chain<T, U> {
1503    first: T,
1504    second: U,
1505    done_first: bool,
1506}
1507
1508impl<T, U> Chain<T, U> {
1509    /// Consumes the `Chain`, returning the wrapped readers.
1510    ///
1511    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1512    pub fn into_inner(self) -> (T, U) {
1513        (self.first, self.second)
1514    }
1515
1516    /// Gets references to the underlying readers in this `Chain`.
1517    ///
1518    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1519    pub fn get_ref(&self) -> (&T, &U) {
1520        (&self.first, &self.second)
1521    }
1522
1523    /// Gets mutable references to the underlying readers in this `Chain`.
1524    ///
1525    /// Care should be taken to avoid modifying the internal I/O state of the
1526    /// underlying readers as doing so may corrupt the internal state of this
1527    /// `Chain`.
1528    ///
1529    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1530    pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1531        (&mut self.first, &mut self.second)
1532    }
1533}
1534
1535impl<T: Read, U: Read> Read for Chain<T, U> {
1536    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1537        if !self.done_first {
1538            match self.first.read(buf)? {
1539                0 if !buf.is_empty() => self.done_first = true,
1540                n => return Ok(n),
1541            }
1542        }
1543        self.second.read(buf)
1544    }
1545
1546    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1547        if !self.done_first {
1548            match self.first.read_vectored(bufs)? {
1549                0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1550                n => return Ok(n),
1551            }
1552        }
1553        self.second.read_vectored(bufs)
1554    }
1555}
1556
1557impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1558    fn fill_buf(&mut self) -> Result<&[u8]> {
1559        if !self.done_first {
1560            match self.first.fill_buf()? {
1561                buf if buf.is_empty() => {
1562                    self.done_first = true;
1563                }
1564                buf => return Ok(buf),
1565            }
1566        }
1567        self.second.fill_buf()
1568    }
1569
1570    fn consume(&mut self, amt: usize) {
1571        if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
1572    }
1573}
1574
1575#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1576impl<T, U> SizeHint for Chain<T, U> {
1577    #[inline]
1578    fn lower_bound(&self) -> usize {
1579        SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
1580    }
1581
1582    #[inline]
1583    fn upper_bound(&self) -> Option<usize> {
1584        match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
1585            (Some(first), Some(second)) => first.checked_add(second),
1586            _ => None,
1587        }
1588    }
1589}
1590
1591/// Reader adapter which limits the bytes read from an underlying reader.
1592///
1593/// This struct is generally created by calling [`take`] on a reader.
1594/// Please see the documentation of [`take`] for more details.
1595///
1596/// [`take`]: Read::take
1597#[derive(Debug)]
1598pub struct Take<T> {
1599    inner: T,
1600    limit: u64,
1601}
1602
1603impl<T> Take<T> {
1604    /// Returns the number of bytes that can be read before this instance will
1605    /// return EOF.
1606    ///
1607    /// # Note
1608    ///
1609    /// This instance may reach `EOF` after reading fewer bytes than indicated by
1610    /// this method if the underlying [`Read`] instance reaches EOF.
1611    ///
1612    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1613    pub fn limit(&self) -> u64 {
1614        self.limit
1615    }
1616
1617    /// Sets the number of bytes that can be read before this instance will
1618    /// return EOF. This is the same as constructing a new `Take` instance, so
1619    /// the amount of bytes read and the previous limit value don't matter when
1620    /// calling this method.
1621    ///
1622    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1623    pub fn set_limit(&mut self, limit: u64) {
1624        self.limit = limit;
1625    }
1626
1627    /// Consumes the `Take`, returning the wrapped reader.
1628    ///
1629    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1630    pub fn into_inner(self) -> T {
1631        self.inner
1632    }
1633
1634    /// Gets a reference to the underlying reader.
1635    ///
1636    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1637    pub fn get_ref(&self) -> &T {
1638        &self.inner
1639    }
1640
1641    /// Gets a mutable reference to the underlying reader.
1642    ///
1643    /// Care should be taken to avoid modifying the internal I/O state of the
1644    /// underlying reader as doing so may corrupt the internal limit of this
1645    /// `Take`.
1646    ///
1647    /// <!-- TODO ADD EXAMPLE CODE THAT DOES NOT USE FS -->
1648    pub fn get_mut(&mut self) -> &mut T {
1649        &mut self.inner
1650    }
1651}
1652
1653impl<T: Read> Read for Take<T> {
1654    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1655        // Don't call into inner reader at all at EOF because it may still block
1656        if self.limit == 0 {
1657            return Ok(0);
1658        }
1659
1660        let max = cmp::min(buf.len() as u64, self.limit) as usize;
1661        let n = self.inner.read(&mut buf[..max])?;
1662        self.limit -= n as u64;
1663        Ok(n)
1664    }
1665
1666    fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
1667        // Don't call into inner reader at all at EOF because it may still block
1668        if self.limit == 0 {
1669            return Ok(());
1670        }
1671
1672        let prev_filled = buf.filled_len();
1673
1674        if self.limit <= buf.remaining() as u64 {
1675            // if we just use an as cast to convert, limit may wrap around on a 32 bit target
1676            let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
1677
1678            let extra_init = cmp::min(limit as usize, buf.initialized_len() - buf.filled_len());
1679
1680            // SAFETY: no uninit data is written to ibuf
1681            let ibuf = unsafe { &mut buf.unfilled_mut()[..limit] };
1682
1683            let mut sliced_buf = ReadBuf::uninit(ibuf);
1684
1685            // SAFETY: extra_init bytes of ibuf are known to be initialized
1686            unsafe {
1687                sliced_buf.assume_init(extra_init);
1688            }
1689
1690            self.inner.read_buf(&mut sliced_buf)?;
1691
1692            let new_init = sliced_buf.initialized_len();
1693            let filled = sliced_buf.filled_len();
1694
1695            // sliced_buf / ibuf must drop here
1696
1697            // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
1698            unsafe {
1699                buf.assume_init(new_init);
1700            }
1701
1702            buf.add_filled(filled);
1703
1704            self.limit -= filled as u64;
1705        } else {
1706            self.inner.read_buf(buf)?;
1707
1708            //inner may unfill
1709            self.limit -= buf.filled_len().saturating_sub(prev_filled) as u64;
1710        }
1711
1712        Ok(())
1713    }
1714}
1715
1716impl<T: BufRead> BufRead for Take<T> {
1717    fn fill_buf(&mut self) -> Result<&[u8]> {
1718        // Don't call into inner reader at all at EOF because it may still block
1719        if self.limit == 0 {
1720            return Ok(&[]);
1721        }
1722
1723        let buf = self.inner.fill_buf()?;
1724        let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1725        Ok(&buf[..cap])
1726    }
1727
1728    fn consume(&mut self, amt: usize) {
1729        // Don't let callers reset the limit by passing an overlarge value
1730        let amt = cmp::min(amt as u64, self.limit) as usize;
1731        self.limit -= amt as u64;
1732        self.inner.consume(amt);
1733    }
1734}
1735
1736#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1737impl<T> SizeHint for Take<T> {
1738    #[inline]
1739    fn lower_bound(&self) -> usize {
1740        cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
1741    }
1742
1743    #[inline]
1744    fn upper_bound(&self) -> Option<usize> {
1745        match SizeHint::upper_bound(&self.inner) {
1746            Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
1747            None => self.limit.try_into().ok(),
1748        }
1749    }
1750}
1751
1752/// An iterator over `u8` values of a reader.
1753///
1754/// This struct is generally created by calling [`bytes`] on a reader.
1755/// Please see the documentation of [`bytes`] for more details.
1756///
1757/// [`bytes`]: Read::bytes
1758#[derive(Debug)]
1759pub struct Bytes<R> {
1760    inner: R,
1761}
1762
1763impl<R: Read> Iterator for Bytes<R> {
1764    type Item = Result<u8>;
1765
1766    fn next(&mut self) -> Option<Result<u8>> {
1767        let mut byte = 0;
1768        loop {
1769            return match self.inner.read(slice::from_mut(&mut byte)) {
1770                Ok(0) => None,
1771                Ok(..) => Some(Ok(byte)),
1772                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1773                Err(e) => Some(Err(e)),
1774            };
1775        }
1776    }
1777
1778    #[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1779    fn size_hint(&self) -> (usize, Option<usize>) {
1780        SizeHint::size_hint(&self.inner)
1781    }
1782}
1783
1784#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1785trait SizeHint {
1786    fn lower_bound(&self) -> usize;
1787
1788    fn upper_bound(&self) -> Option<usize>;
1789
1790    fn size_hint(&self) -> (usize, Option<usize>) {
1791        (self.lower_bound(), self.upper_bound())
1792    }
1793}
1794
1795#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1796impl<T> SizeHint for T {
1797    #[inline]
1798    default fn lower_bound(&self) -> usize {
1799        0
1800    }
1801
1802    #[inline]
1803    default fn upper_bound(&self) -> Option<usize> {
1804        None
1805    }
1806}
1807
1808#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1809impl<T> SizeHint for &mut T {
1810    #[inline]
1811    fn lower_bound(&self) -> usize {
1812        SizeHint::lower_bound(*self)
1813    }
1814
1815    #[inline]
1816    fn upper_bound(&self) -> Option<usize> {
1817        SizeHint::upper_bound(*self)
1818    }
1819}
1820
1821#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1822impl<T> SizeHint for Box<T> {
1823    #[inline]
1824    fn lower_bound(&self) -> usize {
1825        SizeHint::lower_bound(&**self)
1826    }
1827
1828    #[inline]
1829    fn upper_bound(&self) -> Option<usize> {
1830        SizeHint::upper_bound(&**self)
1831    }
1832}
1833
1834#[cfg(portable_io_unstable_all)] // unstable feature: size hint optimization (requires Rust nightly for min_specialization)
1835impl SizeHint for &[u8] {
1836    #[inline]
1837    fn lower_bound(&self) -> usize {
1838        self.len()
1839    }
1840
1841    #[inline]
1842    fn upper_bound(&self) -> Option<usize> {
1843        Some(self.len())
1844    }
1845}
1846
1847/// An iterator over the contents of an instance of `BufRead` split on a
1848/// particular byte.
1849///
1850/// This struct is generally created by calling [`split`] on a `BufRead`.
1851/// Please see the documentation of [`split`] for more details.
1852///
1853/// [`split`]: BufRead::split
1854#[derive(Debug)]
1855pub struct Split<B> {
1856    buf: B,
1857    delim: u8,
1858}
1859
1860impl<B: BufRead> Iterator for Split<B> {
1861    type Item = Result<Vec<u8>>;
1862
1863    fn next(&mut self) -> Option<Result<Vec<u8>>> {
1864        let mut buf = Vec::new();
1865        match self.buf.read_until(self.delim, &mut buf) {
1866            Ok(0) => None,
1867            Ok(_n) => {
1868                if buf[buf.len() - 1] == self.delim {
1869                    buf.pop();
1870                }
1871                Some(Ok(buf))
1872            }
1873            Err(e) => Some(Err(e)),
1874        }
1875    }
1876}
1877
1878/// An iterator over the lines of an instance of `BufRead`.
1879///
1880/// This struct is generally created by calling [`lines`] on a `BufRead`.
1881/// Please see the documentation of [`lines`] for more details.
1882///
1883/// [`lines`]: BufRead::lines
1884#[derive(Debug)]
1885pub struct Lines<B> {
1886    buf: B,
1887}
1888
1889impl<B: BufRead> Iterator for Lines<B> {
1890    type Item = Result<String>;
1891
1892    fn next(&mut self) -> Option<Result<String>> {
1893        let mut buf = String::new();
1894        match self.buf.read_line(&mut buf) {
1895            Ok(0) => None,
1896            Ok(_n) => {
1897                if buf.ends_with('\n') {
1898                    buf.pop();
1899                    if buf.ends_with('\r') {
1900                        buf.pop();
1901                    }
1902                }
1903                Some(Ok(buf))
1904            }
1905            Err(e) => Some(Err(e)),
1906        }
1907    }
1908}