2 * Copyright 2019 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "src/utils/SkCharToGlyphCache.h"
10 SkCharToGlyphCache::SkCharToGlyphCache() {
14 SkCharToGlyphCache::~SkCharToGlyphCache() {}
16 void SkCharToGlyphCache::reset() {
20 // Add sentinels so we can always rely on these to stop linear searches (in either direction)
21 // Neither is a legal unichar, so we don't care what glyphID we use.
23 *fK32.append() = 0x80000000; *fV16.append() = 0;
24 *fK32.append() = 0x7FFFFFFF; *fV16.append() = 0;
29 // Determined experimentally. For N much larger, the slope technique is faster.
30 // For N much smaller, a simple search is faster.
32 constexpr int kSmallCountLimit = 16;
34 // To use slope technique we need at least 2 real entries (+2 sentinels) hence the min of 4
36 constexpr int kMinCountForSlope = 4;
38 static int find_simple(const SkUnichar base[], int count, SkUnichar value) {
40 for (index = 0;; ++index) {
41 if (value <= base[index]) {
42 if (value < base[index]) {
43 index = ~index; // not found
51 static int find_with_slope(const SkUnichar base[], int count, SkUnichar value, double denom) {
52 SkASSERT(count >= kMinCountForSlope);
55 if (value <= base[1]) {
57 if (value < base[index]) {
60 } else if (value >= base[count - 2]) {
62 if (value > base[index]) {
66 // make our guess based on the "slope" of the current values
67 // index = 1 + (int64_t)(count - 2) * (value - base[1]) / (base[count - 2] - base[1]);
68 index = 1 + (int)(denom * (count - 2) * (value - base[1]));
69 SkASSERT(index >= 1 && index <= count - 2);
71 if (value >= base[index]) {
73 if (value <= base[index]) {
74 if (value < base[index]) {
75 index = ~index; // not found
81 for (--index;; --index) {
83 if (value >= base[index]) {
84 if (value > base[index]) {
95 int SkCharToGlyphCache::findGlyphIndex(SkUnichar unichar) const {
96 const int count = fK32.count();
98 if (count <= kSmallCountLimit) {
99 index = find_simple(fK32.begin(), count, unichar);
101 index = find_with_slope(fK32.begin(), count, unichar, fDenom);
109 void SkCharToGlyphCache::insertCharAndGlyph(int index, SkUnichar unichar, SkGlyphID glyph) {
110 SkASSERT(fK32.size() == fV16.size());
111 SkASSERT((unsigned)index < fK32.size());
112 SkASSERT(unichar < fK32[index]);
114 *fK32.insert(index) = unichar;
115 *fV16.insert(index) = glyph;
117 // if we've changed the first [1] or last [count-2] entry, recompute our slope
118 const int count = fK32.count();
119 if (count >= kMinCountForSlope && (index == 1 || index == count - 2)) {
120 SkASSERT(index >= 1 && index <= count - 2);
121 fDenom = 1.0 / ((double)fK32[count - 2] - fK32[1]);
125 for (int i = 1; i < fK32.count(); ++i) {
126 SkASSERT(fK32[i-1] < fK32[i]);