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