Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Zero-Copy Reads

This feature is available in Rust only. The Python bindings always return owned values

The IteratorRead trait provides a read() method that returns a borrowed reference instead of an owned value, avoiding one allocation per item

pub trait IteratorRead {
    type Borrowed<'a> where Self: 'a;
    type Owned: for<'a> From<Self::Borrowed<'a>>;

    fn read(&mut self) -> Result<Option<Self::Borrowed<'_>>>;
}

Borrowed vs Owned Types

IteratorBorrowedOwned
ByteIteratoru8u8
ChunkIterator&[u8]Vec<u8>
LineIterator&strString
SegmentIterator&[u8]Vec<u8>

Usage

Call read() in a loop instead of using the Iterator trait:

use preader::{IteratorRead, PReader};

let reader = PReader::default();
let mut lines = reader.lines("data.txt").build()?;

while let Some(line) = lines.read()? {
    // `line` is a &str borrowed from the iterator's internal buffer
    println!("{line}");
}

The borrowed reference is valid until the next call to read() or next(). Do not store it across iterations

When to Use This

Use read() when you process each item immediately without collecting them. The standard Iterator trait (via next()) is simpler and sufficient for most use cases