SkWriter32.cpp 2.3 KB

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