Skip to main content

IoDecoder

Struct IoDecoder 

Source
pub struct IoDecoder<R: Read> { /* private fields */ }
Available on crate feature 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>

Source

pub fn new(reader: R) -> Self

Wrap reader with the default Config (1 GiB max_alloc, depth limit 128).

For input from a peer, use IoDecoder::with_config with Config::network (or tighter) instead. Whatever the cap, the decoder only grows a buffer as bytes actually arrive from reader, so a large declared length on a short or stalled stream does not reserve memory up front.

§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);
Source

pub fn with_config(reader: R, config: Config) -> Result<Self>

Wrap reader with the supplied configuration.

§Errors
§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");
Source

pub fn config(&self) -> Config

The configuration this decoder enforces.

§Examples
use std::io::Cursor;
use pack_io::{Config, IoDecoder};

let cfg = Config::new().with_max_alloc(4096);
let dec = IoDecoder::with_config(Cursor::new(Vec::new()), cfg).unwrap();
assert_eq!(dec.config().max_alloc, 4096);
Source

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);
Source

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=42
Source

pub fn read<T: Deserialize>(&mut self) -> Result<T>

Decode the next value from the underlying reader.

Each top-level call starts a fresh Config::total_alloc_limit budget, so a decoder that reads one message after another from a socket gives every message the same limit.

§Errors

Trait Implementations§

Source§

impl<R: Debug + Read> Debug for IoDecoder<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: Read> Decode for IoDecoder<R>

Source§

fn read_byte(&mut self) -> Result<u8>

Read the next byte, advancing the cursor. Read more
Source§

fn read_into(&mut self, out: &mut [u8]) -> Result<()>

Fill out with exactly out.len() bytes, advancing the cursor. Read more
Source§

fn max_alloc(&self) -> usize

Maximum number of bytes the decoder will allocate for a single length-prefixed value. Mirrors Config::max_alloc.
Source§

fn config(&self) -> Config

The configuration this decoder enforces. Read more
Source§

fn depth(&self) -> usize

Current nesting depth: the number of derived values whose fields are being decoded right now. Always 0 for decoders that do not track depth (the default).
Source§

fn enter_nested(&mut self) -> Result<()>

Record entry into one more level of nesting. Read more
Source§

fn leave_nested(&mut self)

Record exit from one level of nesting. Pairs with enter_nested; call it on the error path too, so the decoder stays usable after a failed read.
Source§

fn bytes_read(&self) -> Option<u64>

Number of input bytes this decoder has consumed so far, when it counts them. Read more
Source§

fn unbacked(&self) -> usize

Memory, in bytes, charged so far for the value being decoded with charge_unbacked. Always 0 for decoders that keep no running total (the default).
Source§

fn charge_unbacked(&mut self, bytes: usize) -> Result<()>

Charge bytes of memory the value being decoded needs against Config::total_alloc_limit. Read more
Source§

fn reset_unbacked(&mut self)

Clear the running total of charge_unbacked, starting the budget of a new top-level value. Read more
Source§

fn remaining_hint(&self) -> Option<usize>

An upper bound on the number of bytes that can still be read, when the decoder knows it. Read more
Source§

fn consumed(&self) -> Option<&[u8]>

The bytes this decoder has consumed so far, when it keeps its input in memory. Read more
Source§

fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>>

Read exactly len bytes. Read more
Source§

fn read_varint_u64(&mut self) -> Result<u64>

Read a LEB128 varint as a u64. Read more
Source§

fn read_varint_u128(&mut self) -> Result<u128>

Read a LEB128 varint as a u128. Read more
Source§

fn read_length_prefixed(&mut self) -> Result<Vec<u8>>

Read a length-prefixed byte run into a fresh Vec<u8>. Read more

Auto Trait Implementations§

§

impl<R> Forget for IoDecoder<R>

§

impl<R> Freeze for IoDecoder<R>
where R: Freeze,

§

impl<R> Move for IoDecoder<R>

§

impl<R> RefUnwindSafe for IoDecoder<R>
where R: RefUnwindSafe,

§

impl<R> Send for IoDecoder<R>
where R: Send,

§

impl<R> Sync for IoDecoder<R>
where R: Sync,

§

impl<R> Unpin for IoDecoder<R>
where R: Unpin,

§

impl<R> UnsafeUnpin for IoDecoder<R>
where R: UnsafeUnpin,

§

impl<R> UnwindSafe for IoDecoder<R>
where R: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.