2 * Copyright 2021 Google LLC
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef skgpu_KeyBuilder_DEFINED
9 #define skgpu_KeyBuilder_DEFINED
11 #include "include/core/SkString.h"
12 #include "include/private/SkTArray.h"
18 KeyBuilder(SkTArray<uint32_t, true>* data) : fData(data) {}
20 virtual ~KeyBuilder() {
21 // Ensure that flush was called before we went out of scope
22 SkASSERT(fBitsUsed == 0);
25 virtual void addBits(uint32_t numBits, uint32_t val, const char* label) {
26 SkASSERT(numBits > 0 && numBits <= 32);
27 SkASSERT(numBits == 32 || (val < (1u << numBits)));
29 fCurValue |= (val << fBitsUsed);
32 if (fBitsUsed >= 32) {
33 // Overflow, start a new working value
34 fData->push_back(fCurValue);
35 uint32_t excess = fBitsUsed - 32;
36 fCurValue = excess ? (val >> (numBits - excess)) : 0;
40 SkASSERT(fCurValue < (1u << fBitsUsed));
43 void addBytes(uint32_t numBytes, const void* data, const char* label) {
44 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(data);
45 for (; numBytes --> 0; bytes++) {
46 this->addBits(8, *bytes, label);
50 void addBool(bool b, const char* label) {
51 this->addBits(1, b, label);
54 void add32(uint32_t v, const char* label = "unknown") {
55 this->addBits(32, v, label);
58 virtual void appendComment(const char* comment) {}
60 // Introduces a word-boundary in the key. Must be called before using the key with any cache,
61 // but can also be called to create a break between generic data and backend-specific data.
64 fData->push_back(fCurValue);
71 SkTArray<uint32_t, true>* fData;
72 uint32_t fCurValue = 0;
73 uint32_t fBitsUsed = 0; // ... in current value
76 class StringKeyBuilder : public KeyBuilder {
78 StringKeyBuilder(SkTArray<uint32_t, true>* data) : KeyBuilder(data) {}
80 void addBits(uint32_t numBits, uint32_t val, const char* label) override {
81 KeyBuilder::addBits(numBits, val, label);
82 fDescription.appendf("%s: %u\n", label, val);
85 void appendComment(const char* comment) override {
86 fDescription.appendf("%s\n", comment);
89 SkString description() const { return fDescription; }
92 SkString fDescription;
97 #endif // skgpu_KeyBuilder_DEFINED