vld 0.3.0

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
use serde_json::Value;

use crate::error::VldError;
use crate::schema::VldSchema;

/// Wraps a schema to make it optional.
///
/// If the value is `null` or missing, returns `Ok(None)`.
/// Otherwise, delegates to the inner schema and wraps the result in `Some`.
pub struct ZOptional<T: VldSchema> {
    inner: T,
}

impl<T: VldSchema> ZOptional<T> {
    pub fn new(inner: T) -> Self {
        Self { inner }
    }

    /// Access the inner schema (for JSON Schema generation).
    pub fn inner_schema(&self) -> &T {
        &self.inner
    }
}

impl<T: VldSchema> VldSchema for ZOptional<T> {
    type Output = Option<T::Output>;

    fn parse_value(&self, value: &Value) -> Result<Option<T::Output>, VldError> {
        if value.is_null() {
            return Ok(None);
        }
        self.inner.parse_value(value).map(Some)
    }
}