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