| 1 | use crate::{ |
| 2 | compiler, |
| 3 | error::ValidationError, |
| 4 | ext::cmp, |
| 5 | keywords::CompilationResult, |
| 6 | paths::Location, |
| 7 | validator::{Validate, ValidationContext}, |
| 8 | }; |
| 9 | use ahash::{AHashSet, AHasher}; |
| 10 | use serde_json::{Map, Value}; |
| 11 | |
| 12 | use crate::paths::LazyLocation; |
| 13 | use std::hash::{Hash, Hasher}; |
| 14 | |
| 15 | // Based on implementation proposed by Sven Marnach: |
| 16 | // https://stackoverflow.com/questions/60882381/what-is-the-fastest-correct-way-to-detect-that-there-are-no-duplicates-in-a-json |
| 17 | pub(crate) struct HashedValue<'a>(&'a Value); |
| 18 | |
| 19 | impl PartialEq for HashedValue<'_> { |
| 20 | fn eq(&self, other: &Self) -> bool { |
| 21 | cmp::equal(self.0, other.0) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl Eq for HashedValue<'_> {} |
| 26 | |
| 27 | impl Hash for HashedValue<'_> { |
| 28 | fn hash<H: Hasher>(&self, state: &mut H) { |
| 29 | match self.0 { |
| 30 | Value::Null => state.write_u32(3_221_225_473), // chosen randomly |
| 31 | Value::Bool(ref item) => item.hash(state), |
| 32 | Value::Number(ref item) => { |
| 33 | if let Some(number) = item.as_f64() { |
| 34 | number.to_bits().hash(state); |
| 35 | } else if let Some(number) = item.as_u64() { |
| 36 | number.hash(state); |
| 37 | } else if let Some(number) = item.as_i64() { |
| 38 | number.hash(state); |
| 39 | } |
| 40 | } |
| 41 | Value::String(ref item) => item.hash(state), |
| 42 | Value::Array(ref items) => { |
| 43 | for item in items { |
| 44 | HashedValue(item).hash(state); |
| 45 | } |
| 46 | } |
| 47 | Value::Object(ref items) => { |
| 48 | let mut hash = 0; |
| 49 | for (key, value) in items { |
| 50 | // We have no way of building a new hasher of type `H`, so we |
| 51 | // hardcode using the default hasher of a hash map. |
| 52 | let mut item_hasher = AHasher::default(); |
| 53 | key.hash(&mut item_hasher); |
| 54 | HashedValue(value).hash(&mut item_hasher); |
| 55 | hash ^= item_hasher.finish(); |
| 56 | } |
| 57 | state.write_u64(hash); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // Empirically calculated threshold after which the validator resorts to hashing. |
| 64 | // Calculated for an array of mixed types, large homogeneous arrays of primitive values might be |
| 65 | // processed faster with different thresholds, but this one gives a good baseline for the common |
| 66 | // case. |
| 67 | const ITEMS_SIZE_THRESHOLD: usize = 15; |
| 68 | |
| 69 | #[inline] |
| 70 | pub(crate) fn is_unique(items: &[Value]) -> bool { |
| 71 | let size = items.len(); |
| 72 | if size <= 1 { |
| 73 | // Empty arrays and one-element arrays always contain unique elements |
| 74 | true |
| 75 | } else if let [first, second] = items { |
| 76 | !cmp::equal(first, second) |
| 77 | } else if let [first, second, third] = items { |
| 78 | !cmp::equal(first, second) && !cmp::equal(first, third) && !cmp::equal(second, third) |
| 79 | } else if size <= ITEMS_SIZE_THRESHOLD { |
| 80 | // If the array size is small enough we can compare all elements pairwise, which will |
| 81 | // be faster than calculating hashes for each element, even if the algorithm is O(N^2) |
| 82 | let mut idx = 0_usize; |
| 83 | while idx < items.len() { |
| 84 | let mut inner_idx = idx + 1; |
| 85 | while inner_idx < items.len() { |
| 86 | if cmp::equal(&items[idx], &items[inner_idx]) { |
| 87 | return false; |
| 88 | } |
| 89 | inner_idx += 1; |
| 90 | } |
| 91 | idx += 1; |
| 92 | } |
| 93 | true |
| 94 | } else { |
| 95 | let mut seen = AHashSet::with_capacity(size); |
| 96 | items.iter().map(HashedValue).all(move |x| seen.insert(x)) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | pub(crate) struct UniqueItemsValidator { |
| 101 | location: Location, |
| 102 | } |
| 103 | |
| 104 | impl UniqueItemsValidator { |
| 105 | #[inline] |
| 106 | pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> { |
| 107 | Ok(Box::new(UniqueItemsValidator { location })) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | impl Validate for UniqueItemsValidator { |
| 112 | fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool { |
| 113 | if let Value::Array(items) = instance { |
| 114 | if !is_unique(items) { |
| 115 | return false; |
| 116 | } |
| 117 | } |
| 118 | true |
| 119 | } |
| 120 | |
| 121 | fn validate<'i>( |
| 122 | &self, |
| 123 | instance: &'i Value, |
| 124 | location: &LazyLocation, |
| 125 | ctx: &mut ValidationContext, |
| 126 | ) -> Result<(), ValidationError<'i>> { |
| 127 | if self.is_valid(instance, ctx) { |
| 128 | Ok(()) |
| 129 | } else { |
| 130 | Err(ValidationError::unique_items( |
| 131 | self.location.clone(), |
| 132 | location.into(), |
| 133 | instance, |
| 134 | )) |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | #[inline] |
| 140 | pub(crate) fn compile<'a>( |
| 141 | ctx: &compiler::Context, |
| 142 | _: &'a Map<String, Value>, |
| 143 | schema: &'a Value, |
| 144 | ) -> Option<CompilationResult<'a>> { |
| 145 | if let Value::Bool(value) = schema { |
| 146 | if *value { |
| 147 | let location = ctx.location().join("uniqueItems"); |
| 148 | Some(UniqueItemsValidator::compile(location)) |
| 149 | } else { |
| 150 | None |
| 151 | } |
| 152 | } else { |
| 153 | None |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | #[cfg(test)] |
| 158 | mod tests { |
| 159 | use super::{is_unique, ITEMS_SIZE_THRESHOLD}; |
| 160 | use crate::tests_util; |
| 161 | use serde_json::{json, Value}; |
| 162 | use test_case::test_case; |
| 163 | |
| 164 | #[test] |
| 165 | fn location() { |
| 166 | tests_util::assert_schema_location( |
| 167 | &json!({"uniqueItems": true}), |
| 168 | &json!([1, 1]), |
| 169 | "/uniqueItems", |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | #[test_case(&[] => true; "empty array")] |
| 174 | #[test_case(&[json!(1)] => true; "one element array")] |
| 175 | #[test_case(&[json!(1), json!(2)] => true; "two unique elements")] |
| 176 | #[test_case(&[json!(1), json!(1)] => false; "two non-unique elements")] |
| 177 | #[test_case(&[json!(1), json!(2), json!(3)] => true; "three unique elements")] |
| 178 | #[test_case(&[json!(1), json!(2), json!(1)] => false; "three non-unique elements")] |
| 179 | #[test_case(&[json!(1), json!(2), json!(3), json!(4), json!(5), json!(6), json!(7), json!(8), json!(9), json!(10), json!(11), json!(12), json!(13), json!(14), json!(15), json!(1.0)] => false; "positive numbers with fractions")] |
| 180 | #[test_case(&[json!(-1), json!(-2), json!(-3), json!(-4), json!(-5), json!(-6), json!(-7), json!(-8), json!(-9), json!(-10), json!(-11), json!(-12), json!(-13), json!(-14), json!(-15), json!(-1.0)] => false; "negative numbers with fractions")] |
| 181 | #[test_case(&[json!(1), json!("string"), json!(true), json!(null), json!({"key": "value"}), json!([1, 2, 3])] => true; "mixed types")] |
| 182 | #[test_case(&[json!({"a": 1, "b": 1}), json!({"a": 1, "b": 2}), json!({"a": 1, "b": 3})] => true; "complex objects unique")] |
| 183 | #[test_case(&[json!({"a": 1, "b": 2}), json!({"b": 2, "a": 1}), json!({"a": 1, "b": 2})] => false; "complex objects non-unique")] |
| 184 | fn test_is_unique(items: &[Value]) -> bool { |
| 185 | is_unique(items) |
| 186 | } |
| 187 | |
| 188 | #[test_case(ITEMS_SIZE_THRESHOLD => true; "small array unique")] |
| 189 | #[test_case(ITEMS_SIZE_THRESHOLD + 1 => true; "large array unique")] |
| 190 | fn test_unique_arrays(size: usize) -> bool { |
| 191 | let arr = (1..=size).map(|i| json!(i)).collect::<Vec<_>>(); |
| 192 | is_unique(&arr) |
| 193 | } |
| 194 | |
| 195 | #[test_case(ITEMS_SIZE_THRESHOLD => false; "small array non-unique")] |
| 196 | #[test_case(ITEMS_SIZE_THRESHOLD + 1 => false; "large array non-unique")] |
| 197 | fn test_non_unique_arrays(size: usize) -> bool { |
| 198 | let mut arr = (1..=size).map(|i| json!(i)).collect::<Vec<_>>(); |
| 199 | arr[size - 1] = json!(1); |
| 200 | is_unique(&arr) |
| 201 | } |
| 202 | } |