99#include " duckdb/common/enums/order_type.hpp"
1010#include " duckdb/function/aggregate_function.hpp"
1111#include " duckdb/function/create_sort_key.hpp"
12+ #include < new>
1213
1314namespace duckdb {
1415
@@ -180,9 +181,8 @@ class BinaryAggregateHeap {
180181
181182 void Initialize (ArenaAllocator &allocator, const idx_t capacity_p) {
182183 capacity = capacity_p;
183- auto ptr = allocator.AllocateAligned (capacity * sizeof (STORAGE_TYPE));
184- memset (ptr, 0 , capacity * sizeof (STORAGE_TYPE));
185- heap = reinterpret_cast <STORAGE_TYPE *>(ptr);
184+ allocated_capacity = 0 ;
185+ heap = nullptr ;
186186 size = 0 ;
187187 }
188188
@@ -201,6 +201,9 @@ class BinaryAggregateHeap {
201201
202202 // If the heap is not full, insert the value into a new slot
203203 if (size < capacity) {
204+ if (size == allocated_capacity) {
205+ Grow (allocator);
206+ }
204207 heap[size].first .Assign (allocator, key);
205208 heap[size].second .Assign (allocator, value);
206209 size++;
@@ -233,13 +236,33 @@ class BinaryAggregateHeap {
233236 }
234237
235238private:
239+ void Grow (ArenaAllocator &allocator) {
240+ D_ASSERT (allocated_capacity < capacity);
241+ const auto old_allocated_capacity = allocated_capacity;
242+ if (allocated_capacity == 0 ) {
243+ allocated_capacity = 1 ;
244+ } else if (allocated_capacity > capacity / 2 ) {
245+ allocated_capacity = capacity;
246+ } else {
247+ allocated_capacity *= 2 ;
248+ }
249+
250+ const auto old_size = old_allocated_capacity * sizeof (STORAGE_TYPE);
251+ const auto new_size = allocated_capacity * sizeof (STORAGE_TYPE);
252+ auto ptr = heap ? allocator.ReallocateAligned (reinterpret_cast <data_ptr_t >(heap), old_size, new_size)
253+ : allocator.AllocateAligned (new_size);
254+ memset (ptr + old_size, 0 , new_size - old_size);
255+ heap = reinterpret_cast <STORAGE_TYPE *>(ptr);
256+ }
257+
236258 static bool Compare (const STORAGE_TYPE &left, const STORAGE_TYPE &right) {
237259 return K_COMPARATOR::Operation (left.first .value , right.first .value );
238260 }
239261
240- idx_t capacity;
241- STORAGE_TYPE *heap;
242- idx_t size;
262+ idx_t capacity = 0 ;
263+ idx_t allocated_capacity = 0 ;
264+ STORAGE_TYPE *heap = nullptr ;
265+ idx_t size = 0 ;
243266};
244267
245268enum class ArgMinMaxNullHandling { IGNORE_ANY_NULL, HANDLE_ARG_NULL, HANDLE_ANY_NULL };
0 commit comments