Skip to main content

valico/json_schema/validators/
unique_items.rs

1use serde_json::Value;
2
3use super::super::errors;
4use super::super::scope;
5
6#[allow(missing_copy_implementations)]
7pub struct UniqueItems;
8impl super::Validator for UniqueItems {
9    fn validate(
10        &self,
11        val: &Value,
12        path: &str,
13        _scope: &scope::Scope,
14        _: &super::ValidationState,
15    ) -> super::ValidationState {
16        let array = nonstrict_process!(val.as_array(), path);
17
18        // TODO we need some quicker algorithm for this
19
20        let mut unique = true;
21        'main: for (idx, item_i) in array.iter().enumerate() {
22            for item_j in array[..idx].iter() {
23                if item_i == item_j {
24                    unique = false;
25                    break 'main;
26                }
27            }
28
29            for item_j in array[(idx + 1)..].iter() {
30                if item_i == item_j {
31                    unique = false;
32                    break 'main;
33                }
34            }
35        }
36
37        if unique {
38            super::ValidationState::new()
39        } else {
40            val_error!(errors::UniqueItems {
41                path: path.to_string()
42            })
43        }
44    }
45}