• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /*
3  * Copyright 2006 The Android Open Source Project
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  */
8 
9 
10 #ifndef SkChunkAlloc_DEFINED
11 #define SkChunkAlloc_DEFINED
12 
13 #include "SkTypes.h"
14 
15 class SkChunkAlloc : SkNoncopyable {
16 public:
17     SkChunkAlloc(size_t minSize);
18     ~SkChunkAlloc();
19 
20     /**
21      *  Free up all allocated blocks. This invalidates all returned
22      *  pointers.
23      */
24     void reset();
25     /**
26      *  Reset to 0 used bytes preserving as much memory as possible.
27      *  This invalidates all returned pointers.
28      */
29     void rewind();
30 
31     enum AllocFailType {
32         kReturnNil_AllocFailType,
33         kThrow_AllocFailType
34     };
35 
36     void* alloc(size_t bytes, AllocFailType);
allocThrow(size_t bytes)37     void* allocThrow(size_t bytes) {
38         return this->alloc(bytes, kThrow_AllocFailType);
39     }
40 
41     /** Call this to unalloc the most-recently allocated ptr by alloc(). On
42         success, the number of bytes freed is returned, or 0 if the block could
43         not be unallocated. This is a hint to the underlying allocator that
44         the previous allocation may be reused, but the implementation is free
45         to ignore this call (and return 0).
46      */
47     size_t unalloc(void* ptr);
48 
totalCapacity()49     size_t totalCapacity() const { return fTotalCapacity; }
totalUsed()50     size_t totalUsed() const { return fTotalUsed; }
51     SkDEBUGCODE(int blockCount() const { return fBlockCount; })
52     SkDEBUGCODE(size_t totalLost() const { return fTotalLost; })
53 
54     /**
55      *  Returns true if the specified address is within one of the chunks, and
56      *  has at least 1-byte following the address (i.e. if addr points to the
57      *  end of a chunk, then contains() will return false).
58      */
59     bool contains(const void* addr) const;
60 
61 private:
62     struct Block;
63 
64     Block*  fBlock;
65     size_t  fMinSize;
66     size_t  fChunkSize;
67     size_t  fTotalCapacity;
68     size_t  fTotalUsed;     // will be <= fTotalCapacity
69     SkDEBUGCODE(int     fBlockCount;)
70     SkDEBUGCODE(size_t  fTotalLost;)     // will be <= fTotalCapacity
71 
72     Block* newBlock(size_t bytes, AllocFailType ftype);
73     Block* addBlockIfNecessary(size_t bytes, AllocFailType ftype);
74 
75     SkDEBUGCODE(void validate();)
76 };
77 
78 #endif
79