use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::{CacheError, CacheResult};
#[derive(Debug)]
pub struct CacheObject {
name: String,
path: PathBuf,
id: u32,
created_at: SystemTime
}
impl CacheObject {
pub fn new(
name: String,
path: PathBuf,
id: u32
) -> Self {
let obj = CacheObject {
name,
path,
id,
created_at: SystemTime::now()
};
obj
}
pub fn name(&self) -> &str {
&self.name
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn created_at(&self) -> SystemTime {
self.created_at
}
pub fn id(&self) -> u32 {
self.id
}
pub fn get_file(&self) -> CacheResult<std::fs::File> {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&self.path)
.map_err(|e| CacheError::Io(e))
}
pub fn get_string(&self) -> CacheResult<String> {
std::fs::read_to_string(&self.path)
.map_err(|e| CacheError::Io(e))
}
pub fn write_string(&self, content: &str) -> CacheResult<()> {
std::fs::write(&self.path, content)
.map_err(|e| CacheError::Io(e))
}
pub fn write_bytes(&self, content: &[u8]) -> CacheResult<()> {
std::fs::write(&self.path, content)
.map_err(|e| CacheError::Io(e))
}
pub fn get_bytes(&self) -> CacheResult<Vec<u8>> {
std::fs::read(&self.path)
.map_err(|e| CacheError::Io(e))
}
pub fn delete(&self) -> CacheResult<()> {
if self.path.exists() {
std::fs::remove_file(&self.path)
.map_err(|e| CacheError::Io(e))?;
}
Ok(())
}
pub fn exists(&self) -> bool {
self.path.exists()
}
pub fn size(&self) -> CacheResult<u64> {
std::fs::metadata(&self.path)
.map(|metadata| metadata.len())
.map_err(|e| CacheError::Io(e))
}
#[deprecated(note="This enumeration has been deprecated due to issues, and it now only returns false")]
pub fn is_expired(&self) -> bool {
false
}
}
impl Clone for CacheObject {
fn clone(&self) -> Self {
CacheObject {
name: self.name.clone(),
path: self.path.clone(),
id: self.id,
created_at: self.created_at
}
}
}