pub trait AsDecoder<'a, const PRECISION: usize>: Encode<PRECISION> + 'a {
    type AsDecoder: Decode<PRECISION, Word = Self::Word, State = Self::State> + 'a;

    // Required method
    fn as_decoder(&'a self) -> Self::AsDecoder;
}
Expand description

A trait for temporary conversion into a matching decoder type.

This is useful for generic code that encodes some data with a user provided encoder of generic type, and then needs to obtain a compatible decoder.

See also

  • IntoDecoder, if you don’t need the encoder anymore, or if you want to return the resulting decoder from the current stack frame. Needs ownership of the encoder.

Example

To be able to temporarily convert an encoder of generic type Encoder into a decoder, declare a trait bound for<'a> Encoder: AsDecoder<'a, PRECISION>. In the following example, differences to the example for IntoDecoder are marked by // <--.

use constriction::stream::{
    model::{EncoderModel, DecoderModel, LeakyQuantizer},
    stack::DefaultAnsCoder,
    Decode, Encode, AsDecoder
};

fn encode_decode_encode<Encoder, D, const PRECISION: usize>(
    encoder: &mut Encoder, // <-- Doesn't need ownership of `encoder`.
    model: D
)
where
    Encoder: Encode<PRECISION>,
    for<'a> Encoder: AsDecoder<'a, PRECISION>, // <-- Different trait bound.
    D: EncoderModel<PRECISION, Symbol=i32> + DecoderModel<PRECISION, Symbol=i32> + Copy,
    D::Probability: Into<Encoder::Word>,
    Encoder::Word: num_traits::AsPrimitive<D::Probability>
{
    encoder.encode_symbol(137, model);
    let mut decoder = encoder.as_decoder();
    let decoded = decoder.decode_symbol(model).unwrap(); // (Doesn't mutate `encoder`.)
    assert_eq!(decoded, 137);

    std::mem::drop(decoder); // <-- We have to explicitly drop `decoder` ...
    encoder.encode_symbol(42, model); // <-- ... before we can use `encoder` again.
}

// Usage example:
let mut encoder = DefaultAnsCoder::new();
let quantizer = LeakyQuantizer::<_, _, u32, 24>::new(0..=200);
let model = quantizer.quantize(probability::distribution::Gaussian::new(0.0, 50.0));
encode_decode_encode(&mut encoder, model);

Required Associated Types§

source

type AsDecoder: Decode<PRECISION, Word = Self::Word, State = Self::State> + 'a

The target type of the conversion.

Required Methods§

source

fn as_decoder(&'a self) -> Self::AsDecoder

Performs the conversion.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<'a, Word, State, Backend, const PRECISION: usize> AsDecoder<'a, PRECISION> for AnsCoder<Word, State, Backend>
where Word: BitArray + Into<State>, State: BitArray + AsPrimitive<Word>, Backend: WriteWords<Word> + AsReadWords<'a, Word, Stack>,

§

type AsDecoder = AnsCoder<Word, State, <Backend as AsReadWords<'a, Word, Stack>>::AsReadWords>