2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkDiscardableMemory.h"
9 #include "SkResourceCache.h"
13 static void* gGlobalAddress;
14 struct TestingKey : public SkResourceCache::Key {
17 TestingKey(intptr_t value) : fValue(value) {
18 this->init(&gGlobalAddress, sizeof(fValue));
21 struct TestingRec : public SkResourceCache::Rec {
22 TestingRec(const TestingKey& key, uint32_t value) : fKey(key), fValue(value) {}
27 virtual const Key& getKey() const SK_OVERRIDE { return fKey; }
28 virtual size_t bytesUsed() const SK_OVERRIDE { return sizeof(fKey) + sizeof(fValue); }
30 static bool Visitor(const SkResourceCache::Rec& baseRec, void* context) {
31 const TestingRec& rec = static_cast<const TestingRec&>(baseRec);
32 intptr_t* result = (intptr_t*)context;
40 static const int COUNT = 10;
41 static const int DIM = 256;
43 static void test_cache(skiatest::Reporter* reporter, SkResourceCache& cache, bool testPurge) {
44 for (int i = 0; i < COUNT; ++i) {
48 REPORTER_ASSERT(reporter, !cache.find(key, TestingRec::Visitor, &value));
49 REPORTER_ASSERT(reporter, -1 == value);
51 cache.add(SkNEW_ARGS(TestingRec, (key, i)));
53 REPORTER_ASSERT(reporter, cache.find(key, TestingRec::Visitor, &value));
54 REPORTER_ASSERT(reporter, i == value);
58 // stress test, should trigger purges
59 for (size_t i = 0; i < COUNT * 100; ++i) {
61 cache.add(SkNEW_ARGS(TestingRec, (key, i)));
65 // test the originals after all that purging
66 for (int i = 0; i < COUNT; ++i) {
68 (void)cache.find(TestingKey(i), TestingRec::Visitor, &value);
71 cache.setTotalByteLimit(0);
74 #include "SkDiscardableMemoryPool.h"
76 static SkDiscardableMemoryPool* gPool;
77 static SkDiscardableMemory* pool_factory(size_t bytes) {
79 return gPool->create(bytes);
82 DEF_TEST(ImageCache, reporter) {
83 static const size_t defLimit = DIM * DIM * 4 * COUNT + 1024; // 1K slop
86 SkResourceCache cache(defLimit);
87 test_cache(reporter, cache, true);
90 SkAutoTUnref<SkDiscardableMemoryPool> pool(
91 SkDiscardableMemoryPool::Create(defLimit, NULL));
93 SkResourceCache cache(pool_factory);
94 test_cache(reporter, cache, true);
97 SkResourceCache cache(SkDiscardableMemory::Create);
98 test_cache(reporter, cache, false);
102 DEF_TEST(ImageCache_doubleAdd, r) {
103 // Adding the same key twice should be safe.
104 SkResourceCache cache(4096);
108 cache.add(SkNEW_ARGS(TestingRec, (key, 2)));
109 cache.add(SkNEW_ARGS(TestingRec, (key, 3)));
111 // Lookup can return either value.
113 REPORTER_ASSERT(r, cache.find(key, TestingRec::Visitor, &value));
114 REPORTER_ASSERT(r, 2 == value || 3 == value);