3 * Copyright 2013 Google Inc.
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
9 #ifndef GrTMultiMap_DEFINED
10 #define GrTMultiMap_DEFINED
13 #include "SkTDynamicHash.h"
15 /** A set that contains pointers to instances of T. Instances can be looked up with key Key.
16 * Multiple (possibly same) values can have the same key.
20 const Key& (GetKey)(const T&),
21 uint32_t (Hash)(const Key&),
22 bool (Equal)(const T&, const Key&)>
25 explicit ValueList(T* value) : fValue(value), fNext(NULL) {}
27 static const Key& ListGetKey(const ValueList& e) { return GetKey(*e.fValue); }
28 static uint32_t ListHash(const Key& key) { return Hash(key); }
29 static bool ListEqual(const ValueList& a, const Key& b) {
30 return Equal(*a.fValue, b);
36 GrTMultiMap() : fCount(0) {}
39 SkASSERT(fCount == 0);
40 SkASSERT(fHash.count() == 0);
43 void insert(const Key& key, T* value) {
44 ValueList* list = fHash.find(key);
46 // The new ValueList entry is inserted as the second element in the
47 // linked list, and it will contain the value of the first element.
48 ValueList* newEntry = SkNEW_ARGS(ValueList, (list->fValue));
49 newEntry->fNext = list->fNext;
50 // The existing first ValueList entry is updated to contain the
52 list->fNext = newEntry;
55 fHash.add(SkNEW_ARGS(ValueList, (value)));
61 void remove(const Key& key, const T* value) {
62 ValueList* list = fHash.find(key);
63 // Since we expect the caller to be fully aware of what is stored, just
64 // assert that the caller removes an existing value.
65 SkASSERT(NULL != list);
66 ValueList* prev = NULL;
67 while (list->fValue != value) {
72 if (NULL != list->fNext) {
73 ValueList* next = list->fNext;
74 list->fValue = next->fValue;
75 list->fNext = next->fNext;
77 } else if (NULL != prev) {
88 T* find(const Key& key) const {
89 ValueList* list = fHash.find(key);
96 template<class FindPredicate>
97 T* find(const Key& key, const FindPredicate f) {
98 ValueList* list = fHash.find(key);
99 while (NULL != list) {
100 if (f(list->fValue)){
108 int count() const { return fCount; }
111 SkTDynamicHash<ValueList,
113 ValueList::ListGetKey,
115 ValueList::ListEqual> fHash;