Skip to main content

Decode

Trait Decode 

Source
pub trait Decode {
    type Decoder: Decoder<Output = Self> + Default;

    // Provided method
    fn decoder() -> Self::Decoder { ... }
}
Expand description

A Bitcoin object which can be consensus-decoded using a push decoder.

To decode something, create a Self::Decoder and push byte slices into it with Decoder::push_bytes, then call Decoder::end to get the result.

§Examples

use bitcoin_consensus_encoding::{decode_from_slice, Decode, Decoder, DecoderStatus, ArrayDecoder, UnexpectedEofError};

struct Foo([u8; 4]);

#[derive(Default)]
struct FooDecoder(ArrayDecoder<4>);

impl Decoder for FooDecoder {
    type Output = Foo;
    type Error = UnexpectedEofError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<DecoderStatus, Self::Error> {
        self.0.push_bytes(bytes)
    }
    fn end(self) -> Result<Self::Output, Self::Error> { self.0.end().map(Foo) }
    fn read_limit(&self) -> usize { self.0.read_limit() }
}

impl Decode for Foo {
    type Decoder = FooDecoder;
}

let foo: Foo = decode_from_slice(&[0xde, 0xad, 0xbe, 0xef]).unwrap();
assert_eq!(foo.0, [0xde, 0xad, 0xbe, 0xef]);

Required Associated Types§

Source

type Decoder: Decoder<Output = Self> + Default

Associated decoder for the type.

Provided Methods§

Source

fn decoder() -> Self::Decoder

Constructs a “default decoder” for the type.

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§