Add bitv module

This commit is contained in:
Igor Katson 2024-08-20 15:07:23 +01:00
parent d99ebccf4d
commit d7236f05a9
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
2 changed files with 79 additions and 0 deletions

View file

@ -0,0 +1,78 @@
use std::fs::File;
use anyhow::Context;
use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec, view::AsBits, view::AsMutBits};
pub trait BitV: Send {
fn as_slice(&self) -> &BitSlice<u8, Lsb0>;
fn as_slice_mut(&mut self) -> &mut BitSlice<u8, Lsb0>;
fn flush(&mut self) -> anyhow::Result<()>;
fn into_dyn(self) -> Box<dyn BitV>;
}
pub struct MmapBitV {
_file: File,
mmap: memmap2::MmapMut,
}
impl MmapBitV {
pub fn new(file: File) -> anyhow::Result<Self> {
let mmap =
unsafe { memmap2::MmapOptions::new().map_mut(&file) }.context("error mmapping file")?;
Ok(Self { mmap, _file: file })
}
}
impl BitV for BitVec<u8, Lsb0> {
fn as_slice(&self) -> &BitSlice<u8, Lsb0> {
self.as_bitslice()
}
fn as_slice_mut(&mut self) -> &mut BitSlice<u8, Lsb0> {
self.as_mut_bitslice()
}
fn flush(&mut self) -> anyhow::Result<()> {
Ok(())
}
fn into_dyn(self) -> Box<dyn BitV> {
Box::new(self)
}
}
impl BitV for MmapBitV {
fn as_slice(&self) -> &BitSlice<u8, Lsb0> {
self.mmap.as_bits()
}
fn as_slice_mut(&mut self) -> &mut BitSlice<u8, Lsb0> {
self.mmap.as_mut_bits()
}
fn flush(&mut self) -> anyhow::Result<()> {
Ok(self.mmap.flush()?)
}
fn into_dyn(self) -> Box<dyn BitV> {
Box::new(self)
}
}
impl BitV for Box<dyn BitV> {
fn as_slice(&self) -> &BitSlice<u8, Lsb0> {
(**self).as_slice()
}
fn as_slice_mut(&mut self) -> &mut BitSlice<u8, Lsb0> {
(**self).as_slice_mut()
}
fn flush(&mut self) -> anyhow::Result<()> {
(**self).flush()
}
fn into_dyn(self) -> Box<dyn BitV> {
self
}
}

View file

@ -40,6 +40,7 @@ macro_rules! aframe {
pub mod api;
mod api_error;
mod bitv;
mod chunk_tracker;
mod create_torrent_file;
mod dht_utils;