TryNext

Trait TryNext 

Source
pub trait TryNext<S = ()>
where S: Default + Copy,
{ type Item; type Error; // Required method fn try_next(&mut self) -> Result<Option<Self::Item>, Self::Error>; // Provided methods fn try_collect(&mut self) -> Result<Vec<Self::Item>, Self::Error> { ... } fn stats(&self) -> S { ... } }
Expand description

Context-free, fallible producer.

A trait for types that can produce items one at a time, where fetching the next item may fail.

This trait is synchronous — each call to try_next blocks until an item is produced or an error occurs. See the module-level documentation for details and examples.

  • S - Optional stats type.

Required Associated Types§

Source

type Item

The type of items yielded by this source.

Source

type Error

The error type that may be returned when producing the next item fails.

Required Methods§

Source

fn try_next(&mut self) -> Result<Option<Self::Item>, Self::Error>

Attempts to produce the next item from the source.

Returns:

  • Ok(Some(item)) — a new item was produced,
  • Ok(None) — the source is exhausted,
  • Err(e) — iteration failed with an error.

Provided Methods§

Source

fn try_collect(&mut self) -> Result<Vec<Self::Item>, Self::Error>

Collects all remaining items into a Vec.

The method repeatedly calls try_next until None or an error is returned, collecting all successful items into a vector.
If any call returns Err(e), iteration stops immediately and that error is returned.

§Feature

This method is only available when the alloc feature is enabled.

Source

fn stats(&self) -> S

Implementations on Foreign Types§

Source§

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

Implements TryNext for BufReader.

This version does not use a context, and simply reads the next byte sequentially from the buffer.

§Example

use std::io::BufReader;
use try_next::TryNext;

let data = b"hi";
let mut reader = BufReader::new(&data[..]);

assert_eq!(reader.try_next().unwrap(), Some(b'h'));
assert_eq!(reader.try_next().unwrap(), Some(b'i'));
assert_eq!(reader.try_next().unwrap(), None);
Source§

type Item = u8

The type of item yielded — a single u8 byte.

Source§

type Error = Error

The error type produced — io::Error.

Source§

fn try_next(&mut self) -> Result<Option<Self::Item>, Self::Error>

Attempts to read the next byte from the buffer.

§Returns
  • Ok(Some(byte)) if a byte was successfully read.
  • Ok(None) if EOF was reached.
  • Err(e) if an I/O error occurred.

Implementors§