xref: /aosp_15_r20/external/skia/src/core/SkPtrRecorder.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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 #include "src/core/SkPtrRecorder.h"
8 
9 #include "include/private/base/SkAssert.h"
10 #include "src/base/SkTSearch.h"
11 
reset()12 void SkPtrSet::reset() {
13     Pair* p = fList.begin();
14     Pair* stop = fList.end();
15     while (p < stop) {
16         this->decPtr(p->fPtr);
17         p += 1;
18     }
19     fList.reset();
20 }
21 
Less(const Pair & a,const Pair & b)22 bool SkPtrSet::Less(const Pair& a, const Pair& b) {
23     return (char*)a.fPtr < (char*)b.fPtr;
24 }
25 
find(void * ptr) const26 uint32_t SkPtrSet::find(void* ptr) const {
27     if (nullptr == ptr) {
28         return 0;
29     }
30 
31     int count = fList.size();
32     Pair pair;
33     pair.fPtr = ptr;
34 
35     int index = SkTSearch<Pair, Less>(fList.begin(), count, pair, sizeof(pair));
36     if (index < 0) {
37         return 0;
38     }
39     return fList[index].fIndex;
40 }
41 
add(void * ptr)42 uint32_t SkPtrSet::add(void* ptr) {
43     if (nullptr == ptr) {
44         return 0;
45     }
46 
47     int count = fList.size();
48     Pair pair;
49     pair.fPtr = ptr;
50 
51     int index = SkTSearch<Pair, Less>(fList.begin(), count, pair, sizeof(pair));
52     if (index < 0) {
53         index = ~index; // turn it back into an index for insertion
54         this->incPtr(ptr);
55         pair.fIndex = count + 1;
56         *fList.insert(index) = pair;
57         return count + 1;
58     } else {
59         return fList[index].fIndex;
60     }
61 }
62 
copyToArray(void * array[]) const63 void SkPtrSet::copyToArray(void* array[]) const {
64     int count = fList.size();
65     if (count > 0) {
66         SkASSERT(array);
67         const Pair* p = fList.begin();
68         // p->fIndex is base-1, so we need to subtract to find its slot
69         for (int i = 0; i < count; i++) {
70             int index = p[i].fIndex - 1;
71             SkASSERT((unsigned)index < (unsigned)count);
72             array[index] = p[i].fPtr;
73         }
74     }
75 }
76