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
16void 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
25SkColorTable::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
35SkColorTable::~SkColorTable() {
36    sk_free(fColors);
37    // f16BitCache frees itself
38}
39
40#include "SkColorPriv.h"
41
42namespace {
43struct Build16BitCache {
44    const SkPMColor* fColors;
45    int fCount;
46
47    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
57void SkColorTable::Free16BitCache(uint16_t* cache) { sk_free(cache); }
58
59const uint16_t* SkColorTable::read16BitCache() const {
60    const Build16BitCache create = { fColors, fCount };
61    return f16BitCache.get(create);
62}
63
64///////////////////////////////////////////////////////////////////////////////
65
66SkColorTable::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
87void SkColorTable::writeToBuffer(SkWriteBuffer& buffer) const {
88    buffer.writeColorArray(fColors, fCount);
89}
90