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