blob: c35df6c7460f3804633667811fb97d6999ffe3ef [file] [log] [blame]
piotaixre4b23142014-10-02 10:57:53 -07001/*
2 * Copyright 2014 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 "Test.h"
9#include "SkTHashCache.h"
10
11
12// Tests the SkTHashCache<T> class template.
13
14struct Tint {
15 uint32_t value;
16
17 bool operator==(const Tint& rhs) const {
18 return value == rhs.value;
19 }
20};
21
22class Element {
23public:
24
25 bool operator==(const Element& rhs) const {
26 return value == rhs.value && key == rhs.key;
27 }
28
29 static const Tint& GetKey(const Element& element) {
30 return element.key;
31 }
32
33 static uint32_t Hash(const Tint& key) {
34 return key.value;
35 }
36
37 Element(Tint key, int value) : key(key), value(value) {
38 }
39
40 Tint key;
41 int value;
42};
43
44typedef SkTHashCache<Element, Tint> CacheType;
45
46DEF_TEST(THashCache, reporter) {
47 Tint k11 = {11};
48 Element e11(k11, 22);
49
piotaixre4b23142014-10-02 10:57:53 -070050 Element e11Collision(k11, 0);
51 // Element e42(4, 2);
52
53 //Some tests for the class Element
54 REPORTER_ASSERT(reporter, Element::GetKey(e11) == k11);
55 REPORTER_ASSERT(reporter, Element::Hash(k11) == 11);
56
57 CacheType cache;
58
59 // Is the cahce correctly initialized ?
60 REPORTER_ASSERT(reporter, 0 == cache.size());
61 REPORTER_ASSERT(reporter, NULL == cache.find(k11));
62
63 Element& e11_c = cache.add(e11);
piotaixre4b23142014-10-02 10:57:53 -070064
65 // Tests for simple insertion, verifying that the returned element
66 // has the same values as the original one
67 REPORTER_ASSERT(reporter, 1 == cache.size());
68 REPORTER_ASSERT(reporter, NULL != cache.find(k11));
69 REPORTER_ASSERT(reporter, e11_c == e11);
70
71 Element& e11Collision_c = cache.add(e11Collision);
72 // Verifying that, in case of collision, the element alerady in the cache is not removed
73 REPORTER_ASSERT(reporter, e11Collision_c == e11);
74 REPORTER_ASSERT(reporter, 1 == cache.size());
75
76 Tint k42 = {42};
77 Element e42(k42, 2);
78 cache.add(e42);
79 // Can we add more than one element?
80 REPORTER_ASSERT(reporter, NULL != cache.find(k11));
81 REPORTER_ASSERT(reporter, NULL != cache.find(k42));
82 REPORTER_ASSERT(reporter, 2 == cache.size());
83
84 cache.reset();
85 // Does clear do its job?
86 REPORTER_ASSERT(reporter, 0 == cache.size());
87 REPORTER_ASSERT(reporter, NULL == cache.find(k11));
88 REPORTER_ASSERT(reporter, NULL == cache.find(k42));
89}