1
2 /*
3 * Copyright 2009 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10 #include "SkColorTable.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkStream.h"
14 #include "SkTemplates.h"
15
init(const SkPMColor colors[],int count)16 void SkColorTable::init(const SkPMColor colors[], int count) {
17 SkASSERT((unsigned)count <= 256);
18
19 fCount = count;
20 fColors = reinterpret_cast<SkPMColor*>(sk_malloc_throw(count * sizeof(SkPMColor)));
21
22 memcpy(fColors, colors, count * sizeof(SkPMColor));
23 }
24
SkColorTable(const SkPMColor colors[],int count)25 SkColorTable::SkColorTable(const SkPMColor colors[], int count) {
26 SkASSERT(0 == count || colors);
27 if (count < 0) {
28 count = 0;
29 } else if (count > 256) {
30 count = 256;
31 }
32 this->init(colors, count);
33 }
34
~SkColorTable()35 SkColorTable::~SkColorTable() {
36 sk_free(fColors);
37 // f16BitCache frees itself
38 }
39
40 #include "SkColorPriv.h"
41
42 namespace {
43 struct Build16BitCache {
44 const SkPMColor* fColors;
45 int fCount;
46
operator ()__anonf643ee6d0111::Build16BitCache47 uint16_t* operator()() const {
48 uint16_t* cache = (uint16_t*)sk_malloc_throw(fCount * sizeof(uint16_t));
49 for (int i = 0; i < fCount; i++) {
50 cache[i] = SkPixel32ToPixel16_ToU16(fColors[i]);
51 }
52 return cache;
53 }
54 };
55 }//namespace
56
Free16BitCache(uint16_t * cache)57 void SkColorTable::Free16BitCache(uint16_t* cache) { sk_free(cache); }
58
read16BitCache() const59 const uint16_t* SkColorTable::read16BitCache() const {
60 const Build16BitCache create = { fColors, fCount };
61 return f16BitCache.get(create);
62 }
63
64 ///////////////////////////////////////////////////////////////////////////////
65
SkColorTable(SkReadBuffer & buffer)66 SkColorTable::SkColorTable(SkReadBuffer& buffer) {
67 if (buffer.isVersionLT(SkReadBuffer::kRemoveColorTableAlpha_Version)) {
68 /*fAlphaType = */buffer.readUInt();
69 }
70
71 fCount = buffer.getArrayCount();
72 size_t allocSize = fCount * sizeof(SkPMColor);
73 SkDEBUGCODE(bool success = false;)
74 if (buffer.validateAvailable(allocSize)) {
75 fColors = (SkPMColor*)sk_malloc_throw(allocSize);
76 SkDEBUGCODE(success =) buffer.readColorArray(fColors, fCount);
77 } else {
78 fCount = 0;
79 fColors = NULL;
80 }
81 #ifdef SK_DEBUG
82 SkASSERT((unsigned)fCount <= 256);
83 SkASSERT(success);
84 #endif
85 }
86
writeToBuffer(SkWriteBuffer & buffer) const87 void SkColorTable::writeToBuffer(SkWriteBuffer& buffer) const {
88 buffer.writeColorArray(fColors, fCount);
89 }
90