use std::fs::File;
use std::io;
use std::mem::{self, MaybeUninit};
use std::path::Path;
use doublets::data::LinkReference;
use doublets::mem::{FileMapped, RawMem, Result as MemResult};
use doublets::unit::LinkPart;
pub unsafe trait FileMappedValue {}
macro_rules! impl_file_mapped_value_for_unsigned {
($($ty:ty),+ $(,)?) => {
$(
unsafe impl FileMappedValue for $ty {}
)+
};
}
impl_file_mapped_value_for_unsigned!(u8, u16, u32, u64, u128, usize);
unsafe impl<T: FileMappedValue + LinkReference> FileMappedValue for LinkPart<T> {}
#[derive(Debug)]
pub struct PersistentFileMapped<T>(FileMapped<T>);
impl<T> PersistentFileMapped<T> {
pub fn from_path<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
FileMapped::from_path(path).map(Self)
}
pub fn new(file: File) -> io::Result<Self> {
FileMapped::new(file).map(Self)
}
pub fn inner(&self) -> &FileMapped<T> {
&self.0
}
}
impl<T: FileMappedValue> PersistentFileMapped<T> {
pub fn open_existing(file: File) -> io::Result<Self> {
let byte_len = file.metadata()?.len();
let mut mapped = FileMapped::new(file)?;
let item_size = mem::size_of::<T>() as u64;
debug_assert_ne!(item_size, 0, "FileMappedValue must not be zero-sized");
let capacity = usize::try_from(byte_len / item_size).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"file capacity does not fit in usize",
)
})?;
if capacity != 0 {
unsafe { mapped.grow_assumed(capacity) }.map_err(|error| match error {
doublets::mem::Error::System(error) => error,
error => io::Error::other(error),
})?;
}
Ok(Self(mapped))
}
}
impl<T> RawMem for PersistentFileMapped<T> {
type Item = T;
fn allocated(&self) -> &[Self::Item] {
self.0.allocated()
}
fn allocated_mut(&mut self) -> &mut [Self::Item] {
self.0.allocated_mut()
}
unsafe fn grow(
&mut self,
addition: usize,
fill: impl FnOnce(usize, (&mut [Self::Item], &mut [MaybeUninit<Self::Item>])),
) -> MemResult<&mut [Self::Item]> {
unsafe { self.0.grow(addition, fill) }
}
fn shrink(&mut self, cap: usize) -> MemResult<()> {
self.0.shrink(cap)
}
fn grow_filled(&mut self, cap: usize, value: Self::Item) -> MemResult<&mut [Self::Item]>
where
Self::Item: Clone,
{
unsafe { self.0.grow_filled_exact(cap, value) }
}
}