use crate::{Table, TableBuilderError, TableError};
pub use serde::{de::DeserializeOwned, Serialize};
use std::path::{Path, PathBuf};
use std::{fmt::Debug, marker::PhantomData};
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub enum WriteType {
Manual,
#[default]
Automatic,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RWPolicy {
ReadOnly,
Write(WriteType),
}
impl Default for RWPolicy {
fn default() -> Self {
RWPolicy::Write(WriteType::default())
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum ExtensionPolicy {
OnlyJsonFiles,
#[default]
IgnoreNonJson,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum ContentPolicy {
IgnoreSerdeErrors,
#[default]
PromoteSerdeErrors,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct TableMetadata {
pub rw_policy: RWPolicy,
pub extension_policy: ExtensionPolicy,
pub content_policy: ContentPolicy,
}
#[derive(Debug)]
#[must_use]
pub struct TableBuilder<T> {
data: PhantomData<T>,
dir: PathBuf,
metadata: TableMetadata,
}
impl<T> TableBuilder<T> {
pub fn new<Q: AsRef<Path>>(dir: Q) -> Self {
Self {
data: PhantomData,
dir: dir.as_ref().to_path_buf(),
metadata: TableMetadata {
rw_policy: RWPolicy::Write(WriteType::Automatic),
extension_policy: ExtensionPolicy::IgnoreNonJson,
content_policy: ContentPolicy::PromoteSerdeErrors,
},
}
}
pub fn set_manual_write(mut self) -> Self {
self.metadata.rw_policy = RWPolicy::Write(WriteType::Manual);
self
}
pub fn set_auto_write(mut self) -> Self {
self.metadata.rw_policy = RWPolicy::Write(WriteType::Automatic);
self
}
pub fn set_read_only(mut self) -> Self {
self.metadata.rw_policy = RWPolicy::ReadOnly;
self
}
pub fn set_read_non_json_is_error(mut self) -> Self {
self.metadata.extension_policy = ExtensionPolicy::OnlyJsonFiles;
self
}
pub fn set_ignore_de_errors(mut self) -> Self {
self.metadata.content_policy = ContentPolicy::IgnoreSerdeErrors;
self
}
pub fn load(self) -> Result<Table<T>, TableError>
where
T: Serialize + DeserializeOwned,
{
Table::load(&self.dir, Some(self.metadata))
}
pub fn build(self) -> Result<Table<T>, TableBuilderError>
where
T: Serialize + DeserializeOwned,
{
Table::new(&self.dir, self.metadata)
}
}
impl<T> Default for TableBuilder<T> {
fn default() -> Self {
Self {
data: PhantomData,
dir: "".into(),
metadata: TableMetadata {
rw_policy: RWPolicy::Write(WriteType::Automatic),
extension_policy: ExtensionPolicy::IgnoreNonJson,
content_policy: ContentPolicy::PromoteSerdeErrors,
},
}
}
}