title: What is the fastest correct way to detect that there are no duplicates in a JSON array?
body: <p>I need to check if all items are unique in an array of <code>serde_json::Value</code>. Since this type does not implement <code>Hash</code> I came up with the following solution:</p>
  
  <pre><code>use serde_json::{json, Value};
  use std::collections::HashSet;
  
  fn is_unique(items: &amp;[Value]) -&gt; bool {
      let mut seen = HashSet::with_capacity(items.len());
      for item in items.iter() {
          if !seen.insert(item.to_string()) {
              return false;
          }
      }
      true
  }
  
  fn main() {
      let value1 = json!([1, 2]);
      assert!(is_unique(&amp;value1.as_array().unwrap()));
      let value2 = json!([1, 1]);
      assert!(!is_unique(&amp;value2.as_array().unwrap()));
  }
  </code></pre>
  
  <p>I assume that it should only work if <code>serde_json</code> is built with <code>preserve_order</code> feature (to have objects serialized in the same order every time), but I am not 100% sure about it.</p>
  
  <p><strong>Main usage context</strong>:</p>
  
  <p>JSON Schema validation. "<a href="https://json-schema.org/understanding-json-schema/reference/array.html#uniqueness" rel="nofollow noreferrer">uniqueItems</a>" keyword implementation.</p>
  
  <p><strong>Related usage case</strong></p>
  
  <p>Deduplication of JSON arrays to optimize JSON Schema inference on them.</p>
  
  <p>For example, the input data is <code>[1, 2, {"foo": "bar"}]</code>. A straightforward inference might output this:</p>
  
  <pre><code>{
      "type": "array", 
      "items": {
          "anyOf": [
              {"type": "integer"}, 
              {"type": "integer"},
              {"type": "object", "required": ["foo"]}
          ]
      }
  }
  </code></pre>
  
  <p>values in <code>items/anyOf</code> can be reduced to only two values.</p>
  
  <p><strong>Question</strong>: What would be the most time-efficient and correct way to check that there are no duplicates in an arbitrary JSON array?</p>
  
  <p>I used <code>serde_json = "1.0.48"</code></p>
  
  <p><strong>Rust</strong>: 1.42.0</p>
  
  <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=26491642caf1c3e8c31a8d7a60f31a5e" rel="nofollow noreferrer">Playground</a></p>