blob: 568f755ac5acd5d19c829c564c4fc02a1fac6d02 [file] [log] [blame]
Brian Salomon00a5eb82018-07-11 15:32:05 -04001/*
2 * Copyright 2018 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 MemoryCache_DEFINED
9#define MemoryCache_DEFINED
10
11#include <unordered_map>
12#include "GrContextOptions.h"
13#include "SkChecksum.h"
14#include "SkData.h"
15
16namespace sk_gpu_test {
17
18/**
19 * This class can be used to maintain an in memory record of all programs cached by GrContext.
20 * It can be shared by multiple GrContexts so long as those GrContexts are created with the same
21 * options and will have the same GrCaps (e.g. same backend, same GL context creation parameters,
22 * ...).
23 */
24class MemoryCache : public GrContextOptions::PersistentCache {
25public:
26 MemoryCache() = default;
27 MemoryCache(const MemoryCache&) = delete;
28 MemoryCache& operator=(const MemoryCache&) = delete;
29
30 sk_sp<SkData> load(const SkData& key) override;
31 void store(const SkData& key, const SkData& data) override;
32 int numCacheMisses() const { return fCacheMissCnt; }
33 void resetNumCacheMisses() { fCacheMissCnt = 0; }
34
35private:
36 struct Key {
37 Key() = default;
38 Key(const SkData& key) : fKey(SkData::MakeWithCopy(key.data(), key.size())) {}
39 Key(const Key& that) = default;
40 Key& operator=(const Key&) = default;
41 bool operator==(const Key& that) const {
42 return that.fKey->size() == fKey->size() &&
43 !memcmp(fKey->data(), that.fKey->data(), that.fKey->size());
44 }
45 sk_sp<const SkData> fKey;
46 };
47
48 struct Hash {
49 using argument_type = Key;
50 using result_type = uint32_t;
51 uint32_t operator()(const Key& key) const {
52 return key.fKey ? SkOpts::hash_fn(key.fKey->data(), key.fKey->size(), 0) : 0;
53 }
54 };
55
56 int fCacheMissCnt = 0;
57 std::unordered_map<Key, sk_sp<SkData>, Hash> fMap;
58};
59
60} // namespace sk_gpu_test
61
62#endif