[−][src]Crate buf_ref_reader
Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read.
std::io::BufReader
works by copying data from its internal buffer into user-provided Vec
/String
,
or, in case of .lines()
, by emitting new heap-allocated String
for each iteration.
While convenient and versatile, this is not the fastest approach.
Instead, BufRefReader
references its internal buffer with each read, returning &[u8]
.
Lack of extra allocations yields better read performance in situations where most (if not all) of read data:
- requires no modifications,
- is never used outside of a loop body and does not need to be duplicated into the heap for future use.
While being more performant, this approach also severely limits applicability of this reader:
- it does not (and cannot) implement
BufRead
and cannot be used as a direct replacement forBufReader
; - returned values are only valid between calls to reading functions (i.e. they cannot outlive even a single loop cycle), and Rust's borrow checker will prevent you from using stale references;
- consequently,
BufRefReader
cannot be turned into anIterator
(here's an easy way to think about it: what wouldIterator::collect()
return?); - returned references are immutable;
- obviously, there's also nothing that can return
String
s or&str
s for you.
Examples
Read data word by word:
use buf_ref_reader::BufRefReaderBuilder; // &[u8] implements Read, hence we use it as our data source for this example let data = b"lorem ipsum dolor sit amet"; let mut r = BufRefReaderBuilder::new(&data[..]) .capacity(4) .increment(4) .build(); assert_eq!(r.read_until(b' ')?, Some(&b"lorem"[..])); assert_eq!(r.read_until(b' ')?, Some(&b"ipsum"[..])); assert_eq!(r.read_until(b' ')?, Some(&b"dolor"[..])); assert_eq!(r.read_until(b' ')?, Some(&b"sit"[..])); assert_eq!(r.read_until(b' ')?, Some(&b"amet"[..])); assert_eq!(r.read_until(b' ')?, None); // EOF assert_eq!(r.read_until(b' ')?, None);
Structs
BufRefReader | Buffering reader. |
BufRefReaderBuilder | Builder for |