2021-06-16 18:33:33 +02:00
|
|
|
use std::borrow::Cow;
|
2021-05-27 15:27:41 +02:00
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
use heed::BoxedError;
|
|
|
|
|
2023-11-28 10:11:17 +01:00
|
|
|
use super::SliceTooShortError;
|
2021-07-06 11:31:24 +02:00
|
|
|
use crate::{try_split_array_at, FieldId};
|
2021-05-27 15:27:41 +02:00
|
|
|
|
|
|
|
pub struct FieldIdWordCountCodec;
|
|
|
|
|
|
|
|
impl<'a> heed::BytesDecode<'a> for FieldIdWordCountCodec {
|
|
|
|
type DItem = (FieldId, u8);
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
|
2023-11-28 10:11:17 +01:00
|
|
|
let (field_id_bytes, bytes) = try_split_array_at(bytes).ok_or(SliceTooShortError)?;
|
2021-07-06 11:31:24 +02:00
|
|
|
let field_id = u16::from_be_bytes(field_id_bytes);
|
2023-11-28 10:11:17 +01:00
|
|
|
let ([word_count], _nothing) = try_split_array_at(bytes).ok_or(SliceTooShortError)?;
|
2023-11-22 18:21:19 +01:00
|
|
|
Ok((field_id, word_count))
|
2021-05-27 15:27:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> heed::BytesEncode<'a> for FieldIdWordCountCodec {
|
|
|
|
type EItem = (FieldId, u8);
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_encode((field_id, word_count): &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
|
2021-07-06 11:31:24 +02:00
|
|
|
let mut bytes = Vec::with_capacity(2 + 1);
|
|
|
|
bytes.extend_from_slice(&field_id.to_be_bytes());
|
|
|
|
bytes.push(*word_count);
|
2023-11-22 18:21:19 +01:00
|
|
|
Ok(Cow::Owned(bytes))
|
2021-05-27 15:27:41 +02:00
|
|
|
}
|
|
|
|
}
|