1 /*
2 * Copyright 2015 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 "SkVarAlloc.h"
9
10 struct SkVarAlloc::Block {
11 Block* prev;
dataSkVarAlloc::Block12 char* data() { return (char*)(this + 1); }
13
AllocSkVarAlloc::Block14 static Block* Alloc(Block* prev, size_t size) {
15 SkASSERT(size >= sizeof(Block));
16 Block* b = (Block*)sk_malloc_throw(size);
17 b->prev = prev;
18 return b;
19 }
20 };
21
SkVarAlloc(size_t minLgSize)22 SkVarAlloc::SkVarAlloc(size_t minLgSize)
23 : fBytesAllocated(0)
24 , fByte(nullptr)
25 , fRemaining(0)
26 , fLgSize(minLgSize)
27 , fBlock(nullptr) {}
28
SkVarAlloc(size_t minLgSize,char * storage,size_t len)29 SkVarAlloc::SkVarAlloc(size_t minLgSize, char* storage, size_t len)
30 : fBytesAllocated(0)
31 , fByte(storage)
32 , fRemaining(len)
33 , fLgSize(minLgSize)
34 , fBlock(nullptr) {}
35
~SkVarAlloc()36 SkVarAlloc::~SkVarAlloc() {
37 Block* b = fBlock;
38 while (b) {
39 Block* prev = b->prev;
40 sk_free(b);
41 b = prev;
42 }
43 }
44
makeSpace(size_t bytes)45 void SkVarAlloc::makeSpace(size_t bytes) {
46 SkASSERT(SkIsAlignPtr(bytes));
47
48 size_t alloc = 1<<fLgSize++;
49 while (alloc < bytes + sizeof(Block)) {
50 alloc *= 2;
51 }
52 fBytesAllocated += alloc;
53 fBlock = Block::Alloc(fBlock, alloc);
54 fByte = fBlock->data();
55 fRemaining = alloc - sizeof(Block);
56 }
57