| 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 uword At(intptr_t i) const { | |
| 39 ASSERT(i >= 0); | |
| 40 ASSERT(i < Size()); | |
| 41 return keys_[i]; | |
| 42 } | |
| 43 | |
| 44 // Returns false if the caller should stop adding entries to this HashSet. | |
| 45 bool Add(uword value) { | |
| 46 ASSERT(value != 0); | |
| 47 ASSERT(count_ < growth_limit_); | |
| 48 intptr_t hash = Hash(value); | |
| 49 while (true) { | |
| 50 if (keys_[hash] == value) { | |
| 51 return true; | |
| 52 } else if (SlotIsEmpty(hash)) { | |
| 53 keys_[hash] = value; | |
| 54 count_++; | |
| 55 return (count_ < growth_limit_); | |
| 56 } | |
| 57 hash = (hash + 1) & size_mask_; | |
| 58 // Ensure that we do not end up looping forever. | |
| 59 ASSERT(hash != Hash(value)); | |
| 60 } | |
| 61 UNREACHABLE(); | |
| 62 } | |
| 63 | |
| 64 bool Contains(uword value) const { | |
| 65 if (value == 0) { | |
| 66 return false; | |
| 67 } | |
| 68 intptr_t hash = Hash(value); | |
| 69 while (true) { | |
| 70 if (keys_[hash] == value) { | |
| 71 return true; | |
| 72 } else if (SlotIsEmpty(hash)) { | |
| 73 return false; | |
| 74 } | |
| 75 hash = (hash + 1) & size_mask_; | |
| 76 // Ensure that we do not end up looping forever. | |
| 77 ASSERT(hash != Hash(value)); | |
| 78 } | |
| 79 UNREACHABLE(); | |
| 80 } | |
| 81 | |
| 82 private: | |
| 83 intptr_t Hash(uword value) const { | |
| 84 return value & size_mask_; | |
| 85 } | |
| 86 | |
| 87 // Returns true if the given slot does not contain a value. | |
| 88 bool SlotIsEmpty(intptr_t index) const { | |
| 89 return keys_[index] == 0; | |
| 90 } | |
| 91 | |
| 92 uword* keys_; | |
| 93 intptr_t size_mask_; | |
| 94 intptr_t growth_limit_; | |
| 95 intptr_t count_; | |
| 96 intptr_t fill_ratio_; | |
| 97 | |
| 98 DISALLOW_IMPLICIT_CONSTRUCTORS(HashSet); | |
| 99 }; | |
| 100 | |
| 101 } // namespace dart | |
| 102 | |
| 103 #endif // VM_HASH_SET_H_ | |
| OLD | NEW |