SkPtrRecorder.cpp revision 15e9d3e66e161ce23df30bc13f8a0c87d196b463
1
2/*
3 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8#include "SkPtrRecorder.h"
9#include "SkTSearch.h"
10
11SK_DEFINE_INST_COUNT(SkPtrSet)
12
13void SkPtrSet::reset() {
14    Pair* p = fList.begin();
15    Pair* stop = fList.end();
16    while (p < stop) {
17        this->decPtr(p->fPtr);
18        p += 1;
19    }
20    fList.reset();
21}
22
23int SkPtrSet::Cmp(const Pair* a, const Pair* b) {
24    return (char*)a->fPtr - (char*)b->fPtr;
25}
26
27uint32_t SkPtrSet::find(void* ptr) const {
28    if (NULL == ptr) {
29        return 0;
30    }
31
32    int count = fList.count();
33    Pair pair;
34    pair.fPtr = ptr;
35
36    int index = SkTSearch<Pair>(fList.begin(), count, pair, sizeof(pair), &Cmp);
37    if (index < 0) {
38        return 0;
39    }
40    return fList[index].fIndex;
41}
42
43uint32_t SkPtrSet::add(void* ptr) {
44    if (NULL == ptr) {
45        return 0;
46    }
47
48    int count = fList.count();
49    Pair pair;
50    pair.fPtr = ptr;
51
52    int index = SkTSearch<Pair>(fList.begin(), count, pair, sizeof(pair), &Cmp);
53    if (index < 0) {
54        index = ~index; // turn it back into an index for insertion
55        this->incPtr(ptr);
56        pair.fIndex = count + 1;
57        *fList.insert(index) = pair;
58        return count + 1;
59    } else {
60        return fList[index].fIndex;
61    }
62}
63
64void SkPtrSet::copyToArray(void* array[]) const {
65    int count = fList.count();
66    if (count > 0) {
67        SkASSERT(array);
68        const Pair* p = fList.begin();
69        // p->fIndex is base-1, so we need to subtract to find its slot
70        for (int i = 0; i < count; i++) {
71            int index = p[i].fIndex - 1;
72            SkASSERT((unsigned)index < (unsigned)count);
73            array[index] = p[i].fPtr;
74        }
75    }
76}
77
78
79