This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hashset.cpp
136 lines (119 loc) · 2.69 KB
/
hashset.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <cstdlib>
#include "hashset.h"
using namespace std;
hashset_iter::hashset_iter(const hashset &set)
: set(set),
index(0)
{
if (set.items[index] == 0 || set.items[index] == 1)
next();
}
const void *hashset_iter::value() const
{
return (const void *)set.items[index];
}
bool hashset_iter::has_next() const
{
if (set.nitems == 0 || index == set.capacity())
return false;
size_t ii = index;
while (ii < set.capacity()) {
if (set.items[ii] != 0 && set.items[ii] != 1)
return true;
++ii;
}
return false;
}
void hashset_iter::next()
{
if (index == set.capacity())
return;
do {
++index;
} while ((set.items[index] == 0 || set.items[index] == 1) && index < set.capacity());
}
const unsigned int hashset::PRIME1 = 73;
const unsigned int hashset::PRIME2 = 5009;
hashset::hashset()
: nbits(3),
items((uintptr_t *)calloc(capacity(), sizeof(uintptr_t))),
nitems(0)
{}
hashset::~hashset()
{
free(items);
}
void hashset::add_member(const void *item)
{
uintptr_t value = (uintptr_t)item;
if (value == 0 || value == 1)
return;
size_t ii = hash(value);
while (items[ii] != 0 && value != 1) {
if (items[ii] == value)
return;
else
ii = next_hash(ii);
}
nitems++;
items[ii] = value;
}
void hashset::maybe_rehash()
{
if (nitems > (size_t)(capacity() * 0.6)) {
uintptr_t *old_items;
size_t old_capacity;
old_items = items;
old_capacity = capacity();
nbits++;
items = (uintptr_t *)calloc(capacity(), sizeof(uintptr_t));
nitems = 0;
for (size_t ii = 0; ii < old_capacity; ii++)
add_member((const void *)old_items[ii]);
free(old_items);
}
}
void hashset::add(const void *item)
{
add_member(item);
maybe_rehash();
}
void hashset::remove(const void *item)
{
uintptr_t value = (uintptr_t)item;
size_t ii = hash(value);
while (items[ii] != 0) {
if (items[ii] == value) {
items[ii] = 1;
nitems--;
return;
}
else
ii = next_hash(ii);
}
}
void hashset::clear()
{
free(items);
nbits = 3;
items = (uintptr_t *)calloc(capacity(), sizeof(uintptr_t));
nitems = 0;
}
bool hashset::contains(const void *item) const
{
size_t value = (size_t)item;
if (value == 0 || value == 1)
return false;
size_t ii = hash(value);
while (items[ii] != 0) {
if (items[ii] == value)
return true;
else
ii = next_hash(ii);
}
return false;
}
hashset_iter hashset::iter() const
{
return hashset_iter(*this);
}