1 | // |
2 | // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. |
3 | // Use of this source code is governed by a BSD-style license that can be |
4 | // found in the LICENSE file. |
5 | // |
6 | |
7 | #ifndef COMMON_MEMORYBUFFER_H_ |
8 | #define COMMON_MEMORYBUFFER_H_ |
9 | |
10 | #include "common/Optional.h" |
11 | #include "common/angleutils.h" |
12 | #include "common/debug.h" |
13 | |
14 | #include <stdint.h> |
15 | #include <cstddef> |
16 | |
17 | namespace angle |
18 | { |
19 | |
20 | class MemoryBuffer final : NonCopyable |
21 | { |
22 | public: |
23 | MemoryBuffer() = default; |
24 | MemoryBuffer(size_t size) { resize(size); } |
25 | ~MemoryBuffer(); |
26 | |
27 | MemoryBuffer(MemoryBuffer &&other); |
28 | MemoryBuffer &operator=(MemoryBuffer &&other); |
29 | |
30 | bool resize(size_t size); |
31 | size_t size() const { return mSize; } |
32 | bool empty() const { return mSize == 0; } |
33 | |
34 | const uint8_t *data() const { return mData; } |
35 | uint8_t *data() |
36 | { |
37 | ASSERT(mData); |
38 | return mData; |
39 | } |
40 | |
41 | uint8_t &operator[](size_t pos) |
42 | { |
43 | ASSERT(pos < mSize); |
44 | return mData[pos]; |
45 | } |
46 | const uint8_t &operator[](size_t pos) const |
47 | { |
48 | ASSERT(pos < mSize); |
49 | return mData[pos]; |
50 | } |
51 | |
52 | void fill(uint8_t datum); |
53 | |
54 | private: |
55 | size_t mSize = 0; |
56 | uint8_t *mData = nullptr; |
57 | }; |
58 | |
59 | class ScratchBuffer final : NonCopyable |
60 | { |
61 | public: |
62 | // If we request a scratch buffer requesting a smaller size this many times, release and |
63 | // recreate the scratch buffer. This ensures we don't have a degenerate case where we are stuck |
64 | // hogging memory. |
65 | ScratchBuffer(uint32_t lifetime); |
66 | ~ScratchBuffer(); |
67 | |
68 | // Returns true with a memory buffer of the requested size, or false on failure. |
69 | bool get(size_t requestedSize, MemoryBuffer **memoryBufferOut); |
70 | |
71 | // Same as get, but ensures new values are initialized to a fixed constant. |
72 | bool getInitialized(size_t requestedSize, MemoryBuffer **memoryBufferOut, uint8_t initValue); |
73 | |
74 | // Ticks the release counter for the scratch buffer. Also done implicitly in get(). |
75 | void tick(); |
76 | |
77 | void clear(); |
78 | |
79 | private: |
80 | bool getImpl(size_t requestedSize, MemoryBuffer **memoryBufferOut, Optional<uint8_t> initValue); |
81 | |
82 | const uint32_t mLifetime; |
83 | uint32_t mResetCounter; |
84 | MemoryBuffer mScratchMemory; |
85 | }; |
86 | |
87 | } // namespace angle |
88 | |
89 | #endif // COMMON_MEMORYBUFFER_H_ |
90 | |