use crate::error::Error;
use crate::extension::JsonMapExt;
use crate::{JsonMap, SharedString};
#[derive(Debug, Default)]
pub struct Validation {
failed_entries: Vec<(SharedString, Error)>,
}
impl Validation {
#[inline]
pub fn new() -> Self {
Self {
failed_entries: Vec::new(),
}
}
pub fn from_entry(key: impl Into<SharedString>, err: impl Into<Error>) -> Self {
let failed_entries = vec![(key.into(), err.into())];
Self { failed_entries }
}
#[inline]
pub fn add(&mut self, key: impl Into<SharedString>, message: impl Into<SharedString>) {
self.failed_entries.push((key.into(), Error::new(message)));
}
#[inline]
pub fn add_fail(&mut self, key: impl Into<SharedString>, err: impl Into<Error>) {
self.failed_entries.push((key.into(), err.into()));
}
#[inline]
pub fn is_contain_key(&self, key: &str) -> bool {
self.failed_entries.iter().any(|(f, _)| f == key)
}
#[inline]
pub fn is_success(&self) -> bool {
self.failed_entries.is_empty()
}
#[must_use]
pub fn into_json_map(self) -> JsonMap {
let failed_entries = self.failed_entries;
let mut map = JsonMap::with_capacity(failed_entries.len());
for (key, err) in failed_entries {
map.upsert(key, err.to_string());
}
map
}
}