use crate::error::ValidationError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq)]
pub enum ParseResult<T> {
Success(T),
PartialSuccess(T, Vec<ValidationError>),
Failure(Vec<ValidationError>),
}
impl<T> ParseResult<T> {
pub fn is_success(&self) -> bool {
matches!(self, ParseResult::Success(_))
}
pub fn is_failure(&self) -> bool {
matches!(self, ParseResult::Failure(_))
}
pub fn value(&self) -> Option<&T> {
match self {
ParseResult::Success(val) | ParseResult::PartialSuccess(val, _) => Some(val),
ParseResult::Failure(_) => None,
}
}
pub fn errors(&self) -> Vec<&ValidationError> {
match self {
ParseResult::Success(_) => vec![],
ParseResult::PartialSuccess(_, errors) | ParseResult::Failure(errors) => {
errors.iter().collect()
}
}
}
pub fn to_result(self) -> Result<T, Vec<ValidationError>> {
match self {
ParseResult::Success(val) => Ok(val),
ParseResult::PartialSuccess(val, _) => Ok(val),
ParseResult::Failure(errors) => Err(errors),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParserConfig {
pub fail_fast: bool,
pub validate_optional_fields: bool,
pub collect_all_errors: bool,
}
impl Default for ParserConfig {
fn default() -> Self {
ParserConfig {
fail_fast: false,
validate_optional_fields: true,
collect_all_errors: true,
}
}
}
impl ParserConfig {
pub fn fail_fast() -> Self {
ParserConfig {
fail_fast: true,
validate_optional_fields: true,
collect_all_errors: false,
}
}
pub fn lenient() -> Self {
ParserConfig {
fail_fast: false,
validate_optional_fields: false,
collect_all_errors: false,
}
}
}
#[derive(Debug, Default)]
pub struct ErrorCollector {
errors: Vec<ValidationError>,
has_critical_errors: bool,
}
impl ErrorCollector {
pub fn new() -> Self {
ErrorCollector {
errors: Vec::new(),
has_critical_errors: false,
}
}
pub fn add_error(&mut self, error: ValidationError) {
self.errors.push(error);
}
pub fn add_critical_error(&mut self, error: ValidationError) {
self.has_critical_errors = true;
self.errors.push(error);
}
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
pub fn has_critical_errors(&self) -> bool {
self.has_critical_errors
}
pub fn errors(self) -> Vec<ValidationError> {
self.errors
}
pub fn error_count(&self) -> usize {
self.errors.len()
}
}