OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 #ifndef VM_HASH_SET_H_ | |
6 #define VM_HASH_SET_H_ | |
7 | |
8 #include "vm/allocation.h" | |
9 #include "platform/utils.h" | |
10 | |
11 namespace dart { | |
12 | |
13 class HashSet { | |
14 public: | |
15 HashSet(intptr_t size, intptr_t fill_ratio) | |
16 : keys_(new uword[size]), | |
17 size_mask_(size - 1), | |
18 growth_limit_((size * fill_ratio) / 100), | |
19 count_(0), | |
20 fill_ratio_(fill_ratio) { | |
21 ASSERT(Utils::IsPowerOfTwo(size)); | |
22 ASSERT(fill_ratio < 100); | |
23 memset(keys_, 0, size * sizeof(*keys_)); | |
24 } | |
25 | |
26 ~HashSet() { | |
27 delete[] keys_; | |
28 } | |
29 | |
30 intptr_t Size() const { | |
31 return size_mask_ + 1; | |
32 } | |
33 | |
34 intptr_t Count() const { | |
35 return count_; | |
36 } | |
37 | |
38 bool Add(uword value) { | |
siva
2012/07/02 20:57:42
Maybe we should add a comment on the top that the
Ivan Posva
2012/07/03 00:10:24
Done.
| |
39 ASSERT(value != 0); | |
40 intptr_t hash = Hash(value); | |
41 while (true) { | |
42 if (keys_[hash] == value) { | |
43 return true; | |
44 } else if (SlotIsEmpty(hash)) { | |
45 keys_[hash] = value; | |
46 count_++; | |
47 return (count_ < growth_limit_); | |
48 } | |
49 hash = (hash + 1) & size_mask_; | |
50 // Ensure that we do not end up looping forever. | |
51 ASSERT(hash != Hash(value)); | |
52 } | |
53 UNREACHABLE(); | |
54 } | |
55 | |
56 bool Contains(uword value) { | |
siva
2012/07/02 20:57:42
bool Contains(uword value) const {
Ivan Posva
2012/07/03 00:10:24
Done.
| |
57 if (value == 0) { | |
58 return false; | |
59 } | |
60 intptr_t hash = Hash(value); | |
61 while (true) { | |
62 if (keys_[hash] == value) { | |
63 return true; | |
64 } else if (SlotIsEmpty(hash)) { | |
65 return false; | |
66 } | |
67 hash = (hash + 1) & size_mask_; | |
68 // Ensure that we do not end up looping forever. | |
69 ASSERT(hash != Hash(value)); | |
70 } | |
71 UNREACHABLE(); | |
72 } | |
73 | |
74 private: | |
75 intptr_t Hash(uword value) const { | |
76 return value & size_mask_; | |
77 } | |
78 | |
79 // Returns true if the given slot contains a value. | |
80 bool SlotIsEmpty(intptr_t index) const { | |
81 return keys_[index] == 0; | |
82 } | |
83 | |
84 uword* keys_; | |
85 intptr_t size_mask_; | |
86 intptr_t growth_limit_; | |
87 intptr_t count_; | |
88 intptr_t fill_ratio_; | |
89 | |
90 DISALLOW_IMPLICIT_CONSTRUCTORS(HashSet); | |
91 }; | |
92 | |
93 } // namespace dart | |
94 | |
95 #endif // VM_HASH_SET_H_ | |
OLD | NEW |