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();
24     ~MemoryBuffer();
25 
26     MemoryBuffer(MemoryBuffer &&other);
27     MemoryBuffer &operator=(MemoryBuffer &&other);
28 
29     bool resize(size_t size);
size()30     size_t size() const { return mSize; }
empty()31     bool empty() const { return mSize == 0; }
32 
data()33     const uint8_t *data() const { return mData; }
data()34     uint8_t *data()
35     {
36         ASSERT(mData);
37         return mData;
38     }
39 
40     void fill(uint8_t datum);
41 
42   private:
43     size_t mSize;
44     uint8_t *mData;
45 };
46 
47 class ScratchBuffer final : NonCopyable
48 {
49   public:
50     // If we request a scratch buffer requesting a smaller size this many times, release and
51     // recreate the scratch buffer. This ensures we don't have a degenerate case where we are stuck
52     // hogging memory.
53     ScratchBuffer(uint32_t lifetime);
54     ~ScratchBuffer();
55 
56     // Returns true with a memory buffer of the requested size, or false on failure.
57     bool get(size_t requestedSize, MemoryBuffer **memoryBufferOut);
58 
59     // Same as get, but ensures new values are initialized to a fixed constant.
60     bool getInitialized(size_t requestedSize, MemoryBuffer **memoryBufferOut, uint8_t initValue);
61 
62     // Ticks the release counter for the scratch buffer. Also done implicitly in get().
63     void tick();
64 
65     void clear();
66 
67   private:
68     bool getImpl(size_t requestedSize, MemoryBuffer **memoryBufferOut, Optional<uint8_t> initValue);
69 
70     const uint32_t mLifetime;
71     uint32_t mResetCounter;
72     MemoryBuffer mScratchMemory;
73 };
74 
75 }  // namespace angle
76 
77 #endif  // COMMON_MEMORYBUFFER_H_
78