Skip to main content

vld/modifiers/
default_val.rs

1use serde_json::Value;
2
3use crate::error::VldError;
4use crate::schema::VldSchema;
5
6/// Wraps a schema to provide a default value when the input is `null` or missing.
7///
8/// - If the value is `null` → returns the default value.
9/// - If the value is present and valid → returns the parsed value.
10/// - If the value is present but invalid → returns an error (NOT the default).
11pub struct ZDefault<T: VldSchema>
12where
13    T::Output: Clone,
14{
15    inner: T,
16    default_value: T::Output,
17}
18
19impl<T: VldSchema> ZDefault<T>
20where
21    T::Output: Clone,
22{
23    pub fn new(inner: T, default_value: T::Output) -> Self {
24        Self {
25            inner,
26            default_value,
27        }
28    }
29
30    /// Access the inner schema (for JSON Schema generation).
31    pub fn inner_schema(&self) -> &T {
32        &self.inner
33    }
34}
35
36impl<T: VldSchema> VldSchema for ZDefault<T>
37where
38    T::Output: Clone,
39{
40    type Output = T::Output;
41
42    fn parse_value(&self, value: &Value) -> Result<T::Output, VldError> {
43        if value.is_null() {
44            return Ok(self.default_value.clone());
45        }
46        self.inner.parse_value(value)
47    }
48}