pub struct IoDecoder<R: Read> { /* private fields */ }std only.Expand description
Streaming decoder that reads directly from any Read-shaped source.
Each IoDecoder::read call may issue many small reads against the
underlying source. Wrap raw sockets / files in std::io::BufReader
first if read-syscall amplification is a concern.
§Examples
use pack_io::{IoEncoder, IoDecoder};
use std::io::Cursor;
let mut buf: Vec<u8> = Vec::new();
{
let mut enc = IoEncoder::new(&mut buf);
enc.write(&42_u64).unwrap();
enc.write(&"hi").unwrap();
}
let mut dec = IoDecoder::new(Cursor::new(buf));
let n: u64 = dec.read().unwrap();
let s: String = dec.read().unwrap();
assert_eq!((n, s.as_str()), (42, "hi"));Implementations§
Source§impl<R: Read> IoDecoder<R>
impl<R: Read> IoDecoder<R>
Sourcepub fn new(reader: R) -> Self
pub fn new(reader: R) -> Self
Wrap reader with the default Config (1 GiB max_alloc).
For tighter allocation caps on untrusted input, use
IoDecoder::with_config instead.
§Examples
use std::io::Cursor;
use pack_io::IoDecoder;
let bytes = pack_io::encode(&42_u64).unwrap();
let mut dec = IoDecoder::new(Cursor::new(bytes));
let n: u64 = dec.read().unwrap();
assert_eq!(n, 42);Sourcepub fn with_config(reader: R, config: Config) -> Result<Self>
pub fn with_config(reader: R, config: Config) -> Result<Self>
Wrap reader with the supplied configuration.
§Errors
Returns SerialError::InvalidLength if config.max_alloc == 0.
§Examples
use std::io::Cursor;
use pack_io::{Config, IoDecoder};
let cfg = Config::new().with_max_alloc(16 * 1024);
let bytes = pack_io::encode(&"hello").unwrap();
let mut dec = IoDecoder::with_config(Cursor::new(bytes), cfg).unwrap();
let s: String = dec.read().unwrap();
assert_eq!(s, "hello");Sourcepub fn reader(&self) -> &R
pub fn reader(&self) -> &R
Borrow the underlying reader.
§Examples
use std::io::Cursor;
use pack_io::IoDecoder;
let dec = IoDecoder::new(Cursor::new(vec![0u8; 4]));
assert_eq!(dec.reader().get_ref().len(), 4);Sourcepub fn into_inner(self) -> R
pub fn into_inner(self) -> R
Consume the decoder and return the underlying reader.
Useful when the caller wants to take back ownership of the source (e.g. to drop the reader, return it to a pool, or feed it to a different consumer) after the decoded prefix has been processed.
§Examples
use std::io::Cursor;
use pack_io::IoDecoder;
let bytes = pack_io::encode(&42_u64).unwrap();
let mut dec = IoDecoder::new(Cursor::new(bytes));
let _n: u64 = dec.read().unwrap();
let reader: Cursor<Vec<u8>> = dec.into_inner();
assert_eq!(reader.position(), 1); // one byte consumed for u64=42Sourcepub fn read<T: Deserialize>(&mut self) -> Result<T>
pub fn read<T: Deserialize>(&mut self) -> Result<T>
Decode the next value from the underlying reader.
§Errors
- Propagates any
crate::SerialErrorfrom the type’sDeserialize. - Maps any
std::io::Errorfrom the reader intoSerialError::Io.