blob: 119ea8dede38c69874092e644f249249182b8504 [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
Brian Osman5aa11fb2019-04-08 16:40:36 -040036 void writeShadersToDisk(const char* path, GrBackendApi backend);
37
Brian Salomon00a5eb82018-07-11 15:32:05 -040038private:
39 struct Key {
40 Key() = default;
41 Key(const SkData& key) : fKey(SkData::MakeWithCopy(key.data(), key.size())) {}
42 Key(const Key& that) = default;
43 Key& operator=(const Key&) = default;
44 bool operator==(const Key& that) const {
45 return that.fKey->size() == fKey->size() &&
46 !memcmp(fKey->data(), that.fKey->data(), that.fKey->size());
47 }
48 sk_sp<const SkData> fKey;
49 };
50
Brian Osman5aa11fb2019-04-08 16:40:36 -040051 struct Value {
52 Value() = default;
53 Value(const SkData& data)
54 : fData(SkData::MakeWithCopy(data.data(), data.size()))
55 , fHitCount(1) {}
56 Value(const Value& that) = default;
57 Value& operator=(const Value&) = default;
58
59 sk_sp<SkData> fData;
60 int fHitCount;
61 };
62
Brian Salomon00a5eb82018-07-11 15:32:05 -040063 struct Hash {
64 using argument_type = Key;
65 using result_type = uint32_t;
66 uint32_t operator()(const Key& key) const {
67 return key.fKey ? SkOpts::hash_fn(key.fKey->data(), key.fKey->size(), 0) : 0;
68 }
69 };
70
71 int fCacheMissCnt = 0;
Brian Osman5aa11fb2019-04-08 16:40:36 -040072 std::unordered_map<Key, Value, Hash> fMap;
Brian Salomon00a5eb82018-07-11 15:32:05 -040073};
74
75} // namespace sk_gpu_test
76
77#endif