MemoryCache.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  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. #ifndef MemoryCache_DEFINED
  8. #define MemoryCache_DEFINED
  9. #include "include/core/SkData.h"
  10. #include "include/gpu/GrContextOptions.h"
  11. #include "include/private/SkChecksum.h"
  12. #include <unordered_map>
  13. namespace sk_gpu_test {
  14. /**
  15. * This class can be used to maintain an in memory record of all programs cached by GrContext.
  16. * It can be shared by multiple GrContexts so long as those GrContexts are created with the same
  17. * options and will have the same GrCaps (e.g. same backend, same GL context creation parameters,
  18. * ...).
  19. */
  20. class MemoryCache : public GrContextOptions::PersistentCache {
  21. public:
  22. MemoryCache() = default;
  23. MemoryCache(const MemoryCache&) = delete;
  24. MemoryCache& operator=(const MemoryCache&) = delete;
  25. void reset() {
  26. fCacheMissCnt = 0;
  27. fMap.clear();
  28. }
  29. sk_sp<SkData> load(const SkData& key) override;
  30. void store(const SkData& key, const SkData& data) override;
  31. int numCacheMisses() const { return fCacheMissCnt; }
  32. void resetNumCacheMisses() { fCacheMissCnt = 0; }
  33. void writeShadersToDisk(const char* path, GrBackendApi backend);
  34. template <typename Fn>
  35. void foreach(Fn&& fn) {
  36. for (auto it = fMap.begin(); it != fMap.end(); ++it) {
  37. fn(it->first.fKey, it->second.fData, it->second.fHitCount);
  38. }
  39. }
  40. private:
  41. struct Key {
  42. Key() = default;
  43. Key(const SkData& key) : fKey(SkData::MakeWithCopy(key.data(), key.size())) {}
  44. Key(const Key& that) = default;
  45. Key& operator=(const Key&) = default;
  46. bool operator==(const Key& that) const {
  47. return that.fKey->size() == fKey->size() &&
  48. !memcmp(fKey->data(), that.fKey->data(), that.fKey->size());
  49. }
  50. sk_sp<const SkData> fKey;
  51. };
  52. struct Value {
  53. Value() = default;
  54. Value(const SkData& data)
  55. : fData(SkData::MakeWithCopy(data.data(), data.size()))
  56. , fHitCount(1) {}
  57. Value(const Value& that) = default;
  58. Value& operator=(const Value&) = default;
  59. sk_sp<SkData> fData;
  60. int fHitCount;
  61. };
  62. struct Hash {
  63. using argument_type = Key;
  64. using result_type = uint32_t;
  65. uint32_t operator()(const Key& key) const {
  66. return key.fKey ? SkOpts::hash_fn(key.fKey->data(), key.fKey->size(), 0) : 0;
  67. }
  68. };
  69. int fCacheMissCnt = 0;
  70. std::unordered_map<Key, Value, Hash> fMap;
  71. };
  72. } // namespace sk_gpu_test
  73. #endif