use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub enum ValidationResult<T> {
Success(T),
Failure(Vec<ValidationIssue>),
}
impl<T> ValidationResult<T> {
pub fn success(value: T) -> Self {
ValidationResult::Success(value)
}
pub fn failure(message: impl Into<String>) -> Self {
ValidationResult::Failure(vec![ValidationIssue::new(message)])
}
pub fn failure_at(message: impl Into<String>, path: Vec<PathSegment>) -> Self {
ValidationResult::Failure(vec![ValidationIssue::with_path(message, path)])
}
pub fn failures(issues: Vec<ValidationIssue>) -> Self {
ValidationResult::Failure(issues)
}
pub fn is_success(&self) -> bool {
matches!(self, ValidationResult::Success(_))
}
pub fn is_failure(&self) -> bool {
matches!(self, ValidationResult::Failure(_))
}
pub fn ok(self) -> Option<T> {
match self {
ValidationResult::Success(v) => Some(v),
ValidationResult::Failure(_) => None,
}
}
pub fn issues(&self) -> &[ValidationIssue] {
match self {
ValidationResult::Success(_) => &[],
ValidationResult::Failure(issues) => issues,
}
}
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> ValidationResult<U> {
match self {
ValidationResult::Success(v) => ValidationResult::Success(f(v)),
ValidationResult::Failure(issues) => ValidationResult::Failure(issues),
}
}
pub fn with_path_prefix(self, segment: PathSegment) -> Self {
match self {
ValidationResult::Success(v) => ValidationResult::Success(v),
ValidationResult::Failure(issues) => {
let issues = issues
.into_iter()
.map(|mut issue| {
let mut new_path = vec![segment.clone()];
if let Some(path) = issue.path.take() {
new_path.extend(path);
}
issue.path = Some(new_path);
issue
})
.collect();
ValidationResult::Failure(issues)
}
}
}
}
impl<T: Serialize> Serialize for ValidationResult<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[derive(Serialize)]
struct SuccessResult<'a, T> {
value: &'a T,
}
#[derive(Serialize)]
struct FailureResult<'a> {
issues: &'a [ValidationIssue],
}
match self {
ValidationResult::Success(v) => SuccessResult { value: v }.serialize(serializer),
ValidationResult::Failure(issues) => FailureResult { issues }.serialize(serializer),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationIssue {
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<Vec<PathSegment>>,
}
impl ValidationIssue {
pub fn new(message: impl Into<String>) -> Self {
ValidationIssue {
message: message.into(),
path: None,
}
}
pub fn with_path(message: impl Into<String>, path: Vec<PathSegment>) -> Self {
ValidationIssue {
message: message.into(),
path: Some(path),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum PathSegment {
Key(String),
Index(usize),
}
impl From<String> for PathSegment {
fn from(s: String) -> Self {
PathSegment::Key(s)
}
}
impl From<&str> for PathSegment {
fn from(s: &str) -> Self {
PathSegment::Key(s.to_string())
}
}
impl From<usize> for PathSegment {
fn from(i: usize) -> Self {
PathSegment::Index(i)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonSchemaTarget {
Draft202012,
Draft07,
OpenApi30,
}
impl JsonSchemaTarget {
pub fn schema_uri(&self) -> &'static str {
match self {
JsonSchemaTarget::Draft202012 => "https://json-schema.org/draft/2020-12/schema",
JsonSchemaTarget::Draft07 => "http://json-schema.org/draft-07/schema#",
JsonSchemaTarget::OpenApi30 => "", }
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_validation_result_success_serialization() {
let result: ValidationResult<i32> = ValidationResult::success(42);
let json = serde_json::to_value(&result).unwrap();
assert_eq!(json, json!({ "value": 42 }));
}
#[test]
fn test_validation_result_failure_serialization() {
let result: ValidationResult<i32> = ValidationResult::failure("Invalid");
let json = serde_json::to_value(&result).unwrap();
assert_eq!(json, json!({ "issues": [{ "message": "Invalid" }] }));
}
#[test]
fn test_validation_issue_with_path() {
let issue = ValidationIssue::with_path(
"Invalid value",
vec![PathSegment::Key("user".into()), PathSegment::Index(0)],
);
let json = serde_json::to_value(&issue).unwrap();
assert_eq!(
json,
json!({
"message": "Invalid value",
"path": ["user", 0]
})
);
}
#[test]
fn test_path_prefix() {
let result: ValidationResult<i32> = ValidationResult::failure("error");
let result = result.with_path_prefix(PathSegment::Key("field".into()));
if let ValidationResult::Failure(issues) = result {
assert_eq!(issues[0].path, Some(vec![PathSegment::Key("field".into())]));
}
}
}