aboutsummaryrefslogtreecommitdiffhomepage
path: root/tests/THashCache.cpp
blob: 7797431553b078c455460a90fb0a77814a047709 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkTHashCache.h"


// Tests the SkTHashCache<T> class template.

struct Tint {
    uint32_t value;

    bool operator==(const Tint& rhs) const {
        return value == rhs.value;
    }
};

class Element {
public:

    bool operator==(const Element& rhs) const {
        return value == rhs.value && key == rhs.key;
    }

    static const Tint& GetKey(const Element& element) {
        return element.key;
    }

    static uint32_t Hash(const Tint& key) {
        return key.value;
    }

    Element(Tint key, int value) : key(key), value(value) {
    }

    Tint key;
    int value;
};

typedef SkTHashCache<Element, Tint> CacheType;

DEF_TEST(THashCache, reporter) {
    Tint k11 = {11};
    Element e11(k11, 22);

    e11.value = e11.value;
    Element e11Collision(k11, 0);
    //    Element e42(4, 2);

    //Some tests for the class Element
    REPORTER_ASSERT(reporter, Element::GetKey(e11) == k11);
    REPORTER_ASSERT(reporter, Element::Hash(k11) == 11);

    CacheType cache;

    // Is the cahce correctly initialized ?
    REPORTER_ASSERT(reporter, 0 == cache.size());
    REPORTER_ASSERT(reporter, NULL == cache.find(k11));

    Element& e11_c = cache.add(e11);
    e11_c.value = e11_c.value;

    // Tests for simple insertion, verifying that the returned element
    // has the same values as the original one
    REPORTER_ASSERT(reporter, 1 == cache.size());
    REPORTER_ASSERT(reporter, NULL != cache.find(k11));
    REPORTER_ASSERT(reporter, e11_c == e11);

    Element& e11Collision_c = cache.add(e11Collision);
    // Verifying that, in case of collision, the element alerady in the cache is not removed
    REPORTER_ASSERT(reporter, e11Collision_c == e11);
    REPORTER_ASSERT(reporter, 1 == cache.size());

    Tint k42 = {42};
    Element e42(k42, 2);
    cache.add(e42);
    // Can we add more than one element?
    REPORTER_ASSERT(reporter, NULL != cache.find(k11));
    REPORTER_ASSERT(reporter, NULL != cache.find(k42));
    REPORTER_ASSERT(reporter, 2 == cache.size());

    cache.reset();
    // Does clear do its job?
    REPORTER_ASSERT(reporter, 0 == cache.size());
    REPORTER_ASSERT(reporter, NULL == cache.find(k11));
    REPORTER_ASSERT(reporter, NULL == cache.find(k42));
}