Trait eos_rs::api::io::Read

source ·
pub trait Read {
    // Required method
    fn read(&mut self, dst: &mut [u8]) -> Result<usize, Error>;

    // Provided methods
    fn read_vectored(
        &mut self,
        bufs: &mut [IoSliceMut<'_>]
    ) -> Result<usize, Error> { ... }
    fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error> { ... }
    fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error> { ... }
    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> { ... }
    fn by_ref(&mut self) -> &mut Self
       where Self: Sized { ... }
    fn bytes(self) -> Bytes<Self>
       where Self: Sized { ... }
    fn chain<R>(self, next: R) -> Chain<Self, R>
       where R: Read,
             Self: Sized { ... }
    fn take(self, limit: u64) -> Take<Self>
       where Self: Sized { ... }
}
Expand description

The Read trait allows for reading bytes from a source.

Implementors of the Read trait are called ‘readers’.

Readers are defined by one required method, read(). Each call to read() will attempt to pull bytes from this source into a provided buffer. A number of other methods are implemented in terms of read(), giving implementors a number of ways to read bytes while only needing to implement a single method.

Examples

Read from &str because [&[u8]][prim@slice] implements Read:

use acid_io::prelude::*;

let mut b = "This string will be read".as_bytes();
let mut buffer = [0; 10];

// read up to 10 bytes
b.read(&mut buffer)?;

Required Methods§

source

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

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

This function does not provide any guarantees about whether it blocks waiting for data, but if an object needs to block for a read 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 <= dst.len(). A nonzero n value indicates that the buffer dst 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 reader has reached its “end of file” and will likely no longer be able to produce bytes. Note that this does not mean that the reader will always no longer be able to produce bytes.
  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 reader 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 read() was interrupted by a signal.

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

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

Correspondingly, however, callers of this method must not assume any guarantees about how the implementation uses dst. The trait is safe to implement, so it is possible that the code that’s supposed to write to the buffer might also read from it. It is your responsibility to make sure that dst is initialized before calling read. Calling read with an uninitialized dst (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 read.

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

Examples
use acid_io::Read;

let src = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut dst = [0u8; 3];

let mut r = &src[..];

// read up to 3 bytes
let n = r.read(&mut dst[..])?;

assert_eq!(dst, [1, 2, 3]);

Provided Methods§

source

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

Like read, except that it reads 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 read with concatenated buffers.

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

source

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

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

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

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

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 read error is encountered then this function immediately returns. Any bytes which have already been read will be appended to buf.

Examples
use acid_io::prelude::*;

let data = b"Let's read this entire buffer!";

let mut src = &data[..];
let mut dst = Vec::new();
src.read_to_end(&mut dst)?;

assert_eq!(&data[..], &dst);
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.

If successful, this function returns the number of bytes which were read 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 read_to_end for other error semantics.

Examples
use acid_io::prelude::*;

let mut buffer = String::new();

let mut valid = &b"Some valid UTF-8"[..];
valid.read_to_string(&mut buffer)?;

let mut invalid = &b"\xFF\xFF\xFF\xFF"[..];
assert!(invalid.read_to_string(&mut buffer).is_err());

assert_eq!(buffer, "Some valid UTF-8");
source

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

Read the exact number of bytes required to fill buf.

This function reads 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; 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 reading its contents. The documentation on read 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 read 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 read, but it will never read more than would be necessary to completely fill the buffer.

Examples
use acid_io::Read;

let src = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut dst = [0u8; 3];

let mut r = &src[..];

// read exactly 3 bytes
let n = r.read_exact(&mut dst[..])?;

assert_eq!(dst, [1, 2, 3]);
source

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

Creates a “by reference” adapter for this instance of Read.

The returned adapter also implements Read and will simply borrow this current reader.

Examples
use acid_io::prelude::*;

let bytes = [1, 1, 2, 3, 5, 8, 13, 21];
let mut r = &bytes[..];

{ // Use the reader by reference.
    let mut dst = [0u8; 4];
    let mut r2 = r.by_ref();
    r2.read(&mut dst)?;
    assert_eq!(dst, [1, 1, 2, 3]);
} // Drop the mutable borrow on the reader.

let mut dst = [0u8; 4];
r.read(&mut dst)?;
assert_eq!(dst, [5, 8, 13, 21]);
source

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

Transforms this Read instance to an [Iterator] over its bytes.

The returned type implements [Iterator] where the Item is Result<u8>; The yielded item is [Ok] if a byte was successfully read and [Err] otherwise. EOF is mapped to returning [None] from this iterator.

Examples
use acid_io::prelude::*;

let mut it = "Hi!".as_bytes().bytes();

assert_eq!(it.next().transpose()?, Some(b'H'));
assert_eq!(it.next().transpose()?, Some(b'i'));
assert_eq!(it.next().transpose()?, Some(b'!'));
assert_eq!(it.next().transpose()?, None);
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.

The returned Read instance will first read all bytes from this object until EOF is encountered. Afterwards the output is equivalent to the output of next.

Examples
use acid_io::prelude::*;
use acid_io::Cursor;

let mut first = &b"Hello, ";
let mut second = Cursor::new("world!");

let mut s = String::new();
first.chain(second).read_to_string(&mut s)?;

assert_eq!(s, "Hello, world!");
source

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

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

This function returns a new instance of Read which will read at most limit bytes, after which it will always return EOF (Ok(0)). Any read errors will not count towards the number of bytes read and future calls to read() may succeed.

Examples
use acid_io::prelude::*;

let mut r = &b"Bytes and more bytes";

// read at most five bytes
let mut handle = r.take(5);

let mut buffer = Vec::new();
handle.read_to_end(&mut buffer)?;

assert_eq!(&buffer, &b"Bytes");

Implementations on Foreign Types§

source§

impl<R> Read for Box<R, Global>where R: Read,

source§

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

source§

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

source§

impl<R> Read for &mut Rwhere R: Read,

source§

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

source§

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

source§

impl Read for &[u8]

source§

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

source§

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

source§

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

source§

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

Implementors§

source§

impl Read for Empty

source§

impl Read for Repeat

source§

impl<'a> Read for FileReader<'a>

source§

impl<R> Read for BufReader<R>where R: Read,

source§

impl<T> Read for Cursor<T>where T: AsRef<[u8]>,