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
| Iterator | Borrowed | Owned |
|---|---|---|
ByteIterator | u8 | u8 |
ChunkIterator | &[u8] | Vec<u8> |
LineIterator | &str | String |
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()ornext(). 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