1 /*
2 * Copyright 2011 Google Inc.
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 "src/core/SkWriter32.h"
9
10 #include "include/core/SkSamplingOptions.h"
11 #include "include/private/base/SkTo.h"
12 #include "src/core/SkMatrixPriv.h"
13
writeMatrix(const SkMatrix & matrix)14 void SkWriter32::writeMatrix(const SkMatrix& matrix) {
15 size_t size = SkMatrixPriv::WriteToMemory(matrix, nullptr);
16 SkASSERT(SkAlign4(size) == size);
17 SkMatrixPriv::WriteToMemory(matrix, this->reserve(size));
18 }
19
writeSampling(const SkSamplingOptions & sampling)20 void SkWriter32::writeSampling(const SkSamplingOptions& sampling) {
21 this->write32(sampling.maxAniso);
22 if (!sampling.isAniso()) {
23 this->writeBool(sampling.useCubic);
24 if (sampling.useCubic) {
25 this->writeScalar(sampling.cubic.B);
26 this->writeScalar(sampling.cubic.C);
27 } else {
28 this->write32((unsigned)sampling.filter);
29 this->write32((unsigned)sampling.mipmap);
30 }
31 }
32 }
33
writeString(const char str[],size_t len)34 void SkWriter32::writeString(const char str[], size_t len) {
35 if (nullptr == str) {
36 str = "";
37 len = 0;
38 }
39 if ((long)len < 0) {
40 len = strlen(str);
41 }
42
43 // [ 4 byte len ] [ str ... ] [1 - 4 \0s]
44 uint32_t* ptr = this->reservePad(sizeof(uint32_t) + len + 1);
45 *ptr = SkToU32(len);
46 char* chars = (char*)(ptr + 1);
47 memcpy(chars, str, len);
48 chars[len] = '\0';
49 }
50
WriteStringSize(const char * str,size_t len)51 size_t SkWriter32::WriteStringSize(const char* str, size_t len) {
52 if ((long)len < 0) {
53 SkASSERT(str);
54 len = strlen(str);
55 }
56 const size_t lenBytes = 4; // we use 4 bytes to record the length
57 // add 1 since we also write a terminating 0
58 return SkAlign4(lenBytes + len + 1);
59 }
60
growToAtLeast(size_t size)61 void SkWriter32::growToAtLeast(size_t size) {
62 const bool wasExternal = (fExternal != nullptr) && (fData == fExternal);
63
64 fCapacity = 4096 + std::max(size, fCapacity + (fCapacity / 2));
65 fInternal.realloc(fCapacity);
66 fData = fInternal.get();
67
68 if (wasExternal) {
69 // we were external, so copy in the data
70 memcpy(fData, fExternal, fUsed);
71 }
72 }
73
snapshotAsData() const74 sk_sp<SkData> SkWriter32::snapshotAsData() const {
75 return SkData::MakeWithCopy(fData, fUsed);
76 }
77