use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use crate::decimal::Decimal;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PathSegment {
Key(&'static str),
Index(usize),
}
#[derive(Clone, Debug, Default)]
pub struct ValidationPath {
segments: Vec<PathSegment>,
}
impl ValidationPath {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn push_key(&mut self, key: &'static str) {
self.segments.push(PathSegment::Key(key));
}
pub fn push_index(&mut self, index: usize) {
self.segments.push(PathSegment::Index(index));
}
pub fn pop(&mut self) {
self.segments.pop();
}
#[must_use]
pub fn to_pointer(&self) -> String {
if self.segments.is_empty() {
return String::new();
}
let mut out = String::new();
for segment in &self.segments {
out.push('/');
match segment {
PathSegment::Key(k) => {
out.push_str(&k.replace('~', "~0").replace('/', "~1"));
}
PathSegment::Index(i) => {
out.push_str(&i.to_string());
}
}
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ViolationKind {
Occurrence,
Type,
Property,
UnknownEnumValue,
UnknownField,
Protocol,
}
impl fmt::Display for ViolationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
ViolationKind::Occurrence => "occurrence",
ViolationKind::Type => "type",
ViolationKind::Property => "property",
ViolationKind::UnknownEnumValue => "unknown enum value",
ViolationKind::UnknownField => "unknown field",
ViolationKind::Protocol => "protocol",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Violation {
pub path: String,
pub kind: ViolationKind,
pub reason: String,
}
impl fmt::Display for Violation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
write!(f, "{}", self.reason)
} else {
write!(f, "{}: {}", self.path, self.reason)
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Violations {
items: Vec<Violation>,
}
impl Violations {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.items.len()
}
#[must_use]
pub fn as_slice(&self) -> &[Violation] {
&self.items
}
#[must_use]
pub fn first(&self) -> Option<&Violation> {
self.items.first()
}
pub fn push(&mut self, path: &ValidationPath, kind: ViolationKind, reason: impl Into<String>) {
self.items.push(Violation {
path: path.to_pointer(),
kind,
reason: reason.into(),
});
}
pub fn retain_kinds(&mut self, mut keep: impl FnMut(ViolationKind) -> bool) {
self.items.retain(|v| keep(v.kind));
}
#[must_use]
pub fn into_vec(self) -> Vec<Violation> {
self.items
}
}
impl IntoIterator for Violations {
type Item = Violation;
type IntoIter = alloc::vec::IntoIter<Violation>;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
impl fmt::Display for Violations {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, v) in self.items.iter().enumerate() {
if i > 0 {
f.write_str("; ")?;
}
write!(f, "{v}")?;
}
Ok(())
}
}
#[cfg(feature = "std")]
impl std::error::Error for Violations {}
pub trait Validate {
fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations);
fn validate(&self) -> Result<(), Violations> {
let mut path = ValidationPath::new();
let mut out = Violations::new();
self.validate_at(&mut path, &mut out);
if out.is_empty() { Ok(()) } else { Err(out) }
}
}
impl<T: Validate> Validate for Option<T> {
fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
if let Some(v) = self {
v.validate_at(path, out);
}
}
}
impl<T: Validate> Validate for Vec<T> {
fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
for (index, item) in self.iter().enumerate() {
path.push_index(index);
item.validate_at(path, out);
path.pop();
}
}
}
pub fn string(
value: &str,
min: Option<u32>,
max: Option<u32>,
path: &ValidationPath,
out: &mut Violations,
) {
let len = value.chars().count();
if let Some(max) = max {
if len > max as usize {
out.push(
path,
ViolationKind::Property,
format!("maxLength {max} exceeded (got {len} characters)"),
);
}
}
if let Some(min) = min {
if len < min as usize {
out.push(
path,
ViolationKind::Property,
format!("minLength {min} not reached (got {len} characters)"),
);
}
}
}
pub fn int_range(
value: i64,
min: Option<i64>,
max: Option<i64>,
path: &ValidationPath,
out: &mut Violations,
) {
if let Some(min) = min {
if value < min {
out.push(
path,
ViolationKind::Property,
format!("minimum {min} violated (got {value})"),
);
}
}
if let Some(max) = max {
if value > max {
out.push(
path,
ViolationKind::Property,
format!("maximum {max} violated (got {value})"),
);
}
}
}
pub fn range(
value: Decimal,
min: Option<Decimal>,
max: Option<Decimal>,
path: &ValidationPath,
out: &mut Violations,
) {
if let Some(min) = min {
if value < min {
out.push(
path,
ViolationKind::Property,
format!("minimum {min} violated (got {value})"),
);
}
}
if let Some(max) = max {
if value > max {
out.push(
path,
ViolationKind::Property,
format!("maximum {max} violated (got {value})"),
);
}
}
}
pub fn list_len(
len: usize,
min: Option<u32>,
max: Option<u32>,
path: &ValidationPath,
out: &mut Violations,
) {
if let Some(min) = min {
if len < min as usize {
out.push(
path,
ViolationKind::Occurrence,
format!("minItems {min} not reached (got {len})"),
);
}
}
if let Some(max) = max {
if len > max as usize {
out.push(
path,
ViolationKind::Occurrence,
format!("maxItems {max} exceeded (got {len})"),
);
}
}
}
pub fn unknown_enum_value(
value: &str,
type_name: &'static str,
path: &ValidationPath,
out: &mut Violations,
) {
out.push(
path,
ViolationKind::UnknownEnumValue,
format!("{value:?} is not a defined value of {type_name}"),
);
}