Expand description
This crate provides stream traits for conveniently read and writing many data types: bytes,
little or big-endian integers, and UTF-8 strings. DataSource
reads from a stream, DataSink
writes to a stream.
Implementations for byte slices and std::io
’s buffered readers and writers are provided, but
it’s easy to write your own implementations:
struct MySource {
buffer: Vec<u8>,
// ...
}
impl DataSource for MySource {
fn available(&self) -> usize {
self.buffer.len()
}
fn request(&mut self, count: usize) -> Result<bool> {
if self.available() < count {
// Fill the buffer...
}
Ok(self.available() >= count)
}
fn skip(&mut self, count: usize) -> Result<usize> {
// Read bytes up to count bytes from the stream...
// Here we just consume from the buffer as an example.
self.buffer.drain(..count);
Ok(count)
}
fn read_bytes<'a>(&mut self, buf: &'a mut [u8]) -> Result<&'a [u8]> {
let count = self.available().min(buf.len());
buf[..count].copy_from_slice(&self.buffer);
self.buffer.drain(..count);
Ok(&buf[..count])
}
}
struct MySink {
buffer: Vec<u8>,
// ...
}
impl DataSink for MySink {
fn write_bytes(&mut self, buf: &[u8]) -> Result {
self.buffer.extend_from_slice(buf);
// Flush the buffer?
Ok(())
}
}
§Feature flags
std
: Provides impls forstd::io
types, such asBufReader
andBufWriter
. Requires a dependency on the Rust standard library. Disable to allow usage withno_std
.alloc
: Provides impls for dynamically allocated types such asVec
, and source methods for reading into these. Requires a heap allocator, which may not be present on platforms without the standard library.utf8
: Enables reading UTF-8-validated data from sources, and writing toString
s, using a very fast SIMD validation algorithm from thesimdutf8
crate. UTF-8 can be written to sinks without this feature.unstable
: Provides unstable features only present on the nightly compiler. Enables:unstable_borrowed_buf
: ProvidesDataSource
impls forBorrowedBuf
andBorrowedCursor
.unstable_specialization
: Enables trait specialization, providing a defaultDataSource
for impls ofBufferAccess
.unstable_uninit_slice
: Provides aDataSink
impl for&mut [MaybeUninit<u8>]
.
Modules§
Enums§
- Error
- A stream error.
Traits§
- Buffer
Access - Accesses a source’s internal buffer.
- Data
Sink - A sink stream of data.
- Data
Source - A source stream of data.
- Generic
Data Sink - Writes generic data to a sink.
- Generic
Data Source - Reads generic data from a source.
- VecSink
- A sink stream of vector data.
- VecSource
- A source stream reading data into vectors.