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