SkSharingProc.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2019 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 "tools/SkSharingProc.h"
  8. #include "include/core/SkData.h"
  9. #include "include/core/SkImage.h"
  10. #include "include/core/SkSerialProcs.h"
  11. sk_sp<SkData> SkSharingSerialContext::serializeImage(SkImage* img, void* ctx) {
  12. SkSharingSerialContext* context = reinterpret_cast<SkSharingSerialContext*>(ctx);
  13. uint32_t id = img->uniqueID(); // get this process's id for the image. these are not hashes.
  14. // find out if we have already serialized this, and if so, what its in-file id is.
  15. auto iter = context->fImageMap.find(id);
  16. if (iter == context->fImageMap.end()) {
  17. // When not present, add its id to the map and return its usual serialized form.
  18. context->fImageMap[id] = context->fImageMap.size();
  19. return img->encodeToData();
  20. }
  21. uint32_t fid = context->fImageMap[id];
  22. // if present, return only the in-file id we registered the first time we serialized it.
  23. return SkData::MakeWithCopy(&fid, sizeof(fid));
  24. }
  25. sk_sp<SkImage> SkSharingDeserialContext::deserializeImage(
  26. const void* data, size_t length, void* ctx) {
  27. SkSharingDeserialContext* context = reinterpret_cast<SkSharingDeserialContext*>(ctx);
  28. uint32_t fid;
  29. // If the data is an image fid, look up an already deserialized image from our map
  30. if (length == sizeof(fid)) {
  31. memcpy(&fid, data, sizeof(fid));
  32. if (fid >= context->fImages.size()) {
  33. SkDebugf("We do not have the data for image %d.\n", fid);
  34. return nullptr;
  35. }
  36. return context->fImages[fid];
  37. }
  38. // Otherwise, the data is an image, deserialise it, store it in our map at its fid.
  39. // TODO(nifong): make DeserialProcs accept sk_sp<SkData> so we don't have to copy this.
  40. sk_sp<SkData> dataView = SkData::MakeWithCopy(data, length);
  41. const sk_sp<SkImage> image = SkImage::MakeFromEncoded(std::move(dataView));
  42. context->fImages.push_back(image);
  43. return image;
  44. }