use crate::{Parse, Source};
use tanzim_value::{Error, LocatedValue};
pub type BoxedParseFn = Box<dyn Fn(&Source, &[u8], &[Source]) -> Result<LocatedValue, Error>>;
pub type BoxedValidatorFn = Box<dyn Fn(&[u8]) -> Option<bool>>;
pub struct Closure {
name: String,
parser: BoxedParseFn,
validator: BoxedValidatorFn,
supported_format_list: Vec<String>,
}
impl Closure {
pub fn new<N: AsRef<str>, F: AsRef<str>>(
name: N,
supported_format: F,
parser: BoxedParseFn,
) -> Self {
Self {
name: name.as_ref().to_string(),
parser,
validator: Box::new(|_| None),
supported_format_list: vec![supported_format.as_ref().to_string()],
}
}
pub fn with_validator(mut self, validator: BoxedValidatorFn) -> Self {
self.validator = validator;
self
}
pub fn with_format_list<N: AsRef<str>>(mut self, format_list: &[N]) -> Self {
let mut formats = Vec::new();
for format in format_list {
formats.push(format.as_ref().to_string());
}
self.supported_format_list = formats;
self
}
}
impl Parse for Closure {
fn name(&self) -> &str {
self.name.as_str()
}
fn supported_format_list(&self) -> Vec<String> {
self.supported_format_list.clone()
}
fn parse(
&self,
source: &Source,
bytes: &[u8],
other_source_list: &[Source],
) -> Result<LocatedValue, Error> {
(self.parser)(source, bytes, other_source_list)
}
fn is_format_supported(&self, bytes: &[u8]) -> Option<bool> {
(self.validator)(bytes)
}
}