Try to get rid of owned types
Inspired by https://www.youtube.com/watch?v=A4cKi7PTJSs. This turns a lot of cloning Strings and PathBufs into Rcs.
This commit is contained in:
parent
e3b425eb1c
commit
d091265d27
20 changed files with 343 additions and 232 deletions
|
|
@ -1,49 +1,46 @@
|
|||
use std::error::Error;
|
||||
use std::fs::read_dir;
|
||||
use std::path::PathBuf;
|
||||
use std::path::Path;
|
||||
use std::rc::Rc;
|
||||
use std::str::FromStr;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub trait Storage {
|
||||
fn write_filename(&self) -> PathBuf;
|
||||
fn read_filename(&self) -> Result<PathBuf, Box<dyn Error>>;
|
||||
fn write_filename(&self) -> Box<Path>;
|
||||
fn read_filename(&self) -> Result<Box<Path>, Box<dyn Error>>;
|
||||
fn recent_date(&self) -> Result<u64, Box<dyn Error>>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SimpleStorage(PathBuf);
|
||||
pub struct SimpleStorage(Rc<Path>);
|
||||
|
||||
impl SimpleStorage {
|
||||
#[must_use]
|
||||
pub const fn new(base: PathBuf) -> Self {
|
||||
pub const fn new(base: Rc<Path>) -> Self {
|
||||
Self(base)
|
||||
}
|
||||
|
||||
fn get_path(&self, date: Option<u64>) -> PathBuf {
|
||||
match date {
|
||||
Some(d) => self.0.join(d.to_string()),
|
||||
None => self.0.clone(),
|
||||
}
|
||||
fn get_path(&self, date: u64) -> Box<Path> {
|
||||
self.0.join(date.to_string()).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Storage for SimpleStorage {
|
||||
fn write_filename(&self) -> PathBuf {
|
||||
self.get_path(Some(
|
||||
fn write_filename(&self) -> Box<Path> {
|
||||
self.get_path(
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs(),
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
fn read_filename(&self) -> Result<PathBuf, Box<dyn Error>> {
|
||||
Ok(self.get_path(Some(self.recent_date()?)))
|
||||
fn read_filename(&self) -> Result<Box<Path>, Box<dyn Error>> {
|
||||
Ok(self.get_path(self.recent_date()?))
|
||||
}
|
||||
|
||||
fn recent_date(&self) -> Result<u64, Box<dyn Error>> {
|
||||
let dir = self.get_path(None);
|
||||
read_dir(dir)?
|
||||
read_dir(&self.0)?
|
||||
.map(|entry| {
|
||||
entry
|
||||
.ok()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue