vld 0.9.0

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use serde_json::Value;
use std::cmp::Ordering;

use crate::error::{IssueCode, ValidationIssue, VldError, issue_error};
use crate::schema::VldSchema;

use super::{Kind, Num, NumberCheck, ZInt};

/// Schema for number validation (`f64`). Created via [`vld::number()`](crate::number).
///
/// Use `.int()` to convert to integer validation (`i64`).
///
/// `NaN` never satisfies a bound check, and `.coerce()` rejects strings that
/// parse to `NaN` or infinity.
///
/// # Example
/// ```
/// use vld::prelude::*;
///
/// let schema = vld::number().min(0.0).max(100.0);
/// let int_schema = vld::number().int().min(0).max(100);
/// ```
#[derive(Clone)]
pub struct ZNumber {
    checks: Vec<NumberCheck>,
    pub(super) coerce: bool,
    /// `clamp()`: inclusive bounds clamp instead of failing.
    pub(super) clamp: bool,
    /// `one_of(...)`: the allowed values.
    one_of: Option<Vec<Num>>,
    custom_type_error: Option<String>,
    messages: crate::primitives::Messages,
}

impl ZNumber {
    /// Create the schema (the same as its `vld::` constructor function).
    pub fn new() -> Self {
        Self {
            checks: vec![],
            coerce: false,
            clamp: false,
            one_of: None,
            custom_type_error: None,
            messages: None,
        }
    }

    fn push(mut self, kind: Kind) -> Self {
        self.checks.push(NumberCheck { kind, msg: None });
        self
    }

    /// Set a custom error message for type mismatch (when the input is not a number).
    ///
    /// # Example
    /// ```
    /// use vld::prelude::*;
    /// let schema = vld::number().type_error("Must be a number!");
    /// let err = schema.parse(r#""hello""#).unwrap_err();
    /// assert!(err.issues[0].message.contains("Must be a number!"));
    /// ```
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    /// Override error messages in bulk by check key.
    ///
    /// The closure receives the check key (e.g. `"too_small"`, `"too_big"`,
    /// `"not_positive"`, `"not_multiple_of"`, `"not_safe"`)
    /// and should return `Some(new_message)` to replace, or `None` to keep the original.
    ///
    /// The closure is consulted when an issue is built, so it covers checks
    /// added before **and after** this call; a per-check message
    /// (`*_msg(...)`) takes precedence over it. A later call replaces it.
    ///
    /// # Example
    /// ```
    /// use vld::prelude::*;
    /// let schema = vld::number().min(0.0).max(100.0)
    ///     .with_messages(|key| match key {
    ///         "too_small" => Some("Must be >= 0".into()),
    ///         "too_big" => Some("Must be <= 100".into()),
    ///         _ => None,
    ///     });
    /// ```
    pub fn with_messages<F>(mut self, f: F) -> Self
    where
        F: Fn(&str) -> Option<String> + Send + Sync + 'static,
    {
        self.messages = Some(std::sync::Arc::new(f));
        self
    }

    pub(super) fn min_n(self, v: Num) -> Self {
        self.push(Kind::Min(v))
    }

    pub(super) fn max_n(self, v: Num) -> Self {
        self.push(Kind::Max(v))
    }

    pub(super) fn gt_n(self, v: Num) -> Self {
        self.push(Kind::Gt(v))
    }

    pub(super) fn lt_n(self, v: Num) -> Self {
        self.push(Kind::Lt(v))
    }

    pub(super) fn multiple_of_n(self, v: Num) -> Self {
        self.push(Kind::MultipleOf(v))
    }

    /// Minimum value (inclusive). Alias: `gte`.
    pub fn min(self, val: f64) -> Self {
        self.min_n(Num::F(val))
    }

    /// Maximum value (inclusive). Alias: `lte`.
    pub fn max(self, val: f64) -> Self {
        self.max_n(Num::F(val))
    }

    /// Greater than (exclusive).
    pub fn gt(self, val: f64) -> Self {
        self.gt_n(Num::F(val))
    }

    /// Greater than or equal (inclusive). Same as `min`.
    pub fn gte(self, val: f64) -> Self {
        self.min(val)
    }

    /// Less than (exclusive).
    pub fn lt(self, val: f64) -> Self {
        self.lt_n(Num::F(val))
    }

    /// Less than or equal (inclusive). Same as `max`.
    pub fn lte(self, val: f64) -> Self {
        self.max(val)
    }

    /// Must be positive (> 0).
    pub fn positive(self) -> Self {
        self.push(Kind::Positive)
    }

    /// Must be negative (< 0).
    pub fn negative(self) -> Self {
        self.push(Kind::Negative)
    }

    /// Must be non-negative (>= 0).
    pub fn non_negative(self) -> Self {
        self.push(Kind::NonNegative)
    }

    /// Must be non-positive (<= 0).
    pub fn non_positive(self) -> Self {
        self.push(Kind::NonPositive)
    }

    /// Must be a multiple of the given value.
    ///
    /// Uses a relative tolerance of `1e-9` so decimal steps like `0.1` work.
    /// A divisor of `0` never matches (every value is rejected).
    pub fn multiple_of(self, val: f64) -> Self {
        self.multiple_of_n(Num::F(val))
    }

    /// Must be within JavaScript's safe integer range (`-(2^53 - 1)` to `2^53 - 1`).
    pub fn safe(self) -> Self {
        self.push(Kind::Safe)
    }

    /// Convert to integer validation. Returns `ZInt` with `Output = i64`.
    pub fn int(self) -> ZInt {
        ZInt::from_number(self)
    }

    /// Coerce strings and booleans to numbers.
    ///
    /// Strings that parse to `NaN` or infinity are rejected.
    pub fn coerce(mut self) -> Self {
        self.coerce = true;
        self
    }

    /// Must equal one of `values` (`invalid_enum_value`; JSON Schema `enum`).
    ///
    /// ```
    /// use vld::prelude::*;
    /// let ratio = vld::number().one_of(&[0.5, 1.0, 2.0]);
    /// assert_eq!(ratio.parse("1").unwrap(), 1.0);
    /// assert_eq!(ratio.parse("3").unwrap_err().issues[0].code.key(), "invalid_enum_value");
    /// ```
    pub fn one_of(self, values: &[f64]) -> Self {
        self.one_of_n(values.iter().map(|v| Num::F(*v)).collect())
    }

    pub(super) fn one_of_n(mut self, values: Vec<Num>) -> Self {
        self.one_of = Some(values);
        self
    }

    /// Clamp values outside the inclusive bounds (`min` / `max`,
    /// `non_negative` / `non_positive`, `safe`) to the bound instead of failing.
    /// Integer schemas also saturate to their type (`u8`: `0..=255`), `f32`
    /// to its finite range. Exclusive bounds (`gt`, `lt`, `positive`,
    /// `negative`) still fail. The JSON Schema leaves out the clamped bounds.
    ///
    /// ```
    /// use vld::prelude::*;
    /// let volume = vld::number().int().min(0).max(100).clamp();
    /// assert_eq!(volume.parse("150").unwrap(), 100);
    /// assert_eq!(volume.parse("-5").unwrap(), 0);
    /// assert_eq!(vld::u8().clamp().parse("300").unwrap(), 255u8);
    /// ```
    pub fn clamp(mut self) -> Self {
        self.clamp = true;
        self
    }

    /// `n` moved into the inclusive bounds when `clamp()` is on.
    pub(super) fn clamped(&self, n: Num) -> Num {
        if !self.clamp {
            return n;
        }
        self.checks
            .iter()
            .fold(n, |n, c| match (c.kind.lower(), c.kind.upper()) {
                (Some((b, false)), _) if n.cmp(b) == Some(Ordering::Less) => b,
                (_, Some((b, false))) if n.cmp(b) == Some(Ordering::Greater) => b,
                _ => n,
            })
    }

    fn type_err(&self, value: &Value) -> VldError {
        crate::primitives::type_error(&self.custom_type_error, "number", value)
    }

    fn coerce_err(&self, value: &Value) -> VldError {
        issue_error(
            IssueCode::InvalidType {
                expected: "number".to_string(),
                received: "string".to_string(),
            },
            self.custom_type_error.as_ref(),
            value,
        )
    }

    pub(super) fn extract_number(&self, value: &Value) -> Result<f64, VldError> {
        match value {
            Value::Number(n) => n.as_f64().ok_or_else(|| self.type_err(value)),
            Value::String(s) if self.coerce => s
                .parse::<f64>()
                .ok()
                .filter(|f| f.is_finite())
                .ok_or_else(|| self.coerce_err(value)),
            Value::Bool(b) if self.coerce => Ok(if *b { 1.0 } else { 0.0 }),
            _ => Err(self.type_err(value)),
        }
    }

    /// A type-range failure (`u8` above 255, `f32` overflow), with the
    /// `with_messages` text for its key.
    pub(super) fn range_error(&self, code: IssueCode, value: &Value) -> VldError {
        let key = match code {
            IssueCode::TooSmall { .. } => "too_small",
            _ => "too_big",
        };
        let msg = self.messages.as_ref().and_then(|f| f(key));
        ValidationIssue::with_override(code, msg.as_ref())
            .with_received(value)
            .into()
    }

    pub(super) fn validate(&self, n: Num, value: &Value) -> Result<(), VldError> {
        let mut errors = VldError::new();
        for check in &self.checks {
            if let Some(code) = check.kind.failure(n) {
                let bulk = || self.messages.as_ref().and_then(|f| f(check.kind.key()));
                let msg = check.msg.clone().or_else(bulk);
                errors
                    .issues
                    .push(ValidationIssue::with_override(code, msg.as_ref()).with_received(value));
            }
        }
        if let Some(options) = &self.one_of
            && !options.iter().any(|o| n.cmp(*o) == Some(Ordering::Equal))
        {
            let code = IssueCode::InvalidEnumValue {
                options: options.iter().map(ToString::to_string).collect(),
            };
            let msg = self.messages.as_ref().and_then(|f| f("invalid_enum_value"));
            errors
                .issues
                .push(ValidationIssue::with_override(code, msg.as_ref()).with_received(value));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

impl Default for ZNumber {
    fn default() -> Self {
        Self::new()
    }
}

impl VldSchema for ZNumber {
    type Output = f64;

    fn parse_value(&self, value: &Value) -> Result<f64, VldError> {
        // A JSON integer is checked exactly (`multiple_of`, bounds beyond 2^53);
        // a float is already exact as `f64` (float `%` and comparisons are exact).
        let n = match value.as_number().map(|x| (x.as_i64(), x.as_u64())) {
            Some((Some(i), _)) => Num::I(i.into()),
            Some((_, Some(u))) => Num::I(u.into()),
            _ => Num::F(self.extract_number(value)?),
        };
        let n = self.clamped(n);
        self.validate(n, value)?;
        Ok(n.as_f64())
    }
}

/// Generate a JSON Schema representation of this number schema.
///
/// The strictest lower/upper bound (from `min`/`gt`/`positive`/
/// `non_negative`/`safe`, …) is emitted as `minimum` or `exclusiveMinimum`
/// (likewise for the maximum). The first `multiple_of` goes into
/// `multipleOf`, further ones into `allOf`.
#[cfg(feature = "openapi")]
impl crate::openapi::JsonSchema for ZNumber {
    fn json_schema(&self) -> serde_json::Value {
        self.schema("number", None)
    }
}

impl ZNumber {
    /// JSON Schema of the checks; `range` is the output type's own
    /// `[min, max]`, intersected with the user bounds.
    #[cfg(feature = "openapi")]
    pub(super) fn schema(&self, ty: &str, range: Option<(Num, Num)>) -> Value {
        let mut schema = serde_json::json!({ "type": ty });
        // Strictest bound: larger lower bound wins, exclusive wins ties.
        let pick = |a: (Num, bool), b: (Num, bool), want: Ordering| match b.0.cmp(a.0) {
            Some(o) if o == want => b,
            Some(Ordering::Equal) if b.1 => b,
            _ => a,
        };
        // With `clamp()` inclusive bounds (and the type range) accept anything.
        let keep = |b: &(Num, bool)| !self.clamp || b.1;
        let range = range.filter(|_| !self.clamp);
        let lower = range
            .map(|(lo, _)| (lo, false))
            .into_iter()
            .chain(self.checks.iter().filter_map(|c| c.kind.lower()))
            .filter(keep)
            .reduce(|a, b| pick(a, b, Ordering::Greater));
        let upper = range
            .map(|(_, hi)| (hi, false))
            .into_iter()
            .chain(self.checks.iter().filter_map(|c| c.kind.upper()))
            .filter(keep)
            .reduce(|a, b| pick(a, b, Ordering::Less));
        if let Some((v, excl)) = lower {
            let key = if excl { "exclusiveMinimum" } else { "minimum" };
            schema[key] = v.json();
        }
        if let Some((v, excl)) = upper {
            let key = if excl { "exclusiveMaximum" } else { "maximum" };
            schema[key] = v.json();
        }
        // `multipleOf` must be > 0: a zero divisor (never matches) is omitted.
        let mut multiples = self.checks.iter().filter_map(|c| match c.kind {
            Kind::MultipleOf(v) if v.as_f64() != 0.0 => Some(v.json()),
            _ => None,
        });
        if let Some(m) = multiples.next() {
            schema["multipleOf"] = m;
        }
        let rest: Vec<Value> = multiples
            .map(|m| serde_json::json!({ "multipleOf": m }))
            .collect();
        if !rest.is_empty() {
            schema["allOf"] = Value::Array(rest);
        }
        if let Some(options) = &self.one_of {
            schema["enum"] = options.iter().map(|o| o.json()).collect();
        }
        schema
    }
}

#[cfg(feature = "openapi")]
impl crate::openapi::CollectNestedSchemas for ZNumber {}