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