Move mmap to storages from example

This commit is contained in:
Igor Katson 2024-05-01 11:46:10 +01:00
parent 3398babba9
commit bc5098355f
4 changed files with 63 additions and 62 deletions

View file

@ -0,0 +1,60 @@
use anyhow::Context;
use memmap2::{MmapMut, MmapOptions};
use parking_lot::RwLock;
use crate::{FileInfos, ManagedTorrentInfo};
use super::{StorageFactory, TorrentStorage};
pub struct MmapStorageFactory {}
struct MmapStorage {
mmap: RwLock<MmapMut>,
file_infos: FileInfos,
}
impl StorageFactory for MmapStorageFactory {
fn init_storage(
&self,
info: &ManagedTorrentInfo,
) -> anyhow::Result<Box<dyn crate::storage::TorrentStorage>> {
Ok(Box::new(MmapStorage {
mmap: RwLock::new(
MmapOptions::new()
.len(info.lengths.total_length().try_into()?)
.map_anon()?,
),
file_infos: info.file_infos.clone(),
}))
}
}
impl TorrentStorage for MmapStorage {
fn pread_exact(&self, file_id: usize, offset: u64, buf: &mut [u8]) -> anyhow::Result<()> {
let start: usize = (self.file_infos[file_id].offset_in_torrent + offset).try_into()?;
let end = start + buf.len();
buf.copy_from_slice(self.mmap.read().get(start..end).context("bad range")?);
Ok(())
}
fn pwrite_all(&self, file_id: usize, offset: u64, buf: &[u8]) -> anyhow::Result<()> {
let start: usize = (self.file_infos[file_id].offset_in_torrent + offset).try_into()?;
let end = start + buf.len();
let mut g = self.mmap.write();
let target = g.get_mut(start..end).context("bad range")?;
target.copy_from_slice(buf);
Ok(())
}
fn remove_file(&self, _file_id: usize, _filename: &std::path::Path) -> anyhow::Result<()> {
Ok(())
}
fn ensure_file_length(&self, _file_id: usize, _length: u64) -> anyhow::Result<()> {
Ok(())
}
fn take(&self) -> anyhow::Result<Box<dyn TorrentStorage>> {
anyhow::bail!("not implemented")
}
}

View file

@ -1,5 +1,6 @@
pub mod example;
pub mod filesystem;
pub mod mmap;
use std::{any::Any, path::Path};