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 "include/core/SkString.h"
9 #include "include/private/SkTo.h"
10 #include "src/core/SkMatrixPriv.h"
11 #include "src/core/SkReader32.h"
12 
13 #include "src/core/SkWriter32.h"
14 
writeMatrix(const SkMatrix & matrix)15 void SkWriter32::writeMatrix(const SkMatrix& matrix) {
16     size_t size = SkMatrixPriv::WriteToMemory(matrix, nullptr);
17     SkASSERT(SkAlign4(size) == size);
18     SkMatrixPriv::WriteToMemory(matrix, this->reserve(size));
19 }
20 
21 /*
22  *  Strings are stored as: length[4-bytes] + string_data + '\0' + pad_to_mul_4
23  */
24 
readString(size_t * outLen)25 const char* SkReader32::readString(size_t* outLen) {
26     size_t len = this->readU32();
27     const void* ptr = this->peek();
28 
29     // skip over the string + '\0' and then pad to a multiple of 4
30     size_t alignedSize = SkAlign4(len + 1);
31     this->skip(alignedSize);
32 
33     if (outLen) {
34         *outLen = len;
35     }
36     return (const char*)ptr;
37 }
38 
readIntoString(SkString * copy)39 size_t SkReader32::readIntoString(SkString* copy) {
40     size_t len;
41     const char* ptr = this->readString(&len);
42     if (copy) {
43         copy->set(ptr, len);
44     }
45     return len;
46 }
47 
writeString(const char str[],size_t len)48 void SkWriter32::writeString(const char str[], size_t len) {
49     if (nullptr == str) {
50         str = "";
51         len = 0;
52     }
53     if ((long)len < 0) {
54         len = strlen(str);
55     }
56 
57     // [ 4 byte len ] [ str ... ] [1 - 4 \0s]
58     uint32_t* ptr = this->reservePad(sizeof(uint32_t) + len + 1);
59     *ptr = SkToU32(len);
60     char* chars = (char*)(ptr + 1);
61     memcpy(chars, str, len);
62     chars[len] = '\0';
63 }
64 
WriteStringSize(const char * str,size_t len)65 size_t SkWriter32::WriteStringSize(const char* str, size_t len) {
66     if ((long)len < 0) {
67         SkASSERT(str);
68         len = strlen(str);
69     }
70     const size_t lenBytes = 4;    // we use 4 bytes to record the length
71     // add 1 since we also write a terminating 0
72     return SkAlign4(lenBytes + len + 1);
73 }
74 
growToAtLeast(size_t size)75 void SkWriter32::growToAtLeast(size_t size) {
76     const bool wasExternal = (fExternal != nullptr) && (fData == fExternal);
77 
78     fCapacity = 4096 + SkTMax(size, fCapacity + (fCapacity / 2));
79     fInternal.realloc(fCapacity);
80     fData = fInternal.get();
81 
82     if (wasExternal) {
83         // we were external, so copy in the data
84         memcpy(fData, fExternal, fUsed);
85     }
86 }
87 
snapshotAsData() const88 sk_sp<SkData> SkWriter32::snapshotAsData() const {
89     return SkData::MakeWithCopy(fData, fUsed);
90 }
91