Skip to main content

jsonschema_value/
lib.rs

1//! JSON value representations and semantics shared by the validator and its bindings.
2
3pub mod cmp;
4#[cfg(feature = "conformance")]
5pub mod conformance;
6pub mod numeric;
7// The bound checks take a `serde_json::Number`, which only that feature makes a `JsonNumber`.
8#[cfg(feature = "serde_json")]
9pub mod numeric_check;
10pub mod types;
11pub mod unique;
12
13#[cfg(feature = "magnus")]
14mod magnus;
15#[cfg(feature = "pyo3")]
16mod pyo3;
17#[cfg(feature = "serde_json")]
18mod serde_json;
19mod serde_number;
20
21#[cfg(feature = "magnus")]
22pub use magnus::{
23    child as magnus_child, invalidate_members_cache as magnus_invalidate_members_cache,
24    is_object as magnus_is_object, probe_root as magnus_probe_root,
25    take_pending_error as magnus_take_pending_error, Magnus, PendingError,
26    PendingErrorScope as MagnusPendingErrorScope, RbNode,
27};
28#[cfg(feature = "pyo3")]
29pub use pyo3::{probe_root, take_pending_error, PendingErrorScope, Pyo3};
30#[cfg(feature = "serde_json")]
31pub use serde_json::SerdeJson;
32
33use std::{borrow::Cow, fmt, sync::OnceLock};
34
35use ::serde_json::Value;
36
37use crate::types::JsonType;
38
39/// The instance a validation error reports, built once and cached.
40pub enum LazyInstance<'a> {
41    Ready(Cow<'a, Value>),
42    /// Built on first read. A `fn` pointer rather than a boxed closure: dropck cannot see through
43    /// a `dyn` bounded by `'a` and would demand borrows outlive the error's drop, not just its use.
44    Deferred {
45        bytes: &'a [u8],
46        tag: u32,
47        // Elided, so `for<'r> fn(&'r [u8], u32)`: a lifetime in argument position is contravariant
48        // and would fight `bytes`' covariance, making the enum invariant in `'a`.
49        make: fn(&[u8], u32) -> Value,
50        // `'static`, not `'a`: `OnceLock` is invariant in its parameter, which would otherwise
51        // infect every lifetime this type appears under, `ValidationError<'a>` included.
52        cell: OnceLock<Cow<'static, Value>>,
53    },
54}
55
56impl<'a> LazyInstance<'a> {
57    /// The instance, building and caching it on the first call.
58    pub fn get(&self) -> &Cow<'a, Value> {
59        match self {
60            LazyInstance::Ready(value) => value,
61            LazyInstance::Deferred {
62                bytes,
63                tag,
64                make,
65                cell,
66            } => cell.get_or_init(|| Cow::Owned(make(bytes, *tag))),
67        }
68    }
69
70    /// Consumes `self`, returning the instance without cloning an already-built one.
71    #[must_use]
72    pub fn into_cow(self) -> Cow<'a, Value> {
73        match self {
74            LazyInstance::Ready(value) => value,
75            LazyInstance::Deferred {
76                bytes,
77                tag,
78                make,
79                cell,
80            } => cell
81                .into_inner()
82                .unwrap_or_else(|| Cow::Owned(make(bytes, tag))),
83        }
84    }
85}
86
87impl fmt::Debug for LazyInstance<'_> {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        fmt::Debug::fmt(self.get(), f)
90    }
91}
92
93/// One JSON representation.
94pub trait Json: Sized + Send + Sync + 'static {
95    type Node<'a>: Node<'a, Self>;
96
97    /// Property name prepared once at compile time, for repeated object lookups.
98    type PreparedKey: Send + Sync;
99
100    /// Object keys a members pass may visit per [`Object::get`] it replaces, before the pass
101    /// costs more than the lookups. Zero keeps every representation whose lookup is a hash
102    /// probe on lookups.
103    const KEYS_PER_LOOKUP: usize = 0;
104
105    /// Scratch storage for [`Json::with_string_node`], reusable across calls.
106    type StringBuffer: Default;
107
108    fn prepare_key(key: &str) -> Self::PreparedKey;
109
110    /// Call `f` with a node holding `string`, backed by `buffer`.
111    ///
112    /// `propertyNames` validates each property name through this, so names run through the
113    /// same subschema machinery as any other node of the representation.
114    ///
115    /// Representations whose nodes point into an encoded document have two options: a plain
116    /// string variant on the node type, or encoding a single-string document into `buffer`.
117    fn with_string_node<T>(
118        buffer: &mut Self::StringBuffer,
119        string: &str,
120        f: impl FnOnce(Self::Node<'_>) -> T,
121    ) -> T;
122}
123
124/// What tells one node from another within a validation call.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126pub struct NodeIdentity {
127    address: usize,
128    tag: u32,
129}
130
131impl NodeIdentity {
132    /// For representations where a live node's address is its own.
133    #[must_use]
134    pub fn new(address: usize) -> Self {
135        Self { address, tag: 0 }
136    }
137
138    /// For representations where nodes share an address, such as an arena addressed by index.
139    #[must_use]
140    pub fn tagged(address: usize, tag: u32) -> Self {
141        Self { address, tag }
142    }
143}
144
145/// A JSON number, readable without constructing a [`::serde_json::Number`].
146pub trait JsonNumber {
147    fn as_u64(&self) -> Option<u64>;
148    fn as_i64(&self) -> Option<i64>;
149    fn as_f64(&self) -> Option<f64>;
150
151    /// Decimal digits; the only form that holds values outside the primitives.
152    fn as_str(&self) -> Cow<'_, str>;
153
154    /// For cold paths: error construction and annotations.
155    fn to_number(&self) -> Cow<'_, ::serde_json::Number>;
156
157    /// `type: integer` checks call this per number: override it where the default's
158    /// [`JsonNumber::to_number`] round-trip is not free (e.g. decimal representations).
159    fn is_integer(&self) -> bool {
160        crate::types::number_is_integer(&self.to_number())
161    }
162
163    /// Whether the number is *written* as an integer, with neither a fraction nor an exponent
164    /// part. Draft 4 decides `type: integer` this way, so `1.0` and `1e2` are not integers there.
165    ///
166    /// The default reads the literal from [`JsonNumber::as_str`]. A representation holding native
167    /// numbers has none, and must override this to answer from its own types.
168    fn is_written_as_integer(&self) -> bool {
169        self.as_u64().is_some()
170            || self.as_i64().is_some()
171            || !self.as_str().contains(['.', 'e', 'E'])
172    }
173}
174
175/// One JSON value; `Clone` must be cheap.
176pub trait Node<'a, F: Json>: Clone {
177    type Object: Object<'a, F, Node = Self>;
178    type Array: Array<'a, F, Node = Self>;
179    type Number: JsonNumber;
180
181    fn as_object(&self) -> Option<Self::Object>;
182    fn as_array(&self) -> Option<Self::Array>;
183    fn as_string(&self) -> Option<Cow<'a, str>>;
184
185    fn as_number(&self) -> Option<Self::Number>;
186    fn as_boolean(&self) -> Option<bool>;
187    fn is_null(&self) -> bool;
188
189    /// Must agree with `as_number().is_some()`; override where `as_number` has to construct.
190    fn is_number(&self) -> bool {
191        self.as_number().is_some()
192    }
193
194    fn is_string(&self) -> bool {
195        self.json_type() == JsonType::String
196    }
197
198    /// Numbers always report [`JsonType::Number`]; integer-ness is a numeric property, not a type.
199    fn json_type(&self) -> JsonType;
200
201    /// Length in Unicode code points.
202    fn string_length(&self) -> Option<u64> {
203        self.as_string().map(|string| string.chars().count() as u64)
204    }
205
206    /// Equality against a `const`/`enum` value; numbers compare mathematically.
207    fn equals_value(&self, expected: &Value) -> bool {
208        crate::cmp::equal(&self.to_value(), expected)
209    }
210
211    /// For cold paths only: error construction, annotations, the `equals_value` and
212    /// `is_unique` defaults (`const`/`enum`/`uniqueItems`), and serde-only custom keywords.
213    fn to_value(&self) -> Cow<'a, Value>;
214
215    /// The instance a validation error reports. Defaults to eager [`Node::to_value`]; override only
216    /// where the node is `Send + Sync` without a VM lock — `Magnus` would compile but be unsound.
217    fn lazy_value(&self) -> LazyInstance<'a> {
218        LazyInstance::Ready(self.to_value())
219    }
220
221    /// Identity for `$ref` cycle detection and `is_valid` memoization.
222    ///
223    /// Nodes alive at once must never share one, and two handles on a node must report the same
224    /// one, or a collision reports a cycle that is not there. A container's must never pass to a
225    /// later node: [`Node::container_identity`] keys a cache outliving it. `None` opts out,
226    /// leaving recursion bounded only by the stack.
227    fn identity(&self) -> Option<NodeIdentity>;
228
229    fn container_identity(&self) -> Option<NodeIdentity> {
230        if matches!(self.json_type(), JsonType::Object | JsonType::Array) {
231            self.identity()
232        } else {
233            None
234        }
235    }
236}
237
238pub trait Object<'a, F: Json> {
239    type Node: Node<'a, F>;
240    type MemberName: AsRef<str> + Into<Cow<'a, str>>;
241    type MembersIter: Iterator<Item = (Self::MemberName, Self::Node)>;
242
243    fn len(&self) -> usize;
244    fn is_empty(&self) -> bool {
245        self.len() == 0
246    }
247    fn get(&self, key: &F::PreparedKey) -> Option<Self::Node>;
248    fn members(&self) -> Self::MembersIter;
249}
250
251// `len` bounds validation; no caller probes emptiness.
252#[allow(clippy::len_without_is_empty)]
253pub trait Array<'a, F: Json> {
254    type Node: Node<'a, F>;
255    type ElementsIter: Iterator<Item = Self::Node>;
256
257    fn len(&self) -> usize;
258    fn elements(&self) -> Self::ElementsIter;
259
260    /// `uniqueItems`: every element distinct under JSON equality.
261    fn is_unique(&self) -> bool {
262        let values: Vec<Cow<'a, Value>> =
263            self.elements().map(|element| element.to_value()).collect();
264        crate::unique::is_unique(&values)
265    }
266}