bytecodec

Trait DecodeExt

Source
pub trait DecodeExt: Decode + Sized {
Show 14 methods // Provided methods fn map<T, F>(self, f: F) -> Map<Self, T, F> where F: Fn(Self::Item) -> T { ... } fn try_map<T, E, F>(self, f: F) -> TryMap<Self, T, E, F> where F: Fn(Self::Item) -> Result<T, E>, Error: From<E> { ... } fn map_err<E, F>(self, f: F) -> MapErr<Self, E, F> where F: Fn(Error) -> E, Error: From<E> { ... } fn and_then<D, F>(self, f: F) -> AndThen<Self, D, F> where F: Fn(Self::Item) -> D, D: Decode { ... } fn collect<T>(self) -> Collect<Self, T> where T: Extend<Self::Item> + Default { ... } fn collectn<T>(self, n: usize) -> CollectN<Self, T> where T: Extend<Self::Item> + Default { ... } fn length(self, expected_bytes: u64) -> Length<Self> { ... } fn omit(self, do_omit: bool) -> Omittable<Self> { ... } fn max_bytes(self, bytes: u64) -> MaxBytes<Self> { ... } fn chain<T: Decode>(self, other: T) -> TupleDecoder<(Self, T)> { ... } fn slice(self) -> Slice<Self> { ... } fn peekable(self) -> Peekable<Self> { ... } fn maybe_eos(self) -> MaybeEos<Self> { ... } fn decode_from_bytes(&mut self, buf: &[u8]) -> Result<Self::Item> { ... }
}
Expand description

An extension of Decode trait.

Provided Methods§

Source

fn map<T, F>(self, f: F) -> Map<Self, T, F>
where F: Fn(Self::Item) -> T,

Creates a decoder that converts decoded values by calling the given function.

§Examples
use bytecodec::{Decode, DecodeExt};
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = U8Decoder::new().map(|b| b * 2);
let item = decoder.decode_exact([10].as_ref()).unwrap();
assert_eq!(item, 20);
Source

fn try_map<T, E, F>(self, f: F) -> TryMap<Self, T, E, F>
where F: Fn(Self::Item) -> Result<T, E>, Error: From<E>,

Creates a decoder that tries to convert decoded values by calling the given function.

§Examples
use bytecodec::{Decode, DecodeExt, ErrorKind, Result};
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;
use trackable::{track, track_assert, track_assert_ne, track_panic};

let mut decoder = U8Decoder::new().try_map(|b| -> Result<_> {
    track_assert_ne!(b, 0, ErrorKind::InvalidInput);
    Ok(b * 2)
});

let error = decoder.decode_exact([0].as_ref()).err().unwrap();
assert_eq!(*error.kind(), ErrorKind::InvalidInput);

let item = decoder.decode_exact([4].as_ref()).unwrap();
assert_eq!(item, 8);
Source

fn map_err<E, F>(self, f: F) -> MapErr<Self, E, F>
where F: Fn(Error) -> E, Error: From<E>,

Creates a decoder for modifying decoding errors produced by self.

§Examples

The following code shows the idiomatic way to track decoding errors:

use bytecodec::{Decode, DecodeExt};
use bytecodec::fixnum::U16beDecoder;
use bytecodec::io::IoDecodeExt;
use trackable::track;

let mut decoder =
    U16beDecoder::new().map_err(|e| track!(e, "oops!"));
    // or `track_err!(U16beDecoder::new(), "oops!")`

let input = [0]; // Insufficient bytes
let error = track!(decoder.decode_exact(input.as_ref())).err().unwrap();

assert_eq!(error.to_string(), "\
UnexpectedEos (cause; assertion failed: `!eos.is_reached()`; \
               self.offset=1, self.bytes.as_ref().len()=2)
HISTORY:
  [0] at src/bytes.rs:152
  [1] at src/fixnum.rs:200
  [2] at src/decode.rs:10 -- oops!
  [3] at src/io.rs:45
  [4] at src/decode.rs:14\n");
Source

fn and_then<D, F>(self, f: F) -> AndThen<Self, D, F>
where F: Fn(Self::Item) -> D, D: Decode,

Creates a decoder that enables conditional decoding.

If the first item is successfully decoded, it will start decoding the second item by using the decoder returned by f function.

§Examples

Decodes a length-prefixed string:

use bytecodec::{Decode, DecodeExt};
use bytecodec::bytes::Utf8Decoder;
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = U8Decoder::new().and_then(|len| Utf8Decoder::new().length(len as u64));
let item = decoder.decode_exact(b"\x03foobar".as_ref()).unwrap();
assert_eq!(item, "foo");
Source

fn collect<T>(self) -> Collect<Self, T>
where T: Extend<Self::Item> + Default,

Creates a decoder for collecting decoded items.

§Examples
use bytecodec::{Decode, DecodeExt};
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = U8Decoder::new().collect::<Vec<_>>();
let item = decoder.decode_exact(b"foo".as_ref()).unwrap();
assert_eq!(item, vec![b'f', b'o', b'o']);
Source

fn collectn<T>(self, n: usize) -> CollectN<Self, T>
where T: Extend<Self::Item> + Default,

Creates a decoder that decodes n items by using self and collecting the result.

§Examples
use bytecodec::{Decode, DecodeExt};
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = U8Decoder::new().collectn::<Vec<_>>(2);
let item = decoder.decode_exact(b"foo".as_ref()).unwrap();
assert_eq!(item, vec![b'f', b'o']);
Source

fn length(self, expected_bytes: u64) -> Length<Self>

Creates a decoder that consumes the specified number of bytes exactly.

§Examples
use bytecodec::{Decode, DecodeExt, ErrorKind};
use bytecodec::bytes::Utf8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = Utf8Decoder::new().length(3);
let mut input = &b"foobarba"[..];

let item = decoder.decode_exact(&mut input).unwrap();
assert_eq!(item, "foo");

let item = decoder.decode_exact(&mut input).unwrap();
assert_eq!(item, "bar");

let error = decoder.decode_exact(&mut input).err().unwrap();
assert_eq!(*error.kind(), ErrorKind::UnexpectedEos);
Source

fn omit(self, do_omit: bool) -> Omittable<Self>

Creates a decoder that will omit decoding items if do_omit = true is specified.

§Examples
use bytecodec::{Decode, DecodeExt};
use bytecodec::fixnum::U8Decoder;
use bytecodec::io::IoDecodeExt;

let mut input = &b"foo"[..];

let mut decoder = U8Decoder::new().omit(true);
let item = decoder.decode_exact(&mut input).unwrap();
assert_eq!(item, None);

let mut decoder = U8Decoder::new().omit(false);
let item = decoder.decode_exact(&mut input).unwrap();
assert_eq!(item, Some(b'f'));
Source

fn max_bytes(self, bytes: u64) -> MaxBytes<Self>

Creates a decoder that will fail if the number of consumed bytes exceeds bytes.

§Examples
use bytecodec::{Decode, DecodeExt, ErrorKind};
use bytecodec::bytes::Utf8Decoder;
use bytecodec::io::IoDecodeExt;

let mut decoder = Utf8Decoder::new().max_bytes(3);

let item = decoder.decode_exact(b"foo".as_ref()).unwrap();
assert_eq!(item, "foo"); // OK

let error = decoder.decode_exact(b"hello".as_ref()).err();
assert_eq!(error.map(|e| *e.kind()), Some(ErrorKind::InvalidInput)); // Error
Source

fn chain<T: Decode>(self, other: T) -> TupleDecoder<(Self, T)>

Takes two decoders and creates a new decoder that decodes both items in sequence.

This is equivalent to call TupleDecoder::new((self, other)).

Source

fn slice(self) -> Slice<Self>

Creates a decoder that makes it possible to slice the input byte sequence in arbitrary units.

Slicing an input byte sequence makes it easier to demultiplex multiple sequences from it.

§Examples
use bytecodec::{Decode, DecodeExt, Eos};
use bytecodec::bytes::Utf8Decoder;

let mut decoder0 = Utf8Decoder::new().length(3).slice();
let mut decoder1 = Utf8Decoder::new().length(3).slice();

let eos = Eos::new(true);
let input = b"fboaor";
let mut offset = 0;

for _ in 0..3 {
    decoder0.set_consumable_bytes(1);
    offset += decoder0.decode(&input[offset..], eos).unwrap();

    decoder1.set_consumable_bytes(1);
    offset += decoder1.decode(&input[offset..], eos).unwrap();
}

assert_eq!(offset, input.len());
assert_eq!(decoder0.finish_decoding().unwrap(), "foo");
assert_eq!(decoder1.finish_decoding().unwrap(), "bar");
Source

fn peekable(self) -> Peekable<Self>

Creates a decoder that enables to peek decoded items before calling finish_decoding method.

§Examples
use bytecodec::{Decode, DecodeExt, Eos};
use bytecodec::fixnum::U8Decoder;
use bytecodec::tuple::TupleDecoder;

let mut decoder = TupleDecoder::new((
    U8Decoder::new(),
    U8Decoder::new(),
    U8Decoder::new(),
)).peekable();
let size = decoder.decode(b"foo", Eos::new(false)).unwrap();
assert_eq!(size, 3);
assert_eq!(decoder.peek(), Some(&(b'f', b'o', b'o')));
assert_eq!(decoder.finish_decoding().unwrap(), (b'f', b'o', b'o'));
assert_eq!(decoder.peek(), None);
Source

fn maybe_eos(self) -> MaybeEos<Self>

Creates a decoder that ignores EOS if there is no item being decoded.

§Examples
use bytecodec::{Decode, DecodeExt, Eos};
use bytecodec::fixnum::U16beDecoder;

let mut decoder = U16beDecoder::new();
assert!(decoder.decode(&[][..], Eos::new(true)).is_err()); // UnexpectedEos

let mut decoder = U16beDecoder::new().maybe_eos();
assert!(decoder.decode(&[][..], Eos::new(true)).is_ok()); // EOS is ignored

let mut decoder = U16beDecoder::new().maybe_eos();
assert!(decoder.decode(&[1][..], Eos::new(true)).is_err()); // UnexpectedEos
Source

fn decode_from_bytes(&mut self, buf: &[u8]) -> Result<Self::Item>

Decodes an item by consuming the whole part of the given bytes.

§Examples
use bytecodec::DecodeExt;
use bytecodec::fixnum::U16beDecoder;

let mut decoder = U16beDecoder::new();
assert_eq!(
    decoder.decode_from_bytes(&[0x12, 0x34][..]).unwrap(),
    0x1234
);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Decode> DecodeExt for T