1/*
2 * Copyright 2016 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/SkData.h"
9#include "src/core/SkAutoPixmapStorage.h"
10
11SkAutoPixmapStorage::SkAutoPixmapStorage() : fStorage(nullptr) {}
12
13SkAutoPixmapStorage::~SkAutoPixmapStorage() {
14 this->freeStorage();
15}
16
17SkAutoPixmapStorage::SkAutoPixmapStorage(SkAutoPixmapStorage&& other) : fStorage(nullptr) {
18 *this = std::move(other);
19}
20
21SkAutoPixmapStorage& SkAutoPixmapStorage::operator=(SkAutoPixmapStorage&& other) {
22 this->fStorage = other.fStorage;
23 this->INHERITED::reset(other.info(), this->fStorage, other.rowBytes());
24
25 other.fStorage = nullptr;
26 other.INHERITED::reset();
27
28 return *this;
29}
30
31size_t SkAutoPixmapStorage::AllocSize(const SkImageInfo& info, size_t* rowBytes) {
32 size_t rb = info.minRowBytes();
33 if (rowBytes) {
34 *rowBytes = rb;
35 }
36 return info.computeByteSize(rb);
37}
38
39bool SkAutoPixmapStorage::tryAlloc(const SkImageInfo& info) {
40 this->freeStorage();
41
42 size_t rb;
43 size_t size = AllocSize(info, &rb);
44 if (SkImageInfo::ByteSizeOverflowed(size)) {
45 return false;
46 }
47 void* pixels = sk_malloc_canfail(size);
48 if (nullptr == pixels) {
49 return false;
50 }
51 this->reset(info, pixels, rb);
52 fStorage = pixels;
53 return true;
54}
55
56void SkAutoPixmapStorage::alloc(const SkImageInfo& info) {
57 SkASSERT_RELEASE(this->tryAlloc(info));
58}
59
60void* SkAutoPixmapStorage::detachPixels() {
61 if (!fStorage) {
62 return nullptr;
63 }
64
65 void* data = fStorage;
66 fStorage = nullptr;
67 this->INHERITED::reset();
68
69 return data;
70}
71
72sk_sp<SkData> SkAutoPixmapStorage::detachPixelsAsData() {
73 if (!fStorage) {
74 return nullptr;
75 }
76
77 sk_sp<SkData> data = SkData::MakeFromMalloc(fStorage, this->computeByteSize());
78 fStorage = nullptr;
79 this->INHERITED::reset();
80
81 return data;
82}
83