aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/SkTHashCache.h
blob: cfee9722f2ea1c4e7366444dbf5a0b167291c833 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkTHASHCACHE_DEFINED
#define	SkTHASHCACHE_DEFINED

#include "SkTypes.h"
#include "SkTDynamicHash.h"

template <typename T,
typename Key,
typename Traits = T,
int kGrowPercent = 75 >
class SkTHashCache : public SkNoncopyable {
public:

    SkTHashCache() {
        this->reset();
    }

    ~SkTHashCache() {
        this->clear();
    }

    T* find(const Key& key) const {
        return fDict->find(key);
    }

    /**
     *  If element already in cache, return immediately the cached value
     */
    T& add(const T& add) {
        Key key = Traits::GetKey(add);
        if (T* val = this->find(key)) {
            return *val;
        }

        T* element = SkNEW_ARGS(T, (add));

        fDict->add(element);

        return *element;
    }

    int size() const {
        return fDict->count();
    }

    void reset() {
        this->clear();

        fDict.reset(SkNEW(DictType));
    }

private:
    typedef SkTDynamicHash<T, Key, Traits, kGrowPercent> DictType;

    void clear() {
        if (fDict.get()) {
            typename DictType::Iter it(fDict.get());

            while (!it.done()) {
                SkDELETE(&(*it));
                ++it;
            }
        }
    }

    SkAutoTDelete<DictType> fDict;
};

#endif	/* SkHASHCACHE_DEFINED */