Skip to main content

jsonschema_value/
numeric_check.rs

1#![allow(clippy::must_use_candidate)]
2
3use serde_json::Number;
4
5use super::numeric;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub enum BoundOp {
9    Lt,
10    Lte,
11    Gt,
12    Gte,
13}
14
15impl BoundOp {
16    pub fn from_u8(value: u8) -> Option<Self> {
17        match value {
18            0 => Some(Self::Lt),
19            1 => Some(Self::Lte),
20            2 => Some(Self::Gt),
21            3 => Some(Self::Gte),
22            _ => None,
23        }
24    }
25}
26
27// Codegen inlines every u64/i64-representable bound and only routes limits with no `as_u64`/`as_i64`
28// representation through `compile_bound`, so no integer variant is ever constructed.
29#[derive(Clone, Debug, PartialEq)]
30pub enum CompiledBound {
31    F64 {
32        op: BoundOp,
33        limit: f64,
34    },
35    #[cfg(feature = "arbitrary-precision")]
36    BigInt {
37        op: BoundOp,
38        limit: num_bigint::BigInt,
39    },
40    #[cfg(feature = "arbitrary-precision")]
41    BigFrac {
42        op: BoundOp,
43        limit: fraction::BigFraction,
44    },
45}
46
47// Codegen inlines every multipleOf that fits f64 and only routes arbitrary-precision
48// divisors through `compile_multiple_of`, so only the big variants are ever constructed.
49#[derive(Clone, Debug, PartialEq)]
50pub enum CompiledMultipleOf {
51    #[cfg(feature = "arbitrary-precision")]
52    BigInt(num_bigint::BigInt),
53    #[cfg(feature = "arbitrary-precision")]
54    BigFrac(fraction::BigFraction),
55    Unsupported,
56}
57
58#[inline]
59fn check_primitive_bound<T>(op: BoundOp, value: &Number, limit: T) -> bool
60where
61    T: Copy + num_traits::ToPrimitive,
62    u64: num_cmp::NumCmp<T>,
63    i64: num_cmp::NumCmp<T>,
64    f64: num_cmp::NumCmp<T>,
65{
66    match op {
67        BoundOp::Lt => numeric::lt(value, limit),
68        BoundOp::Lte => numeric::le(value, limit),
69        BoundOp::Gt => numeric::gt(value, limit),
70        BoundOp::Gte => numeric::ge(value, limit),
71    }
72}
73
74#[cfg(feature = "arbitrary-precision")]
75#[inline]
76fn infinity_cmp(op: BoundOp, is_negative: bool) -> bool {
77    match op {
78        BoundOp::Gte | BoundOp::Gt => !is_negative,
79        BoundOp::Lte | BoundOp::Lt => is_negative,
80    }
81}
82
83#[cfg(feature = "arbitrary-precision")]
84#[inline]
85fn check_bigint_bound(op: BoundOp, limit: &num_bigint::BigInt, value: &Number) -> bool {
86    use fraction::BigFraction;
87
88    if let Some(instance_bigint) = numeric::bignum::try_parse_bigint(value) {
89        return match op {
90            BoundOp::Lt => instance_bigint < *limit,
91            BoundOp::Lte => instance_bigint <= *limit,
92            BoundOp::Gt => instance_bigint > *limit,
93            BoundOp::Gte => instance_bigint >= *limit,
94        };
95    }
96
97    if let Some(v) = value.as_u64() {
98        return match op {
99            BoundOp::Lt => numeric::bignum::u64_lt_bigint(v, limit),
100            BoundOp::Lte => numeric::bignum::u64_le_bigint(v, limit),
101            BoundOp::Gt => numeric::bignum::u64_gt_bigint(v, limit),
102            BoundOp::Gte => numeric::bignum::u64_ge_bigint(v, limit),
103        };
104    }
105
106    if let Some(v) = value.as_i64() {
107        return match op {
108            BoundOp::Lt => numeric::bignum::i64_lt_bigint(v, limit),
109            BoundOp::Lte => numeric::bignum::i64_le_bigint(v, limit),
110            BoundOp::Gt => numeric::bignum::i64_gt_bigint(v, limit),
111            BoundOp::Gte => numeric::bignum::i64_ge_bigint(v, limit),
112        };
113    }
114
115    if let Some(v) = value.as_f64() {
116        return match op {
117            BoundOp::Lt => numeric::bignum::f64_lt_bigint(v, limit),
118            BoundOp::Lte => numeric::bignum::f64_le_bigint(v, limit),
119            BoundOp::Gt => numeric::bignum::f64_gt_bigint(v, limit),
120            BoundOp::Gte => numeric::bignum::f64_ge_bigint(v, limit),
121        };
122    }
123
124    if let Some(instance_bigfrac) = numeric::bignum::try_parse_bigfraction(value) {
125        let limit_frac = BigFraction::from(limit.clone());
126        return match op {
127            BoundOp::Lt => instance_bigfrac < limit_frac,
128            BoundOp::Lte => instance_bigfrac <= limit_frac,
129            BoundOp::Gt => instance_bigfrac > limit_frac,
130            BoundOp::Gte => instance_bigfrac >= limit_frac,
131        };
132    }
133
134    infinity_cmp(op, value.as_str().starts_with('-'))
135}
136
137#[cfg(feature = "arbitrary-precision")]
138#[inline]
139fn check_bigfrac_bound(op: BoundOp, limit: &fraction::BigFraction, value: &Number) -> bool {
140    if let Some(instance_bigfrac) = numeric::bignum::try_parse_bigfraction(value) {
141        return match op {
142            BoundOp::Lt => instance_bigfrac < *limit,
143            BoundOp::Lte => instance_bigfrac <= *limit,
144            BoundOp::Gt => instance_bigfrac > *limit,
145            BoundOp::Gte => instance_bigfrac >= *limit,
146        };
147    }
148
149    if let Some(v) = value.as_u64() {
150        return match op {
151            BoundOp::Lt => numeric::bignum::u64_lt_bigfrac(v, limit),
152            BoundOp::Lte => numeric::bignum::u64_le_bigfrac(v, limit),
153            BoundOp::Gt => numeric::bignum::u64_gt_bigfrac(v, limit),
154            BoundOp::Gte => numeric::bignum::u64_ge_bigfrac(v, limit),
155        };
156    }
157
158    if let Some(v) = value.as_i64() {
159        return match op {
160            BoundOp::Lt => numeric::bignum::i64_lt_bigfrac(v, limit),
161            BoundOp::Lte => numeric::bignum::i64_le_bigfrac(v, limit),
162            BoundOp::Gt => numeric::bignum::i64_gt_bigfrac(v, limit),
163            BoundOp::Gte => numeric::bignum::i64_ge_bigfrac(v, limit),
164        };
165    }
166
167    if let Some(v) = value.as_f64() {
168        return match op {
169            BoundOp::Lt => numeric::bignum::f64_lt_bigfrac(v, limit),
170            BoundOp::Lte => numeric::bignum::f64_le_bigfrac(v, limit),
171            BoundOp::Gt => numeric::bignum::f64_gt_bigfrac(v, limit),
172            BoundOp::Gte => numeric::bignum::f64_ge_bigfrac(v, limit),
173        };
174    }
175
176    // Dynamic BigFraction validators treat this branch as valid because
177    // extremely large scientific notation cannot be compared reliably.
178    true
179}
180
181pub fn compile_bound(op: BoundOp, limit: &Number) -> CompiledBound {
182    #[cfg(feature = "arbitrary-precision")]
183    {
184        if let Some(value) = numeric::bignum::try_parse_bigint(limit) {
185            return CompiledBound::BigInt { op, limit: value };
186        }
187        if let Some(value) = numeric::bignum::try_parse_bigfraction(limit) {
188            return CompiledBound::BigFrac { op, limit: value };
189        }
190    }
191
192    if let Some(value) = limit.as_f64() {
193        return CompiledBound::F64 { op, limit: value };
194    }
195
196    #[cfg(feature = "arbitrary-precision")]
197    {
198        let limit = if limit.as_str().starts_with('-') {
199            f64::NEG_INFINITY
200        } else {
201            f64::INFINITY
202        };
203        CompiledBound::F64 { op, limit }
204    }
205
206    #[cfg(not(feature = "arbitrary-precision"))]
207    {
208        unreachable!("non-arbitrary-precision serde_json::Number always has an f64 representation");
209    }
210}
211
212pub fn check_bound(compiled: &CompiledBound, value: &Number) -> bool {
213    match compiled {
214        CompiledBound::F64 { op, limit } => check_primitive_bound(*op, value, *limit),
215        #[cfg(feature = "arbitrary-precision")]
216        CompiledBound::BigInt { op, limit } => check_bigint_bound(*op, limit, value),
217        #[cfg(feature = "arbitrary-precision")]
218        CompiledBound::BigFrac { op, limit } => check_bigfrac_bound(*op, limit, value),
219    }
220}
221
222#[cfg(feature = "arbitrary-precision")]
223pub fn compile_multiple_of(multiple_of: &Number) -> CompiledMultipleOf {
224    #[cfg(feature = "arbitrary-precision")]
225    {
226        if let Some(value) = numeric::bignum::try_parse_bigint(multiple_of) {
227            return CompiledMultipleOf::BigInt(value);
228        }
229        if let Some(value) = numeric::bignum::try_parse_bigfraction(multiple_of) {
230            return CompiledMultipleOf::BigFrac(value);
231        }
232    }
233
234    CompiledMultipleOf::Unsupported
235}
236
237#[cfg(feature = "arbitrary-precision")]
238pub fn check_multiple_of(compiled: &CompiledMultipleOf, value: &Number) -> bool {
239    match compiled {
240        #[cfg(feature = "arbitrary-precision")]
241        CompiledMultipleOf::BigInt(multiple) => {
242            use num_bigint::BigInt;
243
244            if let Some(instance_bigint) = numeric::bignum::try_parse_bigint(value) {
245                return numeric::bignum::is_multiple_of_bigint(&instance_bigint, multiple);
246            }
247
248            if let Some(v) = value.as_u64() {
249                let v_bigint = BigInt::from(v);
250                return numeric::bignum::is_multiple_of_bigint(&v_bigint, multiple);
251            }
252
253            if let Some(v) = value.as_i64() {
254                let v_bigint = BigInt::from(v);
255                return numeric::bignum::is_multiple_of_bigint(&v_bigint, multiple);
256            }
257
258            false
259        }
260        #[cfg(feature = "arbitrary-precision")]
261        CompiledMultipleOf::BigFrac(multiple) => {
262            use num_traits::ToPrimitive;
263
264            if let Some(instance_bigfrac) = numeric::bignum::try_parse_bigfraction(value) {
265                return numeric::bignum::is_multiple_of_bigfrac(&instance_bigfrac, multiple);
266            }
267
268            if let Some(instance_bigint) = numeric::bignum::try_parse_bigint(value) {
269                let value_frac = fraction::BigFraction::from(instance_bigint);
270                return numeric::bignum::is_multiple_of_bigfrac(&value_frac, multiple);
271            }
272
273            if let Some(v) = value.as_u64() {
274                let value_frac = fraction::BigFraction::from(v);
275                return numeric::bignum::is_multiple_of_bigfrac(&value_frac, multiple);
276            }
277
278            if let Some(v) = value.as_i64() {
279                let value_frac = fraction::BigFraction::from(v);
280                return numeric::bignum::is_multiple_of_bigfrac(&value_frac, multiple);
281            }
282
283            let multiple_f64 = multiple.to_f64().unwrap_or(f64::INFINITY);
284            numeric::is_multiple_of_float(value, multiple_f64)
285        }
286        CompiledMultipleOf::Unsupported => true,
287    }
288}
289
290/// Which arithmetic the validator uses for a `multipleOf` divisor. A rewrite that moves a divisor
291/// between kinds can change verdicts, so only same-kind rewrites preserve membership.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub enum DivisorKind {
294    /// Integer instances take exact integer modulo.
295    Whole,
296    /// A whole divisor past the exact-modulo guard, where instances go through `f64` remainder.
297    WholeLossy,
298    /// Every instance goes through rational division.
299    Fractional,
300}
301
302/// The arithmetic `divisor` selects, mirroring how `multipleOf` compiles.
303pub fn divisor_kind(divisor: &Number) -> DivisorKind {
304    #[cfg(feature = "arbitrary-precision")]
305    {
306        if numeric::bignum::try_parse_bigint(divisor).is_some() {
307            return DivisorKind::Whole;
308        }
309        if numeric::bignum::try_parse_bigfraction(divisor).is_some() {
310            return DivisorKind::Fractional;
311        }
312    }
313    match divisor.as_f64() {
314        Some(value) if value.fract() != 0. => DivisorKind::Fractional,
315        // `is_multiple_of_integer` keeps exact modulo only while the divisor itself is exact.
316        Some(value) if value.abs() <= MAX_SAFE_INTEGER_F64 => DivisorKind::Whole,
317        // A divisor with no `f64` form only arises under arbitrary precision, where the exact
318        // parses above have already classified it.
319        _ => DivisorKind::WholeLossy,
320    }
321}
322
323const MAX_SAFE_INTEGER_F64: f64 = 9_007_199_254_740_992.0;
324
325/// Whether `value` satisfies `multipleOf: divisor`, deciding it the way the validator does.
326pub fn satisfies_multiple_of(divisor: &Number, value: &Number) -> bool {
327    #[cfg(feature = "arbitrary-precision")]
328    {
329        let compiled = compile_multiple_of(divisor);
330        if compiled != CompiledMultipleOf::Unsupported {
331            return check_multiple_of(&compiled, value);
332        }
333    }
334    // A divisor with no `f64` is one the validator skips, so every instance passes there.
335    divisor.as_f64().is_none_or(|limit| {
336        if limit.fract() == 0. {
337            numeric::is_multiple_of_integer(value, limit)
338        } else {
339            numeric::is_multiple_of_float(value, limit)
340        }
341    })
342}