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