blob: 3729bad1051b6ad518aef157edc43ceb4edabc3f [file] [log] [blame]
mtklein29b1afc2015-04-09 07:46:41 -07001/*
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
mtklein8113dd12014-11-12 15:15:28 -08008#ifndef SkVarAlloc_DEFINED
9#define SkVarAlloc_DEFINED
10
11#include "SkTypes.h"
12
13class SkVarAlloc : SkNoncopyable {
14public:
mtklein59dba142014-12-12 08:41:23 -080015 // Smallest block we'll allocate is 2**N bytes.
16 explicit SkVarAlloc(size_t minLgSize);
mtklein29b1afc2015-04-09 07:46:41 -070017 // Same as above, but first uses up to len bytes from storage.
18 SkVarAlloc(size_t minLgSize, char* storage, size_t len);
19
mtklein8113dd12014-11-12 15:15:28 -080020 ~SkVarAlloc();
21
mtklein5a744b72015-09-14 11:11:17 -070022 // Returns contiguous bytes aligned at least for pointers.
23 char* alloc(size_t bytes) {
mtklein8113dd12014-11-12 15:15:28 -080024 bytes = SkAlignPtr(bytes);
25
mtkleinf2950b12014-11-13 12:41:14 -080026 if (bytes > fRemaining) {
mtklein5a744b72015-09-14 11:11:17 -070027 this->makeSpace(bytes);
mtklein8113dd12014-11-12 15:15:28 -080028 }
mtkleinf2950b12014-11-13 12:41:14 -080029 SkASSERT(bytes <= fRemaining);
mtklein8113dd12014-11-12 15:15:28 -080030
31 char* ptr = fByte;
32 fByte += bytes;
bsalomonccb328d2014-12-11 13:31:06 -080033 fRemaining = SkToU32(fRemaining - bytes);
mtklein8113dd12014-11-12 15:15:28 -080034 return ptr;
35 }
36
mtklein0bd57b22014-11-18 09:32:36 -080037 // Returns our best estimate of the number of bytes we've allocated.
mtklein98b84852015-04-21 15:23:59 -070038 // (We may not track this precisely to save space.)
39 size_t approxBytesAllocated() const { return fBytesAllocated; }
mtklein0bd57b22014-11-18 09:32:36 -080040
mtklein8113dd12014-11-12 15:15:28 -080041private:
mtklein5a744b72015-09-14 11:11:17 -070042 void makeSpace(size_t bytes);
mtklein8113dd12014-11-12 15:15:28 -080043
mtklein98b84852015-04-21 15:23:59 -070044 size_t fBytesAllocated;
45
mtklein8113dd12014-11-12 15:15:28 -080046 char* fByte;
mtkleinf2950b12014-11-13 12:41:14 -080047 unsigned fRemaining;
mtklein59dba142014-12-12 08:41:23 -080048 unsigned fLgSize;
mtklein8113dd12014-11-12 15:15:28 -080049
50 struct Block;
51 Block* fBlock;
52};
bungeman99fe8222015-08-20 07:57:51 -070053static_assert(sizeof(SkVarAlloc) <= 32, "SkVarAllocSize");
mtklein8113dd12014-11-12 15:15:28 -080054
55#endif//SkVarAlloc_DEFINED