1cb93a386Sopenharmony_ci// Copyright 2019 Google LLC.
2cb93a386Sopenharmony_ci// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3cb93a386Sopenharmony_ci#include "tools/fiddle/examples.h"
4cb93a386Sopenharmony_ci// HASH=eb6f861ca1839146d26e40d56c2a001c
5cb93a386Sopenharmony_ciREG_FIDDLE(Bitmap_tryAllocPixels_4, 256, 100, false, 0) {
6cb93a386Sopenharmony_ciclass LargePixelRef : public SkPixelRef {
7cb93a386Sopenharmony_cipublic:
8cb93a386Sopenharmony_ci    LargePixelRef(const SkImageInfo& info, char* storage, size_t rowBytes)
9cb93a386Sopenharmony_ci        : SkPixelRef(info.width(), info.height(), storage, rowBytes) {
10cb93a386Sopenharmony_ci    }
11cb93a386Sopenharmony_ci    ~LargePixelRef() override {
12cb93a386Sopenharmony_ci        delete[] (char* ) this->pixels();
13cb93a386Sopenharmony_ci    }
14cb93a386Sopenharmony_ci};
15cb93a386Sopenharmony_ciclass LargeAllocator : public SkBitmap::Allocator {
16cb93a386Sopenharmony_cipublic:
17cb93a386Sopenharmony_ci    bool allocPixelRef(SkBitmap* bitmap) override {
18cb93a386Sopenharmony_ci        const SkImageInfo& info = bitmap->info();
19cb93a386Sopenharmony_ci        uint64_t rowBytes = info.minRowBytes64();
20cb93a386Sopenharmony_ci        uint64_t size = info.height() * rowBytes;
21cb93a386Sopenharmony_ci        char* addr = new char[size];
22cb93a386Sopenharmony_ci        if (nullptr == addr) {
23cb93a386Sopenharmony_ci            return false;
24cb93a386Sopenharmony_ci        }
25cb93a386Sopenharmony_ci        sk_sp<SkPixelRef> pr = sk_sp<SkPixelRef>(new LargePixelRef(info, addr, rowBytes));
26cb93a386Sopenharmony_ci        if (!pr) {
27cb93a386Sopenharmony_ci            return false;
28cb93a386Sopenharmony_ci        }
29cb93a386Sopenharmony_ci        bitmap->setPixelRef(std::move(pr), 0, 0);
30cb93a386Sopenharmony_ci        return true;
31cb93a386Sopenharmony_ci    }
32cb93a386Sopenharmony_ci};
33cb93a386Sopenharmony_ci
34cb93a386Sopenharmony_civoid draw(SkCanvas* canvas) {
35cb93a386Sopenharmony_ci   LargeAllocator largeAllocator;
36cb93a386Sopenharmony_ci   SkBitmap bitmap;
37cb93a386Sopenharmony_ci   int width = 100; // make this 20000
38cb93a386Sopenharmony_ci   int height = 100; // and this 100000 to allocate 8 gigs on a 64-bit platform
39cb93a386Sopenharmony_ci   bitmap.setInfo(SkImageInfo::MakeN32(width, height, kOpaque_SkAlphaType));
40cb93a386Sopenharmony_ci   if (bitmap.tryAllocPixels(&largeAllocator)) {
41cb93a386Sopenharmony_ci       bitmap.eraseColor(0xff55aa33);
42cb93a386Sopenharmony_ci       canvas->drawImage(bitmap.asImage(), 0, 0);
43cb93a386Sopenharmony_ci   }
44cb93a386Sopenharmony_ci}
45cb93a386Sopenharmony_ci}  // END FIDDLE
46