Simplify `JsonDb::load_or_else` signature to be more idiomatic

main
xenofem 2022-08-16 02:35:02 -04:00
parent add3209b91
commit 1a6bb519ef
2 changed files with 6 additions and 8 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "jsondb"
version = "0.2.1"
version = "0.3.0"
edition = "2021"
authors = ["xenofem <xenofem@xeno.science>"]
license = "MIT"

View File

@ -24,7 +24,6 @@ use std::{
cmp::Ordering,
ffi::OsString,
fmt::Debug,
future::Future,
io::ErrorKind,
ops::Deref,
path::{Path, PathBuf},
@ -134,7 +133,7 @@ impl<T: Schema + Default> JsonDb<T> {
/// initializing it with the schema's default value if it does not
/// exist.
pub async fn load(path: PathBuf) -> Result<JsonDb<T>, Error> {
Self::load_or_else(path, || std::future::ready(Ok(T::default()))).await
Self::load_or_else(path, T::default).await
}
}
@ -164,16 +163,15 @@ impl<T: Schema> JsonDb<T> {
/// initializing it with the provided default value if it does not
/// exist.
pub async fn load_or(path: PathBuf, default: T) -> Result<JsonDb<T>, Error> {
Self::load_or_else(path, || std::future::ready(Ok(default))).await
Self::load_or_else(path, || default).await
}
/// Load a [`JsonDb`] from a given file, creating it and
/// initializing it with the provided function if it does not
/// exist.
pub async fn load_or_else<F, Fut>(path: PathBuf, default: F) -> Result<JsonDb<T>, Error>
pub async fn load_or_else<F>(path: PathBuf, default: F) -> Result<JsonDb<T>, Error>
where
F: FnOnce() -> Fut,
Fut: Future<Output = std::io::Result<T>>,
F: FnOnce() -> T,
{
let open_result = File::open(&path).await;
let data = match open_result {
@ -184,7 +182,7 @@ impl<T: Schema> JsonDb<T> {
}
Err(e) => {
if let ErrorKind::NotFound = e.kind() {
default().await?
default()
} else {
return Err(e.into());
}