You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
1.7 KiB
96 lines
1.7 KiB
use std::ops::RangeBounds;
|
|
use std::slice::SliceIndex;
|
|
use std::{fs,io};
|
|
use std::path::Path;
|
|
use std::ops::Drop;
|
|
use memmap::MmapMut;
|
|
|
|
#[derive(Debug)]
|
|
pub struct MemoryMapMut
|
|
{
|
|
map: MmapMut,
|
|
file: fs::File,
|
|
}
|
|
|
|
impl Drop for MemoryMapMut
|
|
{
|
|
fn drop(&mut self)
|
|
{
|
|
let _ = self.map.flush();
|
|
}
|
|
}
|
|
|
|
impl AsRef<[u8]> for MemoryMapMut
|
|
{
|
|
fn as_ref(&self) -> &[u8]
|
|
{
|
|
&self.map[..]
|
|
}
|
|
}
|
|
|
|
impl AsMut<[u8]> for MemoryMapMut
|
|
{
|
|
fn as_mut(&mut self) -> &mut [u8]
|
|
{
|
|
&mut self.map[..]
|
|
}
|
|
}
|
|
|
|
impl MemoryMapMut
|
|
{
|
|
/// Unmap this file and return the fd
|
|
pub fn unmap(self) -> fs::File
|
|
{
|
|
use std::mem;
|
|
let mut this = mem::ManuallyDrop::new(self);
|
|
unsafe {
|
|
let map = (&mut this.map as *mut MmapMut).read();
|
|
let file = (&mut this.file as *mut fs::File).read();
|
|
|
|
let _ = map.flush();
|
|
|
|
drop(map);
|
|
file
|
|
}
|
|
}
|
|
#[inline] pub fn as_slice_mut(&mut self) -> &mut [u8]
|
|
{
|
|
self.as_mut()
|
|
}
|
|
#[inline] pub fn as_slice(&self) -> &[u8]
|
|
{
|
|
self.as_ref()
|
|
}
|
|
pub fn map(file: fs::File) -> io::Result<Self>
|
|
{
|
|
Ok(Self{
|
|
map: unsafe{ MmapMut::map_mut(&file)? },
|
|
file,
|
|
})
|
|
}
|
|
#[inline] pub fn len(&self) -> usize
|
|
{
|
|
self.map.len()
|
|
}
|
|
pub fn open(from: impl AsRef<Path>) -> io::Result<Self>
|
|
{
|
|
let file = fs::OpenOptions::new()
|
|
.create(true)
|
|
.truncate(true)
|
|
.write(true)
|
|
.read(true)
|
|
.open(from)?;
|
|
|
|
Ok(Self{
|
|
map: unsafe{ MmapMut::map_mut(&file)? },
|
|
file,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[inline] pub unsafe fn slice_mut<'a, 'b, T, R: RangeBounds<usize> + SliceIndex<[T], Output=[T]>>(what: &'a mut [T], range: R)-> &'b mut [T]
|
|
where 'a: 'b
|
|
{
|
|
&mut what[range]
|
|
}
|