heed_types/
lazy_decode.rs

1use std::marker;
2
3use heed_traits::BoxedError;
4
5/// Lazily decodes the data bytes.
6///
7/// It can be used to avoid CPU-intensive decoding before making sure that it
8/// actually needs to be decoded (e.g. based on the key).
9#[derive(Default)]
10pub struct LazyDecode<C>(marker::PhantomData<C>);
11
12impl<'a, C: 'static> heed_traits::BytesDecode<'a> for LazyDecode<C> {
13    type DItem = Lazy<'a, C>;
14
15    fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
16        Ok(Lazy { data: bytes, _phantom: marker::PhantomData })
17    }
18}
19
20/// Owns bytes that can be decoded on demand.
21#[derive(Copy, Clone)]
22pub struct Lazy<'a, C> {
23    data: &'a [u8],
24    _phantom: marker::PhantomData<C>,
25}
26
27impl<'a, C: heed_traits::BytesDecode<'a>> Lazy<'a, C> {
28    /// Change the codec type of the given bytes, specifying the new codec.
29    pub fn remap<NC>(&self) -> Lazy<'a, NC> {
30        Lazy { data: self.data, _phantom: marker::PhantomData }
31    }
32
33    /// Decode the given bytes as `DItem`.
34    pub fn decode(&self) -> Result<C::DItem, BoxedError> {
35        C::bytes_decode(self.data)
36    }
37}