16 BEGIN_NAMESPACE_MEMORY
21 static_assert(std::is_trivially_copyable_v<T>,
"Only trivially copyable types are supported in direct array source buffer.");
25 using BufferIndex = std::size_t;
35 setCapacity(aCapacity);
47 void setCapacity(
const std::size_t aCapacity)
51 buffer = std::vector<T>(aCapacity);
54 std::size_t getCapacity()
const 59 std::size_t getSize()
const 61 const BufferIndex cachedWriteIndex = writeIndex;
62 if (readIndex <= cachedWriteIndex)
63 return cachedWriteIndex - readIndex;
65 return (buffer.size() - readIndex) + cachedWriteIndex;
68 BufferIndex getIndex()
const 73 size_t writeSamples(T* source, std::size_t size)
75 if (size > buffer.size())
77 throw "Buffer size exceeded";
79 size_t totalSizeWritten = size;
81 if (writeIndex + size > buffer.size())
83 std::size_t sizeUntilFullCapacity = buffer.size() - writeIndex;
84 writeSamples(source, sizeUntilFullCapacity);
85 size -= sizeUntilFullCapacity;
86 source += sizeUntilFullCapacity;
89 std::memcpy(&buffer.data()[writeIndex], source, size *
sizeof(T));
92 BufferIndex newWriteIndex = writeIndex + size;
93 if (newWriteIndex >= buffer.size())
94 newWriteIndex -= buffer.size();
95 writeIndex = newWriteIndex;
97 return totalSizeWritten;
100 size_t readSamples(T* destination,
size_t count)
102 count = std::min(count, getSize());
103 std::size_t readCapacity = 0;
104 if (readIndex + count > buffer.size())
106 readCapacity = buffer.size() - readIndex;
107 std::memcpy(destination, &buffer.data()[readIndex], readCapacity *
sizeof(T));
109 destination += readCapacity;
110 count -= readCapacity;
112 std::memcpy(destination, &buffer.data()[readIndex], count *
sizeof(T));
114 return count + readCapacity;
118 std::vector<T> buffer;
119 BufferIndex readIndex{};
120 std::atomic<BufferIndex> writeIndex{};
Definition: nonblockingfifobuffer.h:19