2020-08-28 14:16:37 +02:00
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::convert::TryInto;
|
|
|
|
use std::str;
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
use heed::BoxedError;
|
|
|
|
|
2020-09-06 10:30:53 +02:00
|
|
|
pub struct BEU32StrCodec;
|
2020-08-28 14:16:37 +02:00
|
|
|
|
2020-09-06 10:30:53 +02:00
|
|
|
impl<'a> heed::BytesDecode<'a> for BEU32StrCodec {
|
|
|
|
type DItem = (u32, &'a str);
|
2020-08-28 14:16:37 +02:00
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
|
2020-09-06 10:30:53 +02:00
|
|
|
let (n_bytes, str_bytes) = bytes.split_at(4);
|
2023-11-22 18:21:19 +01:00
|
|
|
let n = n_bytes.try_into().map(u32::from_be_bytes)?;
|
|
|
|
let s = str::from_utf8(str_bytes)?;
|
|
|
|
Ok((n, s))
|
2020-08-28 14:16:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-06 10:30:53 +02:00
|
|
|
impl<'a> heed::BytesEncode<'a> for BEU32StrCodec {
|
|
|
|
type EItem = (u32, &'a str);
|
2020-08-28 14:16:37 +02:00
|
|
|
|
2024-07-09 17:25:39 +02:00
|
|
|
fn bytes_encode((n, s): &Self::EItem) -> Result<Cow<'a, [u8]>, BoxedError> {
|
2020-08-28 14:16:37 +02:00
|
|
|
let mut bytes = Vec::with_capacity(s.len() + 4);
|
|
|
|
bytes.extend_from_slice(&n.to_be_bytes());
|
2020-09-06 10:30:53 +02:00
|
|
|
bytes.extend_from_slice(s.as_bytes());
|
2023-11-22 18:21:19 +01:00
|
|
|
Ok(Cow::Owned(bytes))
|
2020-08-28 14:16:37 +02:00
|
|
|
}
|
|
|
|
}
|