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/SkMallocPixelRef.h"
9
10#include "include/core/SkData.h"
11#include "include/core/SkImageInfo.h"
12#include "include/private/SkMalloc.h"
13
14static bool is_valid(const SkImageInfo& info) {
15 if (info.width() < 0 || info.height() < 0 ||
16 (unsigned)info.colorType() > (unsigned)kLastEnum_SkColorType ||
17 (unsigned)info.alphaType() > (unsigned)kLastEnum_SkAlphaType)
18 {
19 return false;
20 }
21 return true;
22}
23
24sk_sp<SkPixelRef> SkMallocPixelRef::MakeAllocate(const SkImageInfo& info, size_t rowBytes) {
25 if (rowBytes == 0) {
26 rowBytes = info.minRowBytes();
27 // rowBytes can still be zero, if it overflowed (width * bytesPerPixel > size_t)
28 // or if colortype is unknown
29 }
30 if (!is_valid(info) || !info.validRowBytes(rowBytes)) {
31 return nullptr;
32 }
33 size_t size = 0;
34 if (!info.isEmpty() && rowBytes) {
35 size = info.computeByteSize(rowBytes);
36 if (SkImageInfo::ByteSizeOverflowed(size)) {
37 return nullptr;
38 }
39 }
40 void* addr = sk_calloc_canfail(size);
41 if (nullptr == addr) {
42 return nullptr;
43 }
44
45 struct PixelRef final : public SkPixelRef {
46 PixelRef(int w, int h, void* s, size_t r) : SkPixelRef(w, h, s, r) {}
47 ~PixelRef() override { sk_free(this->pixels()); }
48 };
49 return sk_sp<SkPixelRef>(new PixelRef(info.width(), info.height(), addr, rowBytes));
50}
51
52sk_sp<SkPixelRef> SkMallocPixelRef::MakeWithData(const SkImageInfo& info,
53 size_t rowBytes,
54 sk_sp<SkData> data) {
55 SkASSERT(data != nullptr);
56 if (!is_valid(info)) {
57 return nullptr;
58 }
59 // TODO: what should we return if computeByteSize returns 0?
60 // - the info was empty?
61 // - we overflowed computing the size?
62 if ((rowBytes < info.minRowBytes()) || (data->size() < info.computeByteSize(rowBytes))) {
63 return nullptr;
64 }
65 struct PixelRef final : public SkPixelRef {
66 sk_sp<SkData> fData;
67 PixelRef(int w, int h, void* s, size_t r, sk_sp<SkData> d)
68 : SkPixelRef(w, h, s, r), fData(std::move(d)) {}
69 };
70 void* pixels = const_cast<void*>(data->data());
71 sk_sp<SkPixelRef> pr(new PixelRef(info.width(), info.height(), pixels, rowBytes,
72 std::move(data)));
73 pr->setImmutable(); // since we were created with (immutable) data
74 return pr;
75}
76