use crate::{Content, ContentPath, ContentType};
use filecache::{CacheType, FileCache, RandomAccessFile, RandomAccessFlags};
use std::{fs, path::Path};
enum FileContentStatus {
NotOpened,
Opened(FileCache<filecache::RandomAccessFile>),
Error,
}
pub struct FileContent<T: ContentType> {
path: ContentPath,
content_type: Option<T>,
status: FileContentStatus,
size: u64,
exclusive: bool,
}
impl<T: ContentType> FileContent<T> {
pub fn new(path: impl AsRef<Path>, exclusive: bool) -> Self {
Self {
path: ContentPath::from_os(path.as_ref()),
content_type: None,
status: FileContentStatus::NotOpened,
size: fs::metadata(path).map(|m| m.len()).unwrap_or(0),
exclusive,
}
}
pub fn with_content_type(path: impl AsRef<Path>, content_type: T, exclusive: bool) -> Self {
Self {
path: ContentPath::from_os(path.as_ref()),
content_type: Some(content_type),
status: FileContentStatus::NotOpened,
size: fs::metadata(path).map(|m| m.len()).unwrap_or(0),
exclusive,
}
}
pub fn with_size(path: impl AsRef<Path>, size: u64, exclusive: bool) -> Self {
Self {
path: ContentPath::from_os(path.as_ref()),
content_type: None,
status: FileContentStatus::NotOpened,
size,
exclusive,
}
}
fn open(&mut self) {
let (cache, flags) = if self.exclusive {
(CacheType::MemoryMap, RandomAccessFlags::Exclusive)
} else {
(CacheType::LRU { max_pages: 32 }, RandomAccessFlags::None)
};
match RandomAccessFile::open(self.path.as_path(), flags) {
Ok(reader) => match FileCache::new(cache, reader) {
Ok(file) => {
self.status = FileContentStatus::Opened(file);
}
Err(_) => {
self.status = FileContentStatus::Error;
}
},
Err(_) => {
self.status = FileContentStatus::Error;
}
}
}
}
impl<T: ContentType> Content<T> for FileContent<T> {
#[inline(always)]
fn content_type(&self) -> Option<T> {
self.content_type
}
#[inline(always)]
fn path(&self) -> &ContentPath {
&self.path
}
#[inline(always)]
fn size(&self) -> u64 {
match &self.status {
FileContentStatus::Opened(file) => file.len(),
FileContentStatus::NotOpened => self.size,
FileContentStatus::Error => 0,
}
}
#[inline(always)]
fn read(&mut self, offset: u64, count: u32) -> Option<&[u8]> {
if matches!(self.status, FileContentStatus::NotOpened) {
self.open();
}
match &mut self.status {
FileContentStatus::Opened(file) => {
let n = (count as usize).min(file.max_count());
file.read(offset, n).ok()
}
FileContentStatus::NotOpened | FileContentStatus::Error => None,
}
}
#[inline(always)]
fn set_content_type(&mut self, ty: T) {
self.content_type = Some(ty);
}
}