Schemas

Booleans, literals and enums

boolean, null, never, any, char, literal, enumeration and enum_of.

Boolean

use vld::prelude::*;

assert!(vld::boolean().parse("true").unwrap());

let flag = vld::boolean().coerce();
assert!(flag.parse(r#""1""#).unwrap());
assert!(!flag.parse(r#""false""#).unwrap());
assert!(flag.parse("2").unwrap()); // numbers: 0 is false, anything else true

coerce() accepts "true" / "1" and "false" / "0", and numbers (0 → false, any other number → true). type_error("...") sets the message for other input.

Null, never, any

ConstructorAcceptsOutput
vld::null()only null()
vld::never()nothing (invalid_type, expected never)std::convert::Infallible
vld::any()every JSON valueserde_json::Value

never() is useful in unions and for fields that must not be sent: vld::never().optional() accepts only a missing or null value.

Char

vld::char() accepts a string of exactly one Unicode scalar value and returns a char.

assert_eq!(vld::char().parse(r#""é""#).unwrap(), 'é');
assert!(vld::char().parse(r#""ab""#).is_err());

Literal

vld::literal(value) matches one exact value. Supported value types: &'static str, String, bool, f32, f64 and every integer type.

assert_eq!(vld::literal("admin").parse(r#""admin""#).unwrap(), "admin");
assert!(vld::literal(42i64).parse("42").is_ok());
assert!(vld::literal(true).parse("false").is_err()); // invalid_literal

The JSON Schema is {"const": value}; expected_value() returns the literal.

String enum

vld::enumeration(&[...]) accepts one of a fixed set of strings and returns the String.

let role = vld::enumeration(&["admin", "user", "moderator"]);
assert!(role.parse(r#""admin""#).is_ok());

let err = role.parse(r#""root""#).unwrap_err();
assert_eq!(err.issues[0].code.key(), "invalid_enum_value");

Use ZEnum::from_strings(vec![...]) when the options are built at runtime.

Mapping strings to Rust enums

vld::enum_of maps fixed strings to values of any Clone type, without Deserialize:

#[derive(Debug, Clone, PartialEq)]
enum Level { Low, High }

let level = vld::enum_of(&[("low", Level::Low), ("high", Level::High)]);
assert_eq!(level.parse(r#""high""#).unwrap(), Level::High);
assert!(level.parse(r#""mid""#).is_err());

For enums that already implement serde::Deserialize, use vld::from_serde().