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 SkTMultiMap_DEFINED
10 #define SkTMultiMap_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 typename HashTraits=T>
23 explicit ValueList(T* value) : fValue(value), fNext(NULL) {}
25 static const Key& GetKey(const ValueList& e) { return HashTraits::GetKey(*e.fValue); }
26 static uint32_t Hash(const Key& key) { return HashTraits::Hash(key); }
31 SkTMultiMap() : fCount(0) {}
34 SkASSERT(fCount == 0);
35 SkASSERT(fHash.count() == 0);
38 void insert(const Key& key, T* value) {
39 ValueList* list = fHash.find(key);
41 // The new ValueList entry is inserted as the second element in the
42 // linked list, and it will contain the value of the first element.
43 ValueList* newEntry = SkNEW_ARGS(ValueList, (list->fValue));
44 newEntry->fNext = list->fNext;
45 // The existing first ValueList entry is updated to contain the
47 list->fNext = newEntry;
50 fHash.add(SkNEW_ARGS(ValueList, (value)));
56 void remove(const Key& key, const T* value) {
57 ValueList* list = fHash.find(key);
58 // Since we expect the caller to be fully aware of what is stored, just
59 // assert that the caller removes an existing value.
60 SkASSERT(NULL != list);
61 ValueList* prev = NULL;
62 while (list->fValue != value) {
67 if (NULL != list->fNext) {
68 ValueList* next = list->fNext;
69 list->fValue = next->fValue;
70 list->fNext = next->fNext;
72 } else if (NULL != prev) {
83 T* find(const Key& key) const {
84 ValueList* list = fHash.find(key);
91 template<class FindPredicate>
92 T* find(const Key& key, const FindPredicate f) {
93 ValueList* list = fHash.find(key);
94 while (NULL != list) {
103 int count() const { return fCount; }
106 SkTDynamicHash<ValueList, Key> fHash;