2020-09-07 15:42:20 +02:00
|
|
|
use std::borrow::Cow;
|
2021-04-27 18:42:08 +02:00
|
|
|
use std::convert::TryInto;
|
2021-04-27 14:22:33 +02:00
|
|
|
use std::mem::size_of;
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
use heed::{BoxedError, BytesDecode};
|
2020-09-07 15:42:20 +02:00
|
|
|
use roaring::RoaringBitmap;
|
|
|
|
|
2023-06-13 14:41:53 +02:00
|
|
|
use crate::heed_codec::BytesDecodeOwned;
|
|
|
|
|
2020-10-01 10:58:19 +02:00
|
|
|
pub struct BoRoaringBitmapCodec;
|
2020-09-07 15:42:20 +02:00
|
|
|
|
2021-06-09 15:26:40 +02:00
|
|
|
impl BoRoaringBitmapCodec {
|
|
|
|
pub fn serialize_into(bitmap: &RoaringBitmap, out: &mut Vec<u8>) {
|
|
|
|
out.reserve(bitmap.len() as usize * size_of::<u32>());
|
|
|
|
bitmap.iter().map(u32::to_ne_bytes).for_each(|bytes| out.extend_from_slice(&bytes));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-13 14:41:53 +02:00
|
|
|
impl BytesDecode<'_> for BoRoaringBitmapCodec {
|
2020-09-07 15:42:20 +02:00
|
|
|
type DItem = RoaringBitmap;
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_decode(bytes: &[u8]) -> Result<Self::DItem, BoxedError> {
|
2020-09-07 15:42:20 +02:00
|
|
|
let mut bitmap = RoaringBitmap::new();
|
2021-04-27 18:42:08 +02:00
|
|
|
|
|
|
|
for chunk in bytes.chunks(size_of::<u32>()) {
|
2023-11-22 18:21:19 +01:00
|
|
|
let bytes = chunk.try_into()?;
|
2021-04-27 18:42:08 +02:00
|
|
|
bitmap.push(u32::from_ne_bytes(bytes));
|
2020-09-07 15:42:20 +02:00
|
|
|
}
|
2021-04-27 18:42:08 +02:00
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
Ok(bitmap)
|
2020-09-07 15:42:20 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-13 14:41:53 +02:00
|
|
|
impl BytesDecodeOwned for BoRoaringBitmapCodec {
|
|
|
|
type DItem = RoaringBitmap;
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_decode_owned(bytes: &[u8]) -> Result<Self::DItem, BoxedError> {
|
2023-06-13 14:41:53 +02:00
|
|
|
Self::bytes_decode(bytes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-01 10:58:19 +02:00
|
|
|
impl heed::BytesEncode<'_> for BoRoaringBitmapCodec {
|
2020-09-07 15:42:20 +02:00
|
|
|
type EItem = RoaringBitmap;
|
|
|
|
|
2023-11-22 18:21:19 +01:00
|
|
|
fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
|
2021-06-09 15:26:40 +02:00
|
|
|
let mut out = Vec::new();
|
|
|
|
BoRoaringBitmapCodec::serialize_into(item, &mut out);
|
2023-11-22 18:21:19 +01:00
|
|
|
Ok(Cow::Owned(out))
|
2020-09-07 15:42:20 +02:00
|
|
|
}
|
|
|
|
}
|