milli_core/heed_codec/
version.rs

1use std::borrow::Cow;
2use std::mem::{size_of, size_of_val};
3
4use byteorder::{BigEndian, ByteOrder};
5use heed::{BoxedError, BytesDecode, BytesEncode};
6
7const VERSION_SIZE: usize = std::mem::size_of::<u32>() * 3;
8
9#[derive(thiserror::Error, Debug)]
10#[error(
11    "Could not decode the version: Expected {VERSION_SIZE} bytes but instead received {0} bytes"
12)]
13pub struct DecodeVersionError(usize);
14
15pub struct VersionCodec;
16impl<'a> BytesEncode<'a> for VersionCodec {
17    type EItem = (u32, u32, u32);
18
19    fn bytes_encode(item: &'a Self::EItem) -> Result<Cow<'a, [u8]>, BoxedError> {
20        let mut ret = Vec::with_capacity(size_of::<u32>() * 3);
21        ret.extend(&item.0.to_be_bytes());
22        ret.extend(&item.1.to_be_bytes());
23        ret.extend(&item.2.to_be_bytes());
24        Ok(Cow::Owned(ret))
25    }
26}
27impl<'a> BytesDecode<'a> for VersionCodec {
28    type DItem = (u32, u32, u32);
29
30    fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
31        if bytes.len() != VERSION_SIZE {
32            Err(Box::new(DecodeVersionError(bytes.len())))
33        } else {
34            let major = BigEndian::read_u32(bytes);
35            let bytes = &bytes[size_of_val(&major)..];
36            let minor = BigEndian::read_u32(bytes);
37            let bytes = &bytes[size_of_val(&major)..];
38            let patch = BigEndian::read_u32(bytes);
39
40            Ok((major, minor, patch))
41        }
42    }
43}