xref: /aosp_15_r20/external/skia/src/core/SkScalar.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2010 The Android Open Source Project
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 "include/core/SkScalar.h"
9 #include "include/private/base/SkDebug.h"
10 
SkScalarInterpFunc(SkScalar searchKey,const SkScalar keys[],const SkScalar values[],int length)11 SkScalar SkScalarInterpFunc(SkScalar searchKey, const SkScalar keys[],
12                             const SkScalar values[], int length) {
13     SkASSERT(length > 0);
14     SkASSERT(keys != nullptr);
15     SkASSERT(values != nullptr);
16 #ifdef SK_DEBUG
17     for (int i = 1; i < length; i++) {
18         SkASSERT(keys[i-1] <= keys[i]);
19     }
20 #endif
21     int right = 0;
22     while (right < length && keys[right] < searchKey) {
23         ++right;
24     }
25     // Could use sentinel values to eliminate conditionals, but since the
26     // tables are taken as input, a simpler format is better.
27     if (right == length) {
28         return values[length-1];
29     }
30     if (right == 0) {
31         return values[0];
32     }
33     // Otherwise, interpolate between right - 1 and right.
34     SkScalar leftKey = keys[right-1];
35     SkScalar rightKey = keys[right];
36     SkScalar fract = (searchKey - leftKey) / (rightKey - leftKey);
37     return SkScalarInterp(values[right-1], values[right], fract);
38 }
39