| 1 | /* |
| 2 | * Copyright 2013 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
| 8 | #ifndef SkTDynamicHash_DEFINED |
| 9 | #define SkTDynamicHash_DEFINED |
| 10 | |
| 11 | // This is now a simple API wrapper around SkTHashTable<T*>; |
| 12 | // please just use SkTHash{Map,Set,Table} directly for new code. |
| 13 | #include "include/private/SkTHash.h" |
| 14 | |
| 15 | // Traits requires: |
| 16 | // static const Key& GetKey(const T&) { ... } |
| 17 | // static uint32_t Hash(const Key&) { ... } |
| 18 | // We'll look on T for these by default, or you can pass a custom Traits type. |
| 19 | template <typename T, |
| 20 | typename Key, |
| 21 | typename Traits = T> |
| 22 | class SkTDynamicHash { |
| 23 | public: |
| 24 | SkTDynamicHash() {} |
| 25 | |
| 26 | // It is not safe to call set() or remove() while iterating with either foreach(). |
| 27 | // If you mutate the entries be very careful not to change the Key. |
| 28 | |
| 29 | template <typename Fn> // f(T*) |
| 30 | void foreach(Fn&& fn) { |
| 31 | fTable.foreach([&](T** entry) { fn(*entry); }); |
| 32 | } |
| 33 | template <typename Fn> // f(T) or f(const T&) |
| 34 | void foreach(Fn&& fn) const { |
| 35 | fTable.foreach([&](T* entry) { fn(*entry); }); |
| 36 | } |
| 37 | |
| 38 | int count() const { return fTable.count(); } |
| 39 | |
| 40 | T* find(const Key& key) const { return fTable.findOrNull(key); } |
| 41 | |
| 42 | void add(T* entry) { fTable.set(entry); } |
| 43 | void remove(const Key& key) { fTable.remove(key); } |
| 44 | |
| 45 | void rewind() { fTable.reset(); } |
| 46 | void reset () { fTable.reset(); } |
| 47 | |
| 48 | private: |
| 49 | struct AdaptedTraits { |
| 50 | static const Key& GetKey(T* entry) { return Traits::GetKey(*entry); } |
| 51 | static uint32_t Hash(const Key& key) { return Traits::Hash(key); } |
| 52 | }; |
| 53 | SkTHashTable<T*, Key, AdaptedTraits> fTable; |
| 54 | }; |
| 55 | |
| 56 | #endif |
| 57 | |