6 #include "system/stacktrace.h"
7 #include "system/nth_alloc.h"
8 #include "linked_list.h"
19 static uint64_t fnv1(char *data, size_t size)
21 uint64_t hash = 0xcbf29ce484222325;
23 for (size_t i = 0; i < size; ++i) {
24 hash = hash * 0x100000001b3;
25 hash = hash ^ (uint64_t) data[i];
31 HashSet *create_hashset(size_t element_size, size_t n)
38 HashSet *hash_set = PUSH_LT(lt, nth_alloc(sizeof(HashSet)), free);
39 if (hash_set == NULL) {
45 hash_set->element_size = element_size;
47 hash_set->buckets = PUSH_LT(lt, nth_calloc(n, sizeof(LinkedList*)), free);
48 if (hash_set->buckets == NULL) {
52 for (size_t i = 0; i < n; ++i) {
53 hash_set->buckets[i] = PUSH_LT(
55 create_linked_list(element_size),
57 if (hash_set->buckets[i] == NULL) {
65 void destroy_hashset(HashSet *hashset)
67 trace_assert(hashset);
68 RETURN_LT0(hashset->lt);
71 int hashset_insert(HashSet *hashset, void *element)
73 trace_assert(hashset);
74 trace_assert(element);
76 const uint64_t hash = fnv1(element, hashset->element_size);
77 const size_t i = hash % hashset->n;
79 if (linked_list_find(hashset->buckets[i], element) == NULL) {
80 linked_list_push_back(hashset->buckets[i], element);
86 int hashset_remove(HashSet *hashset, void *element)
88 trace_assert(hashset);
89 trace_assert(element);
91 const uint64_t hash = fnv1(element, hashset->element_size);
92 const size_t i = hash % hashset->n;
94 NodeLL *node = linked_list_find(hashset->buckets[i], element);
97 linked_list_remove(hashset->buckets[i], node);
103 bool hashset_contains(HashSet *hashset, void *element)
105 trace_assert(hashset);
106 trace_assert(element);
108 const uint64_t hash = fnv1(element, hashset->element_size);
109 const size_t i = hash % hashset->n;
111 return linked_list_find(hashset->buckets[i], element) != NULL;
114 void hashset_clear(HashSet *hashset)
116 trace_assert(hashset);
118 for (size_t i = 0; i < hashset->n; ++i) {
119 linked_list_clear(hashset->buckets[i]);
123 size_t hashset_count(HashSet *hashset)
125 trace_assert(hashset);
129 HashSetIterator *hashset_begin(HashSet *hashset)
131 trace_assert(hashset);
135 HashSetIterator *hashset_next(HashSet *hashset, HashSetIterator *iter)
137 trace_assert(hashset);