GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
LinearBuffer.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_DATA_LINEAR_BUFFER_HPP
5#define GREM_CORE_DATA_LINEAR_BUFFER_HPP
6
8
11
12#include <algorithm> // std::max
13#include <cstddef> // std::size_t, std::ptrdiff_t, std::byte
14#include <cstdint> // std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t
15#include <cstring> // std::memcpy
16#include <functional> // std::invoke
17#include <memory> // std::align
18#include <memory_resource> // std::pmr::memory_resource
19#include <new> // std::launder
20#include <type_traits> // std::is_..._v, std::remove_..._t, std::false_type, std::true_type, std::integral_constant, std::common_type_t
21#include <utility> // std::forward, std::declval, std::...index_sequence, std::in_place_index...
22
23namespace grem {
24
25template <typename... Ts>
26class LinearBuffer;
27
28namespace detail {
29
30template <typename T, std::size_t Index, typename... Ts>
31struct LinearBufferIndexImpl;
32
33template <typename T, std::size_t Index, typename First, typename... Rest>
34struct LinearBufferIndexImpl<T, Index, First, Rest...> : LinearBufferIndexImpl<T, Index + 1, Rest...> {};
35
36template <typename T, std::size_t Index, typename... Rest>
37struct LinearBufferIndexImpl<T, Index, T, Rest...> : std::integral_constant<std::size_t, Index> {};
38
39template <typename T>
40struct LinearBufferMinElementSize : std::integral_constant<std::size_t, sizeof(T)> {};
41
42template <typename T>
43struct LinearBufferMinElementSize<T[]> : std::integral_constant<std::size_t, sizeof(std::size_t)> {};
44
45template <typename T>
46struct LinearBufferVisitorParameterType {
47 using type = const T;
48};
49
50template <typename T>
51struct LinearBufferVisitorParameterType<T[]> {
52 using type = Span<const T>;
53};
54
55} // namespace detail
56
58template <typename T, typename B>
59struct linear_buffer_has_alternative;
60
61template <typename T, typename First, typename... Rest>
62struct linear_buffer_has_alternative<T, LinearBuffer<First, Rest...>> : linear_buffer_has_alternative<T, LinearBuffer<Rest...>> {};
63
64template <typename T>
65struct linear_buffer_has_alternative<T, LinearBuffer<>> : std::false_type {};
66
67template <typename T, typename... Rest>
68struct linear_buffer_has_alternative<T, LinearBuffer<T, Rest...>> : std::true_type {};
70
71template <typename T, typename B>
72inline constexpr bool linear_buffer_has_alternative_v = linear_buffer_has_alternative<T, B>::value;
73
75template <typename T, typename B>
76struct linear_buffer_index;
77
78template <typename T, typename... Ts>
79struct linear_buffer_index<T, LinearBuffer<Ts...>> : detail::LinearBufferIndexImpl<T, 0, Ts...> {};
81
82template <typename T, typename B>
83inline constexpr std::size_t linear_buffer_index_v = linear_buffer_index<T, B>::value;
84
86template <std::size_t Index, typename B>
87struct linear_buffer_alternative;
88
89template <std::size_t Index, typename First, typename... Rest>
90struct linear_buffer_alternative<Index, LinearBuffer<First, Rest...>> : linear_buffer_alternative<Index - 1, LinearBuffer<Rest...>> {};
91
92template <typename T, typename... Rest>
93struct linear_buffer_alternative<0, LinearBuffer<T, Rest...>> {
94 using type = T;
95};
97
98template <std::size_t Index, typename B>
99using linear_buffer_alternative_t = typename linear_buffer_alternative<Index, B>::type;
100
102template <typename B>
103struct linear_buffer_size;
104
105template <typename... Ts>
106struct linear_buffer_size<LinearBuffer<Ts...>> : std::integral_constant<std::size_t, sizeof...(Ts)> {};
108
109template <typename B>
110inline constexpr std::size_t linear_buffer_size_v = linear_buffer_size<B>::value;
111
112template <typename... Ts>
114public:
115 static_assert((std::is_trivially_copyable_v<std::remove_extent_t<Ts>> && ...), "LinearBuffer requires all element types to be trivially copyable.");
116
117 // clang-format off
119 std::conditional_t<sizeof...(Ts) < 255ull, std::uint8_t,
120 std::conditional_t<sizeof...(Ts) < 65535ull, std::uint16_t,
121 std::conditional_t<sizeof...(Ts) < 4294967295ull, std::uint32_t,
122 std::uint64_t>>>;
123 // clang-format on
124
125 static constexpr index_type npos = sizeof...(Ts);
126
127 explicit LinearBuffer(std::pmr::memory_resource* memoryResource, std::size_t nextChunkSize = 64) noexcept
128 : memoryResource(memoryResource)
129 , nextChunkSize(std::max(nextChunkSize, MIN_CHUNK_SIZE)) {
130 GREM_ASSERT(memoryResource);
131 }
132
133 ~LinearBuffer() = default;
134
135 LinearBuffer(const LinearBuffer&) = delete;
139
140 template <typename T>
141 void push_back(const T& value) requires(!std::is_unbounded_array_v<T> && linear_buffer_has_alternative_v<T, LinearBuffer>) {
142 constexpr std::size_t REQUIRED_SIZE = sizeof(TypeHeader) + sizeof(T) + sizeof(TypeHeader) + sizeof(ChunkTrailer);
143 const std::size_t remainingMemorySize = static_cast<std::size_t>(remainingMemoryEnd - remainingMemoryBegin);
144 if (remainingMemorySize < REQUIRED_SIZE) {
145 [[unlikely]];
146 const std::size_t newChunkSize = std::max(REQUIRED_SIZE, nextChunkSize);
147 if (firstChunkBegin) {
148 GREM_ASSERT(remainingMemorySize >= sizeof(TypeHeader) + sizeof(ChunkTrailer));
149 std::byte* const oldChunkTrailer = remainingMemoryBegin;
150 std::byte* const newChunkBegin = allocateChunk(newChunkSize);
151 std::byte* const newChunkEnd = newChunkBegin + newChunkSize;
152 const TypeHeader typeHeader{.typeIndex = npos};
153 std::memcpy(oldChunkTrailer, &typeHeader, sizeof(TypeHeader));
154 const ChunkTrailer chunkTrailer{.nextChunkBegin = newChunkBegin, .nextChunkEnd = newChunkEnd};
155 std::memcpy(oldChunkTrailer + sizeof(TypeHeader), &chunkTrailer, sizeof(ChunkTrailer));
156 } else {
157 firstChunkBegin = allocateChunk(newChunkSize);
158 firstChunkEnd = firstChunkBegin + newChunkSize;
159 }
160 }
161 const TypeHeader typeHeader{.typeIndex = linear_buffer_index_v<T, LinearBuffer>};
162 std::memcpy(remainingMemoryBegin, &typeHeader, sizeof(TypeHeader));
163 std::memcpy(remainingMemoryBegin + sizeof(TypeHeader), &value, sizeof(T));
164 remainingMemoryBegin += sizeof(TypeHeader) + sizeof(T);
165 }
166
167 template <typename T, typename... Args>
168 void emplace_back(Args&&... args) requires(!std::is_unbounded_array_v<T> && linear_buffer_has_alternative_v<T, LinearBuffer> && std::is_constructible_v<T, Args...>) {
169 return push_back<T>(T{std::forward<Args>(args)...});
170 }
171
172 template <typename T>
174 constexpr std::size_t MIN_REQUIRED_SIZE = sizeof(TypeHeader) + sizeof(ArrayHeader) + sizeof(TypeHeader) + sizeof(ChunkTrailer);
175 const std::size_t remainingMemorySize = static_cast<std::size_t>(remainingMemoryEnd - remainingMemoryBegin);
176 if (remainingMemorySize < MIN_REQUIRED_SIZE ||
177 (!values.empty() &&
178 !getAligned(alignof(T), values.size_bytes(), remainingMemoryBegin + sizeof(TypeHeader) + sizeof(ArrayHeader), remainingMemorySize - MIN_REQUIRED_SIZE))) {
179 [[unlikely]];
180 const std::size_t requiredSize = sizeof(TypeHeader) + sizeof(ArrayHeader) + alignof(T) - 1 + values.size_bytes() + sizeof(TypeHeader) + sizeof(ChunkTrailer);
181 const std::size_t newChunkSize = std::max(requiredSize, nextChunkSize);
182 if (firstChunkBegin) {
183 GREM_ASSERT(remainingMemorySize >= sizeof(TypeHeader) + sizeof(ChunkTrailer));
184 std::byte* const oldChunkTrailer = remainingMemoryBegin;
185 std::byte* const newChunkBegin = allocateChunk(newChunkSize);
186 std::byte* const newChunkEnd = newChunkBegin + newChunkSize;
187 const TypeHeader typeHeader{.typeIndex = npos};
188 std::memcpy(oldChunkTrailer, &typeHeader, sizeof(TypeHeader));
189 const ChunkTrailer chunkTrailer{.nextChunkBegin = newChunkBegin, .nextChunkEnd = newChunkEnd};
190 std::memcpy(oldChunkTrailer + sizeof(TypeHeader), &chunkTrailer, sizeof(ChunkTrailer));
191 } else {
192 firstChunkBegin = allocateChunk(newChunkSize);
193 firstChunkEnd = firstChunkBegin + newChunkSize;
194 }
195 }
196 const TypeHeader typeHeader{.typeIndex = linear_buffer_index_v<T[], LinearBuffer>};
197 std::memcpy(remainingMemoryBegin, &typeHeader, sizeof(TypeHeader));
198 const ArrayHeader arrayHeader{.elementCount = values.size()};
199 std::memcpy(remainingMemoryBegin + sizeof(TypeHeader), &arrayHeader, sizeof(ArrayHeader));
200 Span<const T> result{};
201 if (values.empty()) {
202 remainingMemoryBegin = remainingMemoryBegin + sizeof(TypeHeader) + sizeof(ArrayHeader);
203 } else {
204 void* const alignedPointer = getAligned(alignof(T), values.size_bytes(), remainingMemoryBegin + sizeof(TypeHeader) + sizeof(ArrayHeader),
205 static_cast<std::size_t>(remainingMemoryEnd - remainingMemoryBegin) - MIN_REQUIRED_SIZE);
206 GREM_ASSERT(alignedPointer);
207 std::memcpy(alignedPointer, values.data(), values.size_bytes());
208 result = Span<const T>{std::launder(reinterpret_cast<const T*>(static_cast<std::byte*>(alignedPointer))), values.size()};
209 remainingMemoryBegin = static_cast<std::byte*>(alignedPointer) + values.size_bytes();
210 }
211 return result;
212 }
213
214 template <typename T>
216 return append(Span<const T>{values});
217 }
218
219 template <typename Visitor>
220 auto visit(Visitor&& visitor) const { // NOLINT(cppcoreguidelines-missing-std-forward)
221 using R = std::common_type_t<decltype(std::invoke(std::forward<Visitor>(visitor), std::declval<typename detail::LinearBufferVisitorParameterType<Ts>::type>()))...>;
222 const std::byte* const end = remainingMemoryBegin;
223 const std::byte* chunkEnd = firstChunkEnd;
224 for (const std::byte* pointer = firstChunkBegin; pointer != end;) {
225 GREM_ASSERT(static_cast<std::size_t>(chunkEnd - pointer) >= sizeof(TypeHeader));
226 TypeHeader typeHeader{};
227 std::memcpy(&typeHeader, pointer, sizeof(TypeHeader));
228 pointer += sizeof(TypeHeader);
229 const auto apply = [&]<std::size_t Index>(std::in_place_index_t<Index>) -> void {
231 if constexpr (std::is_unbounded_array_v<MaybeArrayT>) {
232 using T = std::remove_extent_t<MaybeArrayT>;
233 GREM_ASSERT(static_cast<std::size_t>(chunkEnd - pointer) >= sizeof(ArrayHeader));
234 ArrayHeader arrayHeader{};
235 std::memcpy(&arrayHeader, pointer, sizeof(ArrayHeader));
236 pointer += sizeof(ArrayHeader);
237 GREM_ASSERT(static_cast<std::size_t>(chunkEnd - pointer) >= arrayHeader.elementCount * sizeof(T));
238 Span<const T> values{};
239 if (arrayHeader.elementCount > 0) {
240 if constexpr (alignof(T) > 1) {
241 void* const aligned = getAligned(alignof(T), arrayHeader.elementCount * sizeof(T), const_cast<void*>(static_cast<const void*>(pointer)),
242 static_cast<std::size_t>(chunkEnd - pointer) - (sizeof(TypeHeader) + sizeof(ChunkTrailer)));
243 GREM_ASSERT(aligned);
244 pointer = static_cast<const std::byte*>(aligned);
245 }
246 values = Span{std::launder(reinterpret_cast<const T*>(pointer)), arrayHeader.elementCount};
247 }
248 if constexpr (std::is_void_v<R>) {
249 std::invoke(std::forward<Visitor>(visitor), values);
250 pointer += arrayHeader.elementCount * sizeof(T);
251 } else {
252 if (std::invoke(std::forward<Visitor>(visitor), values)) {
253 pointer += arrayHeader.elementCount * sizeof(T);
254 } else {
255 pointer = end;
256 }
257 }
258 } else {
259 using T = MaybeArrayT;
260 GREM_ASSERT(static_cast<std::size_t>(chunkEnd - pointer) >= sizeof(T));
261 alignas(T) std::byte storage[sizeof(T)];
262 std::memcpy(storage, pointer, sizeof(T));
263 const T& value = *std::launder(reinterpret_cast<const T*>(storage));
264 if constexpr (std::is_void_v<R>) {
265 std::invoke(std::forward<Visitor>(visitor), value);
266 pointer += sizeof(T);
267 } else {
268 if (std::invoke(std::forward<Visitor>(visitor), value)) {
269 pointer += sizeof(T);
270 } else {
271 pointer = end;
272 }
273 }
274 }
275 };
276 [&]<std::size_t... Indices>(std::index_sequence<Indices...>) -> void {
277 if (!(((typeHeader.typeIndex == Indices) ? (apply(std::in_place_index<Indices>), true) : false) || ...)) {
278 [[unlikely]];
279 GREM_ASSERT(typeHeader.typeIndex == npos);
280 GREM_ASSERT(static_cast<std::size_t>(chunkEnd - pointer) >= sizeof(ChunkTrailer));
281 ChunkTrailer chunkTrailer{};
282 std::memcpy(&chunkTrailer, pointer, sizeof(ChunkTrailer));
283 GREM_ASSERT(chunkTrailer.nextChunkBegin);
284 GREM_ASSERT(chunkTrailer.nextChunkEnd);
285 GREM_ASSERT(chunkTrailer.nextChunkEnd - chunkTrailer.nextChunkBegin >= std::ptrdiff_t{MIN_CHUNK_SIZE});
286 pointer = chunkTrailer.nextChunkBegin;
287 chunkEnd = chunkTrailer.nextChunkEnd;
288 }
289 }(std::make_index_sequence<sizeof...(Ts)>{});
290 }
291 if constexpr (!std::is_void_v<R>) {
292 return true;
293 }
294 }
295
296private:
297 struct TypeHeader {
298 index_type typeIndex;
299 };
300
301 struct ArrayHeader {
302 std::size_t elementCount;
303 };
304
305 struct ChunkTrailer {
306 std::byte* nextChunkBegin;
307 std::byte* nextChunkEnd;
308 };
309
310 static constexpr std::size_t MIN_CHUNK_SIZE = std::max({(sizeof(TypeHeader) + detail::LinearBufferMinElementSize<Ts>::value + sizeof(TypeHeader) + sizeof(ChunkTrailer))...});
311
312 [[nodiscard]] static void* getAligned(std::size_t alignment, std::size_t size, void* pointer, std::size_t space) {
313 return std::align(alignment, size, pointer, space);
314 }
315
316 [[nodiscard]] std::byte* allocateChunk(std::size_t newChunkSize) {
317 GREM_ASSERT(memoryResource);
318 std::byte* const newChunk = static_cast<std::byte*>(memoryResource->allocate(newChunkSize, 1));
319 remainingMemoryBegin = newChunk;
320 remainingMemoryEnd = newChunk + newChunkSize;
321 nextChunkSize += nextChunkSize / 2;
322 return newChunk;
323 }
324
325 std::pmr::memory_resource* memoryResource;
326 std::byte* firstChunkBegin = nullptr;
327 std::byte* firstChunkEnd = nullptr;
328 std::byte* remainingMemoryBegin = nullptr;
329 std::byte* remainingMemoryEnd = nullptr;
330 std::size_t nextChunkSize;
331};
332
333} // namespace grem
334
335#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition LinearBuffer.hpp:113
LinearBuffer(std::pmr::memory_resource *memoryResource, std::size_t nextChunkSize=64) noexcept
Definition LinearBuffer.hpp:127
void emplace_back(Args &&... args)
Definition LinearBuffer.hpp:168
void push_back(const T &value)
Definition LinearBuffer.hpp:141
LinearBuffer(LinearBuffer &&)=delete
Span< const T > append(Span< const T > values)
Definition LinearBuffer.hpp:173
~LinearBuffer()=default
Span< const T > append(Span< T > values)
Definition LinearBuffer.hpp:215
LinearBuffer & operator=(LinearBuffer &&)=delete
std::conditional_t< sizeof...(Ts)< 255ull, std::uint8_t, std::conditional_t< sizeof...(Ts)< 65535ull, std::uint16_t, std::conditional_t< sizeof...(Ts)< 4294967295ull, std::uint32_t, std::uint64_t > > > index_type
Definition LinearBuffer.hpp:118
LinearBuffer(const LinearBuffer &)=delete
static constexpr index_type npos
Definition LinearBuffer.hpp:125
LinearBuffer & operator=(const LinearBuffer &)=delete
auto visit(Visitor &&visitor) const
Definition LinearBuffer.hpp:220
Definition Span.hpp:146
constexpr size_type size_bytes() const noexcept
Definition Span.hpp:253
Definition concepts.hpp:106
@ T
't'
Definition keyboard.hpp:90
Definition aliases.hpp:9
constexpr bool linear_buffer_has_alternative_v
Definition LinearBuffer.hpp:72
constexpr std::size_t linear_buffer_index_v
Definition LinearBuffer.hpp:83
typename linear_buffer_alternative< Index, B >::type linear_buffer_alternative_t
Definition LinearBuffer.hpp:99
GREM_ALWAYS_INLINE constexpr decltype(auto) max(A &&a, B &&b)
Get the greater of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:598
constexpr std::size_t linear_buffer_size_v
Definition LinearBuffer.hpp:110
constexpr decltype(auto) apply(Function &&function, Tuple< Ts... > &tuple)
Definition Tuple.hpp:535