1/*
2 * Copyright 2011 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 "SkRefDict.h"
9#include "Test.h"
10
11class TestRC : public SkRefCnt {
12public:
13    SK_DECLARE_INST_COUNT(TestRC)
14private:
15    typedef SkRefCnt INHERITED;
16};
17
18DEF_TEST(RefDict, reporter) {
19    TestRC    data0, data1;
20    SkRefDict dict;
21
22    REPORTER_ASSERT(reporter, NULL == dict.find(NULL));
23    REPORTER_ASSERT(reporter, NULL == dict.find("foo"));
24    REPORTER_ASSERT(reporter, NULL == dict.find("bar"));
25
26    dict.set("foo", &data0);
27    REPORTER_ASSERT(reporter, &data0 == dict.find("foo"));
28    REPORTER_ASSERT(reporter, 2 == data0.getRefCnt());
29
30    dict.set("foo", &data0);
31    REPORTER_ASSERT(reporter, &data0 == dict.find("foo"));
32    REPORTER_ASSERT(reporter, 2 == data0.getRefCnt());
33
34    dict.set("foo", &data1);
35    REPORTER_ASSERT(reporter, &data1 == dict.find("foo"));
36    REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
37    REPORTER_ASSERT(reporter, 2 == data1.getRefCnt());
38
39    dict.set("foo", NULL);
40    REPORTER_ASSERT(reporter, NULL == dict.find("foo"));
41    REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
42    REPORTER_ASSERT(reporter, 1 == data1.getRefCnt());
43
44    dict.set("foo", &data0);
45    dict.set("bar", &data1);
46    REPORTER_ASSERT(reporter, &data0 == dict.find("foo"));
47    REPORTER_ASSERT(reporter, &data1 == dict.find("bar"));
48    REPORTER_ASSERT(reporter, 2 == data0.getRefCnt());
49    REPORTER_ASSERT(reporter, 2 == data1.getRefCnt());
50
51    dict.set("foo", &data1);
52    REPORTER_ASSERT(reporter, &data1 == dict.find("foo"));
53    REPORTER_ASSERT(reporter, &data1 == dict.find("bar"));
54    REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
55    REPORTER_ASSERT(reporter, 3 == data1.getRefCnt());
56
57    dict.removeAll();
58    REPORTER_ASSERT(reporter, NULL == dict.find("foo"));
59    REPORTER_ASSERT(reporter, NULL == dict.find("bar"));
60    REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
61    REPORTER_ASSERT(reporter, 1 == data1.getRefCnt());
62
63    {
64        SkRefDict d;
65        REPORTER_ASSERT(reporter, NULL == d.find("foo"));
66        REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
67        d.set("foo", &data0);
68        REPORTER_ASSERT(reporter, &data0 == d.find("foo"));
69        REPORTER_ASSERT(reporter, 2 == data0.getRefCnt());
70        // let d go out of scope still with a ref on data0
71    }
72    // be sure d's destructor lowered data0's owner count back to 1
73    REPORTER_ASSERT(reporter, 1 == data0.getRefCnt());
74}
75