Struct peekable::Peekable

source ·
pub struct Peekable<R> { /* private fields */ }
Expand description

A wrapper around an Read types to make them support peek related methods.

Implementations§

source§

impl<R> Peekable<R>

source

pub fn new(reader: R) -> Self

Creates a new peekable wrapper around the given reader.

source

pub fn with_capacity(reader: R, capacity: usize) -> Self

Creates a new peekable wrapper around the given reader with the specified capacity for the peek buffer.

source

pub fn get_mut(&mut self) -> (&[u8], &mut R)

Returns the bytes already be peeked into memory and a mutable reference to the underlying reader.

WARNING: If you invoke AsyncRead or AsyncReadExt methods on the underlying reader, may lead to unexpected read behaviors.

source

pub fn get_ref(&self) -> (&[u8], &R)

Returns the bytes already be peeked into memory and a reference to the underlying reader.

WARNING: If you invoke AsyncRead or AsyncReadExt methods on the underlying reader, may lead to unexpected read behaviors.

source

pub fn into_components(self) -> (Buffer, R)

Consumes the AsyncPeekable, returning the a vec may contain the bytes already be peeked into memory and the wrapped reader.

source§

impl<R: Read> Peekable<R>

source

pub fn peek(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were peeked.

This function does not provide any guarantees about whether it blocks waiting for data, but if an object needs to block for a peek and cannot, it will typically signal this via an Err return value.

If the return value of this method is Ok(n), then implementations must guarantee that 0 <= n <= buf.len(). A nonzero n value indicates that the buffer buf has been filled in with n bytes of data from this source. If n is 0, then it can indicate one of two scenarios:

  1. This peeker has reached its “end of file” and will likely no longer be able to produce bytes. Note that this does not mean that the peeker will always no longer be able to produce bytes. As an example, on Linux, this method will call the recv syscall for a TcpStream, where returning zero indicates the connection was shut down correctly. While for File, it is possible to reach the end of file and get zero as result, but if more data is appended to the file, future calls to peek will return more data.
  2. The buffer specified was 0 bytes in length.

It is not an error if the returned value n is smaller than the buffer size, even when the peeker is not at the end of the stream yet. This may happen for example because fewer bytes are actually available right now (e. g. being close to end-of-file) or because peek() was interrupted by a signal.

As this trait is safe to implement, callers in unsafe code cannot rely on n <= buf.len() for safety. Extra care needs to be taken when unsafe functions are used to access the peek bytes. Callers have to ensure that no unchecked out-of-bounds accesses are possible even if n > buf.len().

No guarantees are provided about the contents of buf when this function is called, so implementations cannot rely on any property of the contents of buf being true. It is recommended that implementations only write data to buf instead of peeking its contents.

Correspondingly, however, callers of this method in unsafe code must not assume any guarantees about how the implementation uses buf. The trait is safe to implement, so it is possible that the code that’s supposed to write to the buffer might also peek from it. It is your responsibility to make sure that buf is initialized before calling peek. Calling peek with an uninitialized buf (of the kind one obtains via MaybeUninit<T>) is not safe, and can lead to undefined behavior.

§Errors

If this function encounters any form of I/O or other error, an error variant will be returned. If an error is returned then it must be guaranteed that no bytes were peek.

An error of the [ErrorKind::Interrupted] kind is non-fatal and the peek operation should be retried if there is nothing else to do.

§Examples
use std::io;
use std::io::{Cursor, Read};
use peekable::PeekExt;


let mut peekable = Cursor::new([1, 2, 3, 4]).peekable();
let mut output = [0u8; 5];

let bytes = peekable.peek(&mut output[..3])?;

// This is only guaranteed to be 4 because `&[u8]` is a synchronous
// reader. In a real system you could get anywhere from 1 to
// `output.len()` bytes in a single read.
assert_eq!(bytes, 3);
assert_eq!(output, [1, 2, 3, 0, 0]);

// you can peek mutiple times

let bytes = peekable.peek(&mut output[..])?;
assert_eq!(bytes, 4);
assert_eq!(output, [1, 2, 3, 4, 0]);

// you can read after peek
let mut output = [0u8; 5];
let bytes = peekable.read(&mut output[..2])?;
assert_eq!(bytes, 2);
assert_eq!(output, [1, 2, 0, 0, 0]);

// peek after read
let mut output = [0u8; 5];
let bytes = peekable.peek(&mut output[..])?;
assert_eq!(bytes, 2);
assert_eq!(output, [3, 4, 0, 0, 0]);
source

pub fn peek_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Like peek, except that it peeks into a slice of buffers.

Data is copied to fill each buffer in order, with the final buffer written to possibly being only partially filled. This method must behave equivalently to a single call to peek with concatenated buffers.

The default implementation calls peek with either the first nonempty buffer provided, or an empty one if none exists.

source

pub fn peek_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>

Peek all bytes until EOF in this source, placing them into buf.

All bytes peek from this source will be appended to the specified buffer buf. This function will continuously call peek() to append more data to buf until peek() returns either Ok(0) or an error of non-[ErrorKind::Interrupted] kind.

If successful, this function will return the total number of bytes peek.

§Errors

If this function encounters an error of the kind [ErrorKind::Interrupted] then the error is ignored and the operation will continue.

If any other peek error is encountered then this function immediately returns. Any bytes which have alpeeky been peek will be appended to buf.

§Examples
use std::io;
use std::io::{Cursor, Read};
use peekable::PeekExt;

let mut peekable = Cursor::new([1, 2, 3, 4]).peekable();
let mut output = Vec::with_capacity(4);

let bytes = peekable.peek_to_end(&mut output)?;

assert_eq!(bytes, 4);
assert_eq!(output, vec![1, 2, 3, 4]);

// read after peek
let mut output = Vec::with_capacity(4);

let bytes = peekable.read_to_end(&mut output)?;

assert_eq!(bytes, 4);
assert_eq!(output, vec![1, 2, 3, 4]);
source

pub fn peek_to_string(&mut self, buf: &mut String) -> Result<usize>

Peek all bytes until EOF in this source, appending them to buf.

If successful, this function returns the number of bytes which were peek and appended to buf.

§Errors

If the data in this stream is not valid UTF-8 then an error is returned and buf is unchanged.

See peek_to_end for other error semantics.

§Examples
use std::io;
use std::io::{Cursor, Read};
use peekable::PeekExt;


let mut peekable = Cursor::new(&b"1234"[..]).peekable();
let mut buffer = String::with_capacity(4);

let bytes = peekable.peek_to_string(&mut buffer)?;

assert_eq!(bytes, 4);
assert_eq!(buffer, String::from("1234"));

// read after peek
let mut buffer = String::with_capacity(4);
let bytes = peekable.peek_to_string(&mut buffer)?;

assert_eq!(bytes, 4);
assert_eq!(buffer, String::from("1234"));
source

pub fn peek_exact(&mut self, buf: &mut [u8]) -> Result<()>

Peek the exact number of bytes required to fill buf.

This function peeks as many bytes as necessary to completely fill the specified buffer buf.

No guarantees are provided about the contents of buf when this function is called, so implementations cannot rely on any property of the contents of buf being true. It is recommended that implementations only write data to buf instead of peeking its contents. The documentation on [peek] has a more detailed explanation on this subject.

§Errors

If this function encounters an error of the kind ErrorKind::Interrupted then the error is ignored and the operation will continue.

If this function encounters an “end of file” before completely filling the buffer, it returns an error of the kind ErrorKind::UnexpectedEof. The contents of buf are unspecified in this case.

If any other peek error is encountered then this function immediately returns. The contents of buf are unspecified in this case.

If this function returns an error, it is unspecified how many bytes it has peek, but it will never peek more than would be necessary to completely fill the buffer.

§Examples
use std::io;
use std::io::{Cursor, Read};
use peekable::PeekExt;


let mut peekable = Cursor::new([1, 2, 3, 4]).peekable();
let mut output = [0u8; 4];

peekable.peek_exact(&mut output)?;

assert_eq!(output, [1, 2, 3, 4]);

// read after peek
let mut output = [0u8; 2];

peekable.read_exact(&mut output[..])?;

assert_eq!(output, [1, 2]);

// peek after read
let mut output = [0u8; 2];
peekable.peek_exact(&mut output)?;

assert_eq!(output, [3, 4]);
§EOF is hit before buf is filled
use std::io;
use std::io::{Cursor, Read};
use peekable::PeekExt;


let mut peekable = Cursor::new([1, 2, 3, 4]).peekable();
let mut output = [0u8; 5];

let result = peekable.peek_exact(&mut output);
assert_eq!(
  result.unwrap_err().kind(),
  std::io::ErrorKind::UnexpectedEof
);

let result = peekable.peek_exact(&mut output[..4]);
assert!(result.is_ok());
assert_eq!(output, [1, 2, 3, 4, 0]);

Trait Implementations§

source§

impl<R> From<R> for Peekable<R>

source§

fn from(reader: R) -> Self

Converts to this type from the input type.
source§

impl<R: Read> Read for Peekable<R>

source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Read the exact number of bytes required to fill buf. Read more
source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Read the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more

Auto Trait Implementations§

§

impl<R> RefUnwindSafe for Peekable<R>
where R: RefUnwindSafe,

§

impl<R> Send for Peekable<R>
where R: Send,

§

impl<R> Sync for Peekable<R>
where R: Sync,

§

impl<R> Unpin for Peekable<R>
where R: Unpin,

§

impl<R> UnwindSafe for Peekable<R>
where R: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<R> PeekExt for R
where R: Read + ?Sized,

source§

fn peekable(self) -> Peekable<Self>
where Self: Sized,

Wraps a Read type in a Peekable which provides a peek method.
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.