use std::{io, time::SystemTime};
use crate::{
common::{
configs::{CHAR_LIST, RANDOMNESS_LENGTH},
errors::RowIDError,
},
functions::{
decode::{_decode, DecodeOptions},
encode::{_encode, EncodeOptions},
generate::{_generate, GenerateOptions, GenerateResult},
get_randomness::{_get_randomness, GetRandomnessOptions},
rowid::{_rowid, RowIDOptions},
verify::{_verify, VerifyOptions, VerifyResult},
},
};
#[derive(Debug, Clone)]
pub struct RowIDWithConfigState {
pub char_list: String,
pub randomness_length: usize,
}
#[derive(Debug, Clone)]
pub struct RowIDWithConfigResult {
pub state: RowIDWithConfigState,
}
impl RowIDWithConfigResult {
pub fn rowid(&self) -> String {
_rowid(RowIDOptions {
char_list: &self.state.char_list,
randomness_length: self.state.randomness_length,
})
}
pub fn encode<T: Into<SystemTime>>(
&self,
system_time: T,
) -> io::Result<String> {
_encode(EncodeOptions {
char_list: &self.state.char_list,
system_time: system_time.into(),
})
}
pub fn decode<S: AsRef<str>>(
&self,
encoded: S,
) -> io::Result<SystemTime> {
_decode(DecodeOptions {
char_list: &self.state.char_list,
encoded: encoded.as_ref(),
})
}
pub fn generate<T: Into<SystemTime>>(
&self,
system_time: T,
randomness_length: Option<usize>,
) -> GenerateResult {
_generate(GenerateOptions {
char_list: &self.state.char_list,
system_time: system_time.into(),
randomness_length: match randomness_length {
| Some(l) => l,
| None => self.state.randomness_length,
},
})
}
pub fn verify<S: AsRef<str>>(
&self,
encoded: S,
) -> VerifyResult {
_verify(VerifyOptions {
char_list: &self.state.char_list,
encoded: encoded.as_ref(),
})
}
pub fn get_randomness(
&self,
randomness_length: usize,
) -> String {
_get_randomness(GetRandomnessOptions {
char_list: &self.state.char_list,
randomness_length,
})
}
}
#[derive(Debug, Clone)]
pub struct RowIDWithConfig {
state: RowIDWithConfigState,
}
impl RowIDWithConfig {
pub fn new() -> Self {
Self {
state: RowIDWithConfigState {
char_list: CHAR_LIST.to_string(),
randomness_length: RANDOMNESS_LENGTH,
},
}
}
pub fn char_list<S: Into<String>>(
mut self,
list: S,
) -> Self {
self.state.char_list = list.into();
self
}
pub fn randomness_length(
mut self,
length: usize,
) -> Self {
self.state.randomness_length = length;
self
}
pub fn done(self) -> io::Result<RowIDWithConfigResult> {
if self.state.char_list.len() < 28 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
RowIDError::CharListLength.as_str(),
));
}
Ok(RowIDWithConfigResult {
state: RowIDWithConfigState {
char_list: self.state.char_list,
randomness_length: self.state.randomness_length,
},
})
}
}
impl Default for RowIDWithConfig {
fn default() -> Self {
Self::new()
}
}