Debian Codegraph @

src/ext/numeric.rs

raw symbols SCIP
1 #![allow(
2 clippy::cast_possible_truncation,
3 clippy::cast_possible_wrap,
4 clippy::cast_sign_loss,
5 clippy::cast_precision_loss,
6 clippy::float_cmp
7 )]
8
9 use fraction::{BigFraction, One, Zero};
10 use serde_json::Number;
11
12 macro_rules! define_num_cmp {
13 ($($trait_fn:ident => $fn_name:ident, $op:tt, $infinity_positive:literal),* $(,)?) => {
14 $(
15 pub(crate) fn $fn_name<T>(value: &Number, limit: T) -> bool
16 where
17 T: Copy + num_traits::ToPrimitive,
18 u64: num_cmp::NumCmp<T>,
19 i64: num_cmp::NumCmp<T>,
20 f64: num_cmp::NumCmp<T>,
21 {
22 if let Some(v) = value.as_u64() {
23 num_cmp::NumCmp::$trait_fn(v, limit)
24 } else if let Some(v) = value.as_i64() {
25 num_cmp::NumCmp::$trait_fn(v, limit)
26 } else if let Some(v) = value.as_f64() {
27 num_cmp::NumCmp::$trait_fn(v, limit)
28 } else {
29 #[cfg(feature = "arbitrary-precision")]
30 {
31 if let Some(big_value) = bignum::try_parse_bigfraction(value) {
32 if let Some(limit_f64) = num_traits::ToPrimitive::to_f64(&limit) {
33 let limit_frac = BigFraction::from(limit_f64);
34 return big_value $op limit_frac;
35 }
36 }
37 // Treat unparsable numbers as infinity based on sign
38 let is_negative = value.as_str().starts_with('-');
39 if $infinity_positive {
40 !is_negative
41 } else {
42 is_negative
43 }
44 }
45 #[cfg(not(feature = "arbitrary-precision"))]
46 {
47 unreachable!("Always Some without `arbitrary-precision`")
48 }
49 }
50 }
51 )*
52 };
53 }
54
55 define_num_cmp!(
56 num_ge => ge, >=, true, // +infinity passes >=, >
57 num_le => le, <=, false, // -infinity passes <=, <
58 num_gt => gt, >, true,
59 num_lt => lt, <, false,
60 );
61
62 pub(crate) fn is_multiple_of_float(value: &Number, multiple: f64) -> bool {
63 if let Some(value_f64) = value.as_f64() {
64 // Zero is a multiple of any non-zero number
65 // This check must come first to avoid division-related edge cases
66 if value_f64.is_zero() {
67 return true;
68 }
69 if value_f64 < multiple {
70 return false;
71 }
72 // From the JSON Schema spec
73 //
74 // > A numeric instance is valid only if division by this keyword's value results in an integer.
75 //
76 // For fractions, integers have denominator equal to one.
77 //
78 // Ref: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.1
79 (BigFraction::from(value_f64) / BigFraction::from(multiple))
80 .denom()
81 .is_none_or(One::is_one)
82 } else {
83 // This branch is only possible for large floats in scientific notation, we don't really
84 // support it
85 false
86 }
87 }
88
89 pub(crate) fn is_multiple_of_integer(value: &Number, multiple: f64) -> bool {
90 if let Some(value_f64) = value.as_f64() {
91 // As the divisor has its fractional part as zero, then any value with a non-zero
92 // fractional part can't be a multiple of this divisor, therefore it is short-circuited
93 value_f64.fract() == 0. && (value_f64 % multiple) == 0.
94 } else {
95 // Number doesn't fit in f64 - must be huge with arbitrary_precision
96 #[cfg(feature = "arbitrary-precision")]
97 {
98 // Try parsing as BigInt first for large integers
99 if let Some(big_value) = bignum::try_parse_bigint(value) {
100 use num_bigint::BigInt;
101 // Convert the multiple to BigInt.
102 // Note: For large divisors beyond i64/u64 range, the schema compilation
103 // should have created a MultipleOfBigIntValidator instead, which stores
104 // the divisor as BigInt directly. This path handles the case where the
105 // instance is huge but the divisor fits in f64.
106 // Since we know multiple is an integer (checked before calling this function),
107 // we can safely convert via i64 for divisors in the i64 range.
108 // For divisors beyond i64 but representable in f64, precision may be lost,
109 // but that's inherent to f64 representation.
110 let multiple_int = BigInt::from(multiple as i64);
111 return bignum::is_multiple_of_bigint(&big_value, &multiple_int);
112 }
113 // Not an integer - can't be a multiple of an integer divisor
114 false
115 }
116 #[cfg(not(feature = "arbitrary-precision"))]
117 {
118 unreachable!("Always Some without `arbitrary-precision`")
119 }
120 }
121 }
122
123 #[cfg(feature = "arbitrary-precision")]
124 pub(crate) mod bignum {
125 use fraction::BigFraction;
126 use num_bigint::BigInt;
127 use num_traits::{ToPrimitive, Zero};
128 use serde_json::Number;
129 use std::str::FromStr;
130
131 /// Guardrail for how many decimal shifts we are willing to perform when normalizing
132 /// a JSON number written in scientific notation.
133 ///
134 /// Schema authors (and instances) are untrusted input: a literal like `"1e1000000000"`
135 /// would otherwise force us to append billions of zeros just to materialize the number,
136 /// opening the door to denial-of-service attacks. Limiting the exponent adjustment to
137 /// one million digits keeps conversions deterministic while still covering realistic
138 /// use-cases (`10^1_000_000` is already astronomically large for JSON Schema).
139 const MAX_EXPONENT_ADJUSTMENT: u32 = 1_000_000;
140
141 #[derive(Debug, Clone)]
142 struct DecimalComponents {
143 negative: bool,
144 digits: String,
145 fraction_digits: usize,
146 exponent: i64,
147 }
148
149 impl DecimalComponents {
150 fn parse(num_str: &str) -> Option<Self> {
151 let bytes = num_str.as_bytes();
152 if bytes.is_empty() {
153 return None;
154 }
155
156 let mut idx = 0;
157 let negative = if bytes[idx] == b'-' {
158 idx += 1;
159 true
160 } else {
161 false
162 };
163
164 if idx >= bytes.len() {
165 return None;
166 }
167
168 let mut digits = String::with_capacity(bytes.len());
169 let int_start = idx;
170 while idx < bytes.len() && bytes[idx].is_ascii_digit() {
171 idx += 1;
172 }
173 if int_start == idx {
174 return None;
175 }
176 digits.push_str(&num_str[int_start..idx]);
177
178 let mut fraction_digits = 0usize;
179 if idx < bytes.len() && bytes[idx] == b'.' {
180 idx += 1;
181 let frac_start = idx;
182 while idx < bytes.len() && bytes[idx].is_ascii_digit() {
183 idx += 1;
184 }
185 if frac_start == idx {
186 return None;
187 }
188 digits.push_str(&num_str[frac_start..idx]);
189 fraction_digits = idx - frac_start;
190 }
191
192 let mut exponent: i64 = 0;
193 if idx < bytes.len() && (bytes[idx] == b'e' || bytes[idx] == b'E') {
194 idx += 1;
195 if idx >= bytes.len() {
196 return None;
197 }
198 let mut exp_sign: i64 = 1;
199 if bytes[idx] == b'+' {
200 idx += 1;
201 } else if bytes[idx] == b'-' {
202 exp_sign = -1;
203 idx += 1;
204 }
205 let exp_start = idx;
206 while idx < bytes.len() && bytes[idx].is_ascii_digit() {
207 idx += 1;
208 }
209 if exp_start == idx {
210 return None;
211 }
212 let exp_value = num_str[exp_start..idx].parse::<i64>().ok()?;
213 exponent = exp_value.checked_mul(exp_sign)?;
214 }
215
216 if idx != bytes.len() {
217 return None;
218 }
219
220 Some(Self {
221 negative,
222 digits,
223 fraction_digits,
224 exponent,
225 })
226 }
227
228 #[inline]
229 fn decimal_shift(&self) -> i64 {
230 self.exponent - self.fraction_digits as i64
231 }
232 }
233
234 fn digits_are_zero(s: &str) -> bool {
235 s.bytes().all(|b| b == b'0')
236 }
237
238 fn trailing_zero_count(s: &str) -> usize {
239 s.as_bytes()
240 .iter()
241 .rev()
242 .take_while(|b| **b == b'0')
243 .count()
244 }
245
246 fn append_zeros(target: &mut String, count: usize) -> Option<()> {
247 let new_len = target.len().checked_add(count)?;
248 target.reserve(count);
249 target.extend(std::iter::repeat_n('0', count));
250 debug_assert_eq!(target.len(), new_len);
251 Some(())
252 }
253
254 fn pow10_bigint(exp: usize) -> Option<BigInt> {
255 if exp == 0 {
256 return Some(BigInt::from(1));
257 }
258 let exp_u32 = u32::try_from(exp).ok()?;
259 Some(BigInt::from(10).pow(exp_u32))
260 }
261
262 fn shift_exceeds_limit(shift: i64) -> bool {
263 if shift <= 0 {
264 return false;
265 }
266 shift as u64 > u64::from(MAX_EXPONENT_ADJUSTMENT)
267 }
268
269 fn exponent_reduction_exceeds_limit(exponent: i64) -> bool {
270 if exponent >= 0 {
271 return false;
272 }
273 match exponent.checked_abs() {
274 Some(abs) => abs as u64 > u64::from(MAX_EXPONENT_ADJUSTMENT),
275 None => true,
276 }
277 }
278
279 /// Try to parse a Number as `BigInt` if it's outside i64 range or for compile-time
280 /// schema values that need exact representation
281 pub(crate) fn try_parse_bigint(num: &Number) -> Option<BigInt> {
282 let num_str = num.as_str();
283
284 // Only parse as BigInt if it doesn't fit in i64
285 // We include u64 values beyond i64::MAX because they can't be accurately
286 // represented when cast to i64, which is needed for certain operations
287 if num.as_i64().is_some() {
288 return None;
289 }
290
291 let has_fraction_or_exponent = num_str.bytes().any(|b| b == b'.' || b == b'e' || b == b'E');
292 if !has_fraction_or_exponent {
293 return BigInt::from_str(num_str).ok();
294 }
295
296 let mut components = DecimalComponents::parse(num_str)?;
297 let mut shift = components.decimal_shift();
298
299 if shift < 0 {
300 let needed = (-shift) as usize;
301 if digits_are_zero(&components.digits) {
302 components.digits.clear();
303 components.digits.push('0');
304 shift = 0;
305 } else {
306 if exponent_reduction_exceeds_limit(components.exponent) {
307 return None;
308 }
309 let zeros = trailing_zero_count(&components.digits);
310 if zeros < needed {
311 return None;
312 }
313 let new_len = components.digits.len() - needed;
314 components.digits.truncate(new_len);
315 shift = 0;
316 }
317 }
318
319 if shift > 0 {
320 if shift_exceeds_limit(shift) {
321 return None;
322 }
323 append_zeros(&mut components.digits, shift as usize)?;
324 }
325
326 let digits_trimmed = components.digits.trim_start_matches('0');
327 let digits_ref = if digits_trimmed.is_empty() {
328 "0"
329 } else {
330 digits_trimmed
331 };
332 let mut value = BigInt::from_str(digits_ref).ok()?;
333 if components.negative && !value.is_zero() {
334 value = -value;
335 }
336 Some(value)
337 }
338
339 /// Try to parse a Number as `BigFraction` for arbitrary precision decimal support
340 ///
341 /// Returns Some for numbers requiring exact decimal precision:
342 /// - Decimals with a decimal point (e.g., `0.1`, `123.456`)
343 /// - Scientific notation decimals that can't be represented exactly as f64
344 ///
345 /// Returns None for:
346 /// - Integers that fit in i64 (handled by standard numeric path)
347 /// - Large integers including u64 beyond `i64::MAX` (handled by `try_parse_bigint`)
348 pub(crate) fn try_parse_bigfraction(num: &Number) -> Option<BigFraction> {
349 // Skip integers that fit in i64 - they don't need BigFraction
350 if num.as_i64().is_some() {
351 return None;
352 }
353
354 let num_str = num.as_str();
355
356 // Check for decimal point and exponent in a single pass
357 let mut has_decimal_point = false;
358 let mut has_exponent = false;
359 for b in num_str.bytes() {
360 if b == b'.' {
361 has_decimal_point = true;
362 } else if b == b'e' || b == b'E' {
363 has_exponent = true;
364 break;
365 }
366 }
367
368 if !has_decimal_point && !has_exponent {
369 return None;
370 }
371
372 if !has_exponent {
373 return BigFraction::from_str(num_str).ok();
374 }
375
376 let components = DecimalComponents::parse(num_str)?;
377 let shift = components.decimal_shift();
378
379 // A number with exponent that still resolves to an integer is handled by BigInt.
380 if shift >= 0 {
381 return None;
382 }
383
384 if exponent_reduction_exceeds_limit(components.exponent) {
385 return None;
386 }
387
388 let denom_power = (-shift) as usize;
389 let denominator = pow10_bigint(denom_power)?;
390 let mut numerator = BigInt::from_str(&components.digits).ok()?;
391 if components.negative && !numerator.is_zero() {
392 numerator = -numerator;
393 }
394 Some(BigFraction::from(numerator) / BigFraction::from(denominator))
395 }
396
397 macro_rules! define_bigint_cmp {
398 ($($fn_name:ident, $prim_type:ty, $to_prim:ident, $op:tt, $overflow_sign:expr);* $(;)?) => {
399 $(
400 pub(crate) fn $fn_name(bigint: &BigInt, value: $prim_type) -> bool {
401 if let Some(converted) = bigint.$to_prim() {
402 converted $op value
403 } else {
404 bigint.sign() == $overflow_sign
405 }
406 }
407 )*
408 };
409 }
410
411 define_bigint_cmp!(
412 bigint_ge_u64, u64, to_u64, >=, num_bigint::Sign::Plus;
413 bigint_le_u64, u64, to_u64, <=, num_bigint::Sign::Minus;
414 bigint_gt_u64, u64, to_u64, >, num_bigint::Sign::Plus;
415 bigint_lt_u64, u64, to_u64, <, num_bigint::Sign::Minus;
416 bigint_ge_i64, i64, to_i64, >=, num_bigint::Sign::Plus;
417 bigint_le_i64, i64, to_i64, <=, num_bigint::Sign::Minus;
418 bigint_gt_i64, i64, to_i64, >, num_bigint::Sign::Plus;
419 bigint_lt_i64, i64, to_i64, <, num_bigint::Sign::Minus;
420 bigint_ge_f64, f64, to_f64, >=, num_bigint::Sign::Plus;
421 bigint_le_f64, f64, to_f64, <=, num_bigint::Sign::Minus;
422 bigint_gt_f64, f64, to_f64, >, num_bigint::Sign::Plus;
423 bigint_lt_f64, f64, to_f64, <, num_bigint::Sign::Minus;
424 );
425
426 // Generate reverse comparison functions (primitive op BigType -> BigType op primitive)
427 macro_rules! define_reverse_cmp {
428 ($($rev_ge:ident, $rev_le:ident, $rev_gt:ident, $rev_lt:ident, $prim_type:ty, $big_type:ty, $fwd_ge:ident, $fwd_le:ident, $fwd_gt:ident, $fwd_lt:ident);* $(;)?) => {
429 $(
430 pub(crate) fn $rev_ge(value: $prim_type, big: &$big_type) -> bool {
431 $fwd_le(big, value)
432 }
433
434 pub(crate) fn $rev_le(value: $prim_type, big: &$big_type) -> bool {
435 $fwd_ge(big, value)
436 }
437
438 pub(crate) fn $rev_gt(value: $prim_type, big: &$big_type) -> bool {
439 $fwd_lt(big, value)
440 }
441
442 pub(crate) fn $rev_lt(value: $prim_type, big: &$big_type) -> bool {
443 $fwd_gt(big, value)
444 }
445 )*
446 };
447 }
448
449 define_reverse_cmp!(
450 u64_ge_bigint, u64_le_bigint, u64_gt_bigint, u64_lt_bigint, u64, BigInt, bigint_ge_u64, bigint_le_u64, bigint_gt_u64, bigint_lt_u64;
451 i64_ge_bigint, i64_le_bigint, i64_gt_bigint, i64_lt_bigint, i64, BigInt, bigint_ge_i64, bigint_le_i64, bigint_gt_i64, bigint_lt_i64;
452 f64_ge_bigint, f64_le_bigint, f64_gt_bigint, f64_lt_bigint, f64, BigInt, bigint_ge_f64, bigint_le_f64, bigint_gt_f64, bigint_lt_f64;
453 );
454
455 /// Check if a Number (as `BigInt`) is a multiple of another `BigInt`
456 pub(crate) fn is_multiple_of_bigint(value: &BigInt, multiple: &BigInt) -> bool {
457 // Zero is a multiple of any non-zero number
458 // Mathematically: 0 = k * multiple for k = 0
459 if value.is_zero() {
460 return true;
461 }
462
463 // Note: multiple.is_zero() case is not handled here because JSON Schema
464 // validation rejects schemas with "multipleOf: 0" during compilation
465 // (exclusiveMinimum constraint requires multipleOf > 0).
466 // The modulo operation below would panic if multiple is zero, but this
467 // is prevented by schema validation.
468
469 (value % multiple).is_zero()
470 }
471
472 // BigFraction comparison functions
473 macro_rules! define_bigfraction_cmp {
474 ($($fn_name:ident, $prim_type:ty, $op:tt);* $(;)?) => {
475 $(
476 pub(crate) fn $fn_name(bigfrac: &BigFraction, value: $prim_type) -> bool {
477 let value_frac = BigFraction::from(value);
478 *bigfrac $op value_frac
479 }
480 )*
481 };
482 }
483
484 define_bigfraction_cmp!(
485 bigfrac_ge_u64, u64, >=;
486 bigfrac_le_u64, u64, <=;
487 bigfrac_gt_u64, u64, >;
488 bigfrac_lt_u64, u64, <;
489 bigfrac_ge_i64, i64, >=;
490 bigfrac_le_i64, i64, <=;
491 bigfrac_gt_i64, i64, >;
492 bigfrac_lt_i64, i64, <;
493 bigfrac_ge_f64, f64, >=;
494 bigfrac_le_f64, f64, <=;
495 bigfrac_gt_f64, f64, >;
496 bigfrac_lt_f64, f64, <;
497 );
498
499 define_reverse_cmp!(
500 u64_ge_bigfrac, u64_le_bigfrac, u64_gt_bigfrac, u64_lt_bigfrac, u64, BigFraction, bigfrac_ge_u64, bigfrac_le_u64, bigfrac_gt_u64, bigfrac_lt_u64;
501 i64_ge_bigfrac, i64_le_bigfrac, i64_gt_bigfrac, i64_lt_bigfrac, i64, BigFraction, bigfrac_ge_i64, bigfrac_le_i64, bigfrac_gt_i64, bigfrac_lt_i64;
502 f64_ge_bigfrac, f64_le_bigfrac, f64_gt_bigfrac, f64_lt_bigfrac, f64, BigFraction, bigfrac_ge_f64, bigfrac_le_f64, bigfrac_gt_f64, bigfrac_lt_f64;
503 );
504
505 /// Check if a `BigFraction` is a multiple of another value
506 pub(crate) fn is_multiple_of_bigfrac(value: &BigFraction, multiple: &BigFraction) -> bool {
507 // Zero is a multiple of any non-zero number
508 if value.is_zero() {
509 return true;
510 }
511 // Division by zero is undefined, so return false
512 if multiple.is_zero() {
513 return false;
514 }
515 // A number is a multiple of another if division results in an integer
516 // (denominator of the result is 1)
517 (value / multiple).denom().is_none_or(fraction::One::is_one)
518 }
519 }
520
521 #[cfg(all(test, feature = "arbitrary-precision"))]
522 mod tests {
523 use super::bignum;
524 use fraction::BigFraction;
525 use num_bigint::BigInt;
526 use serde_json::{Number, Value};
527 use test_case::test_case;
528
529 fn number_from_str(raw: &str) -> Number {
530 match serde_json::from_str::<Value>(raw).expect("valid JSON number") {
531 Value::Number(num) => num,
532 _ => unreachable!(),
533 }
534 }
535
536 #[test]
537 fn bigint_parses_scientific_integer() {
538 let num = number_from_str("1e19");
539 let parsed = bignum::try_parse_bigint(&num).expect("parsed bigint");
540 assert_eq!(
541 parsed,
542 BigInt::parse_bytes(b"10000000000000000000", 10).unwrap()
543 );
544 }
545
546 #[test]
547 fn bigint_rejects_non_integer_scientific() {
548 let num = number_from_str("1.25e1");
549 assert!(bignum::try_parse_bigint(&num).is_none());
550 }
551
552 #[test]
553 fn bigfraction_parses_scientific_decimal() {
554 let num = number_from_str("1.5e-5");
555 let parsed = bignum::try_parse_bigfraction(&num).expect("parsed bigfraction");
556 let expected =
557 BigFraction::from(BigInt::from(3)) / BigFraction::from(BigInt::from(200_000));
558 assert_eq!(parsed, expected);
559 }
560
561 #[test]
562 fn bigfraction_skips_scientific_integer() {
563 let num = number_from_str("3e4");
564 assert!(bignum::try_parse_bigfraction(&num).is_none());
565 }
566
567 // Huge decimal beyond f64 range
568 const HUGE_POSITIVE: &str = "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5";
569 const HUGE_NEGATIVE: &str = "-99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5";
570
571 #[test_case(r#"{"minimum": 0}"#, HUGE_POSITIVE, true ; "huge_positive_vs_minimum_0")]
572 #[test_case(r#"{"minimum": 0}"#, HUGE_NEGATIVE, false ; "huge_negative_vs_minimum_0")]
573 #[test_case(r#"{"maximum": 1000}"#, HUGE_POSITIVE, false ; "huge_positive_vs_maximum_1000")]
574 #[test_case(r#"{"maximum": 0}"#, HUGE_NEGATIVE, true ; "huge_negative_vs_maximum_0")]
575 #[test_case(r#"{"exclusiveMinimum": 0}"#, HUGE_POSITIVE, true ; "huge_positive_vs_exclusive_minimum_0")]
576 #[test_case(r#"{"exclusiveMinimum": 0}"#, HUGE_NEGATIVE, false ; "huge_negative_vs_exclusive_minimum_0")]
577 #[test_case(r#"{"exclusiveMaximum": 1000}"#, HUGE_POSITIVE, false ; "huge_positive_vs_exclusive_maximum_1000")]
578 #[test_case(r#"{"exclusiveMaximum": 0}"#, HUGE_NEGATIVE, true ; "huge_negative_vs_exclusive_maximum_0")]
579 #[test_case(r#"{"minimum": -1000, "maximum": 1000}"#, HUGE_POSITIVE, false ; "huge_positive_outside_range")]
580 #[test_case(r#"{"minimum": -1000, "maximum": 1000}"#, HUGE_NEGATIVE, false ; "huge_negative_outside_range")]
581 #[test_case(r#"{"multipleOf": 0.5}"#, HUGE_POSITIVE, true ; "huge_positive_multiple_of_0_5")]
582 #[test_case(r#"{"multipleOf": 0.5}"#, HUGE_NEGATIVE, true ; "huge_negative_multiple_of_0_5")]
583 #[test_case(r#"{"multipleOf": 2}"#, HUGE_POSITIVE, false ; "huge_positive_not_multiple_of_2")]
584 fn test_huge_decimal_validation(schema_json: &str, instance_value: &str, expected_valid: bool) {
585 let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
586 let validator = crate::validator_for(&schema).unwrap();
587 let instance = serde_json::from_str(instance_value).unwrap();
588
589 assert_eq!(validator.is_valid(&instance), expected_valid);
590 }
591 }