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 "SkScaledImageCache.h"
12 static void make_bm(SkBitmap* bm, int w, int h) {
13 bm->allocN32Pixels(w, h);
16 static const int COUNT = 10;
17 static const int DIM = 256;
19 static void test_cache(skiatest::Reporter* reporter, SkScaledImageCache& cache,
21 SkScaledImageCache::ID* id;
25 const SkScalar scale = 2;
26 for (int i = 0; i < COUNT; ++i) {
27 make_bm(&bm[i], DIM, DIM);
30 for (int i = 0; i < COUNT; ++i) {
33 SkScaledImageCache::ID* id = cache.findAndLock(bm[i], scale, scale, &tmp);
34 REPORTER_ASSERT(reporter, NULL == id);
36 make_bm(&tmp, DIM, DIM);
37 id = cache.addAndLock(bm[i], scale, scale, tmp);
38 REPORTER_ASSERT(reporter, NULL != id);
41 SkScaledImageCache::ID* id2 = cache.findAndLock(bm[i], scale, scale,
43 REPORTER_ASSERT(reporter, id == id2);
44 REPORTER_ASSERT(reporter, tmp.pixelRef() == tmp2.pixelRef());
45 REPORTER_ASSERT(reporter, tmp.width() == tmp2.width());
46 REPORTER_ASSERT(reporter, tmp.height() == tmp2.height());
53 // stress test, should trigger purges
55 for (size_t i = 0; i < COUNT * 100; ++i) {
59 make_bm(&tmp, DIM, DIM);
61 SkScaledImageCache::ID* id = cache.addAndLock(bm[0], incScale,
63 REPORTER_ASSERT(reporter, NULL != id);
68 // test the originals after all that purging
69 for (int i = 0; i < COUNT; ++i) {
71 id = cache.findAndLock(bm[i], scale, scale, &tmp);
77 cache.setTotalByteLimit(0);
80 #include "SkDiscardableMemoryPool.h"
82 static SkDiscardableMemoryPool* gPool;
83 static SkDiscardableMemory* pool_factory(size_t bytes) {
85 return gPool->create(bytes);
88 DEF_TEST(ImageCache, reporter) {
89 static const size_t defLimit = DIM * DIM * 4 * COUNT + 1024; // 1K slop
92 SkScaledImageCache cache(defLimit);
93 test_cache(reporter, cache, true);
96 SkAutoTUnref<SkDiscardableMemoryPool> pool(
97 SkDiscardableMemoryPool::Create(defLimit, NULL));
99 SkScaledImageCache cache(pool_factory);
100 test_cache(reporter, cache, true);
103 SkScaledImageCache cache(SkDiscardableMemory::Create);
104 test_cache(reporter, cache, false);
108 DEF_TEST(ImageCache_doubleAdd, r) {
109 // Adding the same key twice should be safe.
110 SkScaledImageCache cache(4096);
113 original.allocN32Pixels(40, 40);
116 scaled1.allocN32Pixels(20, 20);
119 scaled2.allocN32Pixels(20, 20);
121 SkScaledImageCache::ID* id1 = cache.addAndLock(original, 0.5f, 0.5f, scaled1);
122 SkScaledImageCache::ID* id2 = cache.addAndLock(original, 0.5f, 0.5f, scaled2);
123 // We don't really care if id1 == id2 as long as unlocking both works.
128 // Lookup should return the value that was added last.
129 SkScaledImageCache::ID* id = cache.findAndLock(original, 0.5f, 0.5f, &tmp);
130 REPORTER_ASSERT(r, NULL != id);
131 REPORTER_ASSERT(r, tmp.getGenerationID() == scaled2.getGenerationID());