1 /*
2 * Copyright 2016 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 #include "src/core/SkLRUCache.h"
9 #include "tests/Test.h"
10
11 #include <memory>
12 #include <utility>
13
14 struct Value {
ValueValue15 Value(int value, int* counter)
16 : fValue(value)
17 , fCounter(counter) {
18 (*fCounter)++;
19 }
20
~ValueValue21 ~Value() {
22 (*fCounter)--;
23 }
24
25 int fValue;
26 int* fCounter;
27 };
28
DEF_TEST(LRUCacheSequential,r)29 DEF_TEST(LRUCacheSequential, r) {
30 int instances = 0;
31 {
32 static const int kSize = 100;
33 SkLRUCache<int, std::unique_ptr<Value>> test(kSize);
34 for (int i = 1; i < kSize * 2; i++) {
35 REPORTER_ASSERT(r, !test.find(i));
36 test.insert(i, std::make_unique<Value>(i * i, &instances));
37 REPORTER_ASSERT(r, test.find(i));
38 REPORTER_ASSERT(r, i * i == (*test.find(i))->fValue);
39 if (i > kSize) {
40 REPORTER_ASSERT(r, kSize == instances);
41 REPORTER_ASSERT(r, !test.find(i - kSize));
42 } else {
43 REPORTER_ASSERT(r, i == instances);
44 }
45 REPORTER_ASSERT(r, (int) test.count() == instances);
46 }
47 }
48 REPORTER_ASSERT(r, 0 == instances);
49 }
50
DEF_TEST(LRUCacheRandom,r)51 DEF_TEST(LRUCacheRandom, r) {
52 int instances = 0;
53 {
54 int seq[] = { 0, 1, 2, 3, 4, 1, 6, 2, 7, 5, 3, 2, 2, 3, 1, 7 };
55 int expected[] = { 7, 1, 3, 2, 5 };
56 static const int kSize = 5;
57 SkLRUCache<int, std::unique_ptr<Value>> test(kSize);
58 for (int i = 0; i < (int) (sizeof(seq) / sizeof(int)); i++) {
59 int k = seq[i];
60 if (!test.find(k)) {
61 test.insert(k, std::make_unique<Value>(k, &instances));
62 }
63 }
64 REPORTER_ASSERT(r, kSize == instances);
65 REPORTER_ASSERT(r, kSize == test.count());
66 for (int i = 0; i < kSize; i++) {
67 int k = expected[i];
68 REPORTER_ASSERT(r, test.find(k));
69 REPORTER_ASSERT(r, k == (*test.find(k))->fValue);
70 }
71 }
72 REPORTER_ASSERT(r, 0 == instances);
73 }
74