Replaced filename string with PathBuf.

This commit is contained in:
Jeff Baskin 2023-03-05 00:19:11 -05:00
parent 691ab6a27e
commit 8fada737ac

View File

@ -1,7 +1,7 @@
use super::{DBError, FileData, SessionData, Store};
use async_std::{
fs::{read, remove_file, write},
path::Path,
path::{Path, PathBuf},
};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
@ -10,6 +10,8 @@ use std::{
time::{Duration, Instant},
};
const ENTRY: &str = "EntryPoint";
#[derive(Clone)]
enum DataType {
DBMap(Store),
@ -86,16 +88,21 @@ impl FileData<Self> for DataType {
struct Entry {
data: DataType,
filename: String,
filename: PathBuf,
last_used: Cell<Instant>,
}
impl Entry {
async fn new(filename: String, data: DataType) -> Result<Self, DBError> {
if Path::new(&filename).exists().await {
async fn new<P>(filename: P, data: DataType) -> Result<Self, DBError>
where
P: Into<PathBuf>,
{
let pathbuf = filename.into();
if pathbuf.as_path().exists().await {
// if Path::new(&filename).exists().await {
return Err(DBError::new("entry already exists"));
} else {
match write(&filename, data.to_bytes()).await {
match write(&pathbuf, data.to_bytes()).await {
Ok(_) => (),
Err(err) => {
let mut error = DBError::new("failed to write");
@ -106,13 +113,17 @@ impl Entry {
}
Ok(Self {
data: data,
filename: filename,
filename: pathbuf,
last_used: Cell::new(Instant::now()),
})
}
async fn get(filename: &str) -> Result<Self, DBError> {
let content = match read(filename).await {
async fn get<P>(filename: P) -> Result<Self, DBError>
where
P: Into<PathBuf>,
{
let pathbuf = filename.into();
let content = match read(&pathbuf).await {
Ok(text) => text,
Err(err) => {
let mut error = DBError::new("read error");
@ -130,7 +141,7 @@ impl Entry {
};
Ok(Self {
data: data,
filename: filename.to_string(),
filename: pathbuf,
last_used: Cell::new(Instant::now()),
})
}
@ -173,8 +184,15 @@ impl Entry {
struct Cache;
impl Cache {
async fn new(dir: &str) -> Self {
Self
async fn new<P>(dir: P) -> Self
where
P: Into<PathBuf>,
{
let pathbuf = dir.into();
let entry = pathbuf.as_path().join(ENTRY);
let store = DataType::new("store").unwrap();
Entry::new(entry, store).await.unwrap();
Self {}
}
}
@ -463,7 +481,7 @@ mod entry {
output.data().list(["database"].to_vec()).unwrap(),
data.list(["database"].to_vec()).unwrap()
);
assert_eq!(output.filename, filename);
assert_eq!(output.filename.to_str().unwrap(), filename);
assert!(
Duration::from_secs(1) > item.elapsed(),
"last_used should have been reset."
@ -568,5 +586,16 @@ mod cache {
async fn create() {
let dir = tempdir().unwrap();
Cache::new(dir.path().to_str().unwrap()).await;
let epoint = dir.path().join(ENTRY);
assert!(
epoint.is_file(),
"{} did not get created.",
epoint.display()
);
let entry = Entry::get(epoint.to_str().unwrap()).await.unwrap();
assert_eq!(
entry.data().list(["database"].to_vec()).unwrap(),
Vec::<String>::new()
);
}
}