1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.core.collections;
7 
8 /// A simple hash set implementation using the build-in AA.
9 final class HashSet(T)
10 {
11   private:
12   /// The build-in AA.
13   ubyte[T] _set;
14 
15   public:
16   final:
17   /// Creates a new hash set.
18   this() { }
19 
20   /**
21   * Creates a new hash set from a sequence of elements.
22   */
23   this(T[] elements)
24   {
25     if (elements && elements.length)
26     {
27       foreach (element; elements)
28       {
29         _set[element] = 0;
30       }
31     }
32   }
33 
34   /**
35   * Adds a value to the hash set.
36   * Params:
37   *   value = The value added to the hash set.
38   */
39   void add(T value)
40   {
41     _set[value] = 0;
42   }
43 
44   /**
45   * Checks whether the hash set contains the given value.
46   * Params:
47   *   value = The value to check for existence within the set.
48   * Returns:
49   *   True if the set contains the given value.
50   */
51   bool has(T value)
52   {
53     if (!_set)
54     {
55       return false;
56     }
57 
58     if (value in _set)
59     {
60       return true;
61     }
62 
63     return false;
64   }
65 
66   /**
67   * Operator overload for accessing the set like an array.
68   * This calls "bool has(T value);"
69   */
70   bool opIndex(T value)
71   {
72     return has(value);
73   }
74 }