Make SkTSearch variants with compare func as template param

Review URL: https://codereview.appspot.com/6345060/



git-svn-id: http://skia.googlecode.com/svn/trunk@4449 2bbb7eff-a529-9590-31e7-b0007b416f81
This commit is contained in:
bsalomon@google.com 2012-07-03 15:03:10 +00:00
parent 6ea165dd8f
commit 44f7c4a6f8
2 changed files with 68 additions and 2 deletions

View File

@ -63,6 +63,39 @@ int SkTSearch(const T* base, int count, const T& target, size_t elemSize)
return hi;
}
template <typename T, int (COMPARE)(const T*, const T*)>
int SkTSearch(const T* base, int count, const T& target, size_t elemSize)
{
SkASSERT(count >= 0);
if (count <= 0) {
return ~0;
}
SkASSERT(base != NULL); // base may be NULL if count is zero
int lo = 0;
int hi = count - 1;
while (lo < hi) {
int mid = (hi + lo) >> 1;
const T* elem = (const T*)((const char*)base + mid * elemSize);
if (COMPARE(elem, &target) < 0)
lo = mid + 1;
else
hi = mid;
}
const T* elem = (const T*)((const char*)base + hi * elemSize);
int pred = COMPARE(elem, &target);
if (pred != 0) {
if (pred < 0)
hi += 1;
hi = ~hi;
}
return hi;
}
template <typename T>
int SkTSearch(const T* base, int count, const T& target, size_t elemSize,
int (*compare)(const T*, const T*))
@ -132,6 +165,39 @@ int SkTSearch(const T** base, int count, const T* target, size_t elemSize,
return hi;
}
template <typename T, int (COMPARE)(const T*, const T*)>
int SkTSearch(const T** base, int count, const T* target, size_t elemSize)
{
SkASSERT(count >= 0);
if (count <= 0)
return ~0;
SkASSERT(base != NULL); // base may be NULL if count is zero
int lo = 0;
int hi = count - 1;
while (lo < hi)
{
int mid = (hi + lo) >> 1;
const T* elem = *(const T**)((const char*)base + mid * elemSize);
if (COMPARE(elem, target) < 0)
lo = mid + 1;
else
hi = mid;
}
const T* elem = *(const T**)((const char*)base + hi * elemSize);
int pred = COMPARE(elem, target);
if (pred != 0)
{
if (pred < 0)
hi += 1;
hi = ~hi;
}
return hi;
}
int SkStrSearch(const char*const* base, int count, const char target[],
size_t target_len, size_t elemSize);
int SkStrSearch(const char*const* base, int count, const char target[],

View File

@ -33,7 +33,7 @@ uint32_t SkPtrSet::find(void* ptr) const {
Pair pair;
pair.fPtr = ptr;
int index = SkTSearch<Pair>(fList.begin(), count, pair, sizeof(pair), &Cmp);
int index = SkTSearch<Pair, Cmp>(fList.begin(), count, pair, sizeof(pair));
if (index < 0) {
return 0;
}
@ -49,7 +49,7 @@ uint32_t SkPtrSet::add(void* ptr) {
Pair pair;
pair.fPtr = ptr;
int index = SkTSearch<Pair>(fList.begin(), count, pair, sizeof(pair), &Cmp);
int index = SkTSearch<Pair, Cmp>(fList.begin(), count, pair, sizeof(pair));
if (index < 0) {
index = ~index; // turn it back into an index for insertion
this->incPtr(ptr);