| 1 |
#ifndef _BRIAN_DYNAMIC_ARRAY_H |
| 2 |
#define _BRIAN_DYNAMIC_ARRAY_H |
| 3 |
|
| 4 |
#include <cstddef> |
| 5 |
#include <type_traits> |
| 6 |
#include <vector> |
| 7 |
#include <algorithm> |
| 8 |
#include <cstring> |
| 9 |
#include <cassert> |
| 10 |
|
| 11 |
// NOTE : using std::vector<bool> is bit-packed and doesn’t support .data(), unlike other std::vector<T>. |
| 12 |
|
| 13 |
/** |
| 14 |
* A simple 1D dynamic array that grows efficiently over time. |
| 15 |
* |
| 16 |
* This class is designed to mimic the behavior of C-style contiguous memory, |
| 17 |
* making it suitable for interop with tools like Cython and NumPy. |
| 18 |
* |
| 19 |
* Internally, it keeps track of: |
| 20 |
* - `m_size`: the number of elements the user is actively working with. |
| 21 |
* - `m_data.capacity()`: the total number of elements currently allocated. |
| 22 |
* |
| 23 |
* When growing, it over-allocates using a growth factor to avoid frequent |
| 24 |
* memory reallocations — giving us amortized O(1) behavior for appending elements. |
| 25 |
* |
| 26 |
* When shrinking, it simply zeroes out the unused portion instead of |
| 27 |
* releasing memory immediately. To actually free that extra memory, |
| 28 |
* call `shrink_to_fit()`. |
| 29 |
*/ |
| 30 |
template <class T> |
| 31 |
class DynamicArray1D |
| 32 |
{ |
| 33 |
private: |
| 34 |
std::vector<T> m_data; |
| 35 |
size_t m_size; // Logical size (what user sees) |
| 36 |
double m_growth_factor; |
| 37 |
|
| 38 |
public: |
| 39 |
/** |
| 40 |
* |
| 41 |
* We call m_data.resize(initial_size) to ensure that operator[] is safe up to |
| 42 |
* initial_size-1 immediately after construction. This also sets capacity() to |
| 43 |
* at least initial_size. |
| 44 |
*/ |
| 45 |
DynamicArray1D(size_t initial_size = 0, double factor = 2.0) |
| 46 |
: m_size(initial_size), m_growth_factor(factor) |
| 47 |
{ |
| 48 |
m_data.resize(initial_size,T(0)); |
| 49 |
} |
| 50 |
|
| 51 |
~DynamicArray1D(){}; |
| 52 |
|
| 53 |
/** |
| 54 |
* @brief Resizes the array to a new logical size. |
| 55 |
* |
| 56 |
* If the new size is larger than the current capacity, we grow the buffer. |
| 57 |
* To avoid frequent reallocations, we over-allocate using a growth factor— |
| 58 |
* that means the actual buffer might grow more than you asked for. |
| 59 |
* This helps keep future resizes fast (amortized O(1) behavior). |
| 60 |
* |
| 61 |
* If the new size is smaller than the current logical size, we don't shrink |
| 62 |
* the buffer immediately. Instead, we zero out the unused part to avoid |
| 63 |
* keeping stale data around. If you really want to release unused memory, |
| 64 |
* call `shrink_to_fit()` separately. |
| 65 |
*/ |
| 66 |
void resize(size_t new_size) |
| 67 |
{ |
| 68 |
if (new_size > m_data.size()) |
| 69 |
{ |
| 70 |
// Growing: allocate more than strictly needed to reduce future allocations |
| 71 |
size_t grown = static_cast<size_t>(m_data.size() * m_growth_factor) + 1; |
| 72 |
size_t new_capacity = std::max(new_size, grown); |
| 73 |
m_data.resize(new_capacity,T(0)); |
| 74 |
} |
| 75 |
else if (new_size < m_size) |
| 76 |
{ |
| 77 |
// Shrinking: zero out "deleted" entries for safety |
| 78 |
std::fill(m_data.begin() + new_size, |
| 79 |
m_data.begin() + m_size, |
| 80 |
T(0)); |
| 81 |
} |
| 82 |
m_size = new_size; |
| 83 |
} |
| 84 |
|
| 85 |
/** |
| 86 |
* Shrink array to exact new size as mentioned , freezing unused memory |
| 87 |
* @param new_size Must be <= current logical size |
| 88 |
* |
| 89 |
* Unlike resize(), this immediately frees unused memory by creating |
| 90 |
* a new buffer of exactly new_size . |
| 91 |
* Note: Use it with precaution as it defeats the purpose of amortized growth optimisation |
| 92 |
*/ |
| 93 |
void shrink(size_t new_size) |
| 94 |
{ |
| 95 |
if(new_size > m_size){ |
| 96 |
// Don't allow growing via shrink method |
| 97 |
return; |
| 98 |
} |
| 99 |
if(new_size < m_size){ |
| 100 |
std::vector<T> new_buffer(new_size); // We create a new buffer of exact size |
| 101 |
if (std::is_trivially_copyable<T>::value && new_size > 0) |
| 102 |
{ |
| 103 |
std::memcpy(new_buffer.data(), m_data.data(), new_size* sizeof(T)); |
| 104 |
}else |
| 105 |
{ |
| 106 |
for ( size_t i =0; i < new_size; ++i) |
| 107 |
{ |
| 108 |
new_buffer[i] = m_data[i]; |
| 109 |
} |
| 110 |
} |
| 111 |
m_data.swap(new_buffer); |
| 112 |
m_size = new_size; |
| 113 |
} |
| 114 |
// If new_size == m_size, we still shrink the buffer to fit |
| 115 |
else{ |
| 116 |
shrink_to_fit(); |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
/** |
| 121 |
* Shrink capacity to match current size |
| 122 |
* Use with precaution as it defeats the purpose of amortized growth |
| 123 |
*/ |
| 124 |
void shrink_to_fit() |
| 125 |
{ |
| 126 |
m_data.resize(m_size); |
| 127 |
m_data.shrink_to_fit(); |
| 128 |
} |
| 129 |
size_t size() const { return m_size; } |
| 130 |
size_t capacity() const { return m_data.size(); } |
| 131 |
|
| 132 |
/** |
| 133 |
* @brief Direct access to the underlying data pointer. |
| 134 |
* @return Pointer to the first element (may be null if capacity()==0). |
| 135 |
* |
| 136 |
* This be used by us for using the dynamic array with numpy |
| 137 |
*/ |
| 138 |
T *get_data_ptr() { return m_data.data(); } |
| 139 |
const T *get_data_ptr() const { return m_data.data(); } |
| 140 |
|
| 141 |
T &operator[](size_t idx) { return m_data[idx]; } |
| 142 |
const T &operator[](size_t idx) const { return m_data[idx]; } |
| 143 |
}; |
| 144 |
|
| 145 |
/** |
| 146 |
* @brief A two-dimensional dynamic array backed by a flat, row-major buffer. |
| 147 |
* |
| 148 |
* Stores data in a single contiguous std::vector<T> to match C-style and NumPy |
| 149 |
* memory layout, enabling zero-copy interop (e.g., via Cython). |
| 150 |
* Supports amortized , O(1) growth in both dimensions and efficient shrinking. |
| 151 |
*/ |
| 152 |
template <class T> |
| 153 |
class DynamicArray2D |
| 154 |
{ |
| 155 |
private: |
| 156 |
std::vector<T> m_buffer; // Underlying flat buffer (capacity = allocated slots) |
| 157 |
size_t m_rows; // Logical number of rows exposed to the user |
| 158 |
size_t m_cols; // Logical number of columns exposed to the user |
| 159 |
size_t m_buffer_rows; // Physical buffer row capacity |
| 160 |
size_t m_buffer_cols; // Physical buffer column capacity (stride) |
| 161 |
double m_growth_factor; // Grow multiplier to reduce realloc frequency |
| 162 |
|
| 163 |
/** |
| 164 |
* Convert 2D coordinates to flat index |
| 165 |
* Row-major: i.e. elements of same row are contiguous |
| 166 |
*/ |
| 167 |
inline size_t index(size_t i, size_t j) const |
| 168 |
{ |
| 169 |
assert(i < m_buffer_rows && j < m_buffer_cols); |
| 170 |
return i * m_buffer_cols + j; |
| 171 |
} |
| 172 |
|
| 173 |
public: |
| 174 |
// We keep these for backwards compatibility |
| 175 |
size_t &n; |
| 176 |
size_t &m; |
| 177 |
|
| 178 |
DynamicArray2D(size_t rows = 0, size_t cols = 0, double factor = 2.0) |
| 179 |
: m_rows(rows), m_cols(cols), |
| 180 |
m_buffer_rows(rows), m_buffer_cols(cols), |
| 181 |
m_growth_factor(factor), |
| 182 |
n(m_rows), m(m_cols) |
| 183 |
{ |
| 184 |
m_buffer.resize(m_buffer_rows * m_buffer_cols,T(0)); |
| 185 |
} |
| 186 |
/** |
| 187 |
* @brief Legacy constructor |
| 188 |
*/ |
| 189 |
DynamicArray2D(int _n, int _m) |
| 190 |
: DynamicArray2D(static_cast<size_t>(_n), |
| 191 |
static_cast<size_t>(_m), |
| 192 |
2.0) {} |
| 193 |
|
| 194 |
~DynamicArray2D(){}; |
| 195 |
|
| 196 |
/** |
| 197 |
* @brief Resize the array to new_rows x new_cols, preserving as much data as possible. |
| 198 |
* @param new_rows The desired number of logical rows. |
| 199 |
* @param new_cols The desired number of logical columns. |
| 200 |
* |
| 201 |
* If the requested size is larger than the current buffer, we grow the |
| 202 |
* internal storage using an over-allocation strategy: |
| 203 |
* new_dim = max(requested, old_capacity * growth_factor + 1) |
| 204 |
* for each dimension. This reduces the number of reallocations over time |
| 205 |
* and provides amortized O(1) growth. |
| 206 |
* |
| 207 |
* When resizing down (shrinking), we *don’t* free memory immediately. |
| 208 |
* Instead, we simply zero out the parts of the buffer that are now |
| 209 |
* outside the logical size. To actually release unused memory, |
| 210 |
* call `shrink_to_fit()`. |
| 211 |
*/ |
| 212 |
void resize(size_t new_rows, size_t new_cols) |
| 213 |
{ |
| 214 |
bool needs_realloc = false; |
| 215 |
size_t grow_rows = m_buffer_rows; |
| 216 |
size_t grow_cols = m_buffer_cols; |
| 217 |
|
| 218 |
// First we check if buffer needs to grows |
| 219 |
if (new_rows > m_buffer_rows) |
| 220 |
{ |
| 221 |
size_t candidate = static_cast<size_t>(m_buffer_rows * m_growth_factor) + 1; |
| 222 |
grow_rows = std::max(new_rows, candidate); |
| 223 |
needs_realloc = true; |
| 224 |
} |
| 225 |
if (new_cols > m_buffer_cols) |
| 226 |
{ |
| 227 |
size_t candidate = static_cast<size_t>(m_buffer_cols * m_growth_factor) + 1; |
| 228 |
grow_cols = std::max(new_cols, candidate); |
| 229 |
needs_realloc = true; |
| 230 |
} |
| 231 |
|
| 232 |
if (needs_realloc) |
| 233 |
{ |
| 234 |
// Allocate new buffer and copy existing data |
| 235 |
std::vector<T> new_buf(grow_rows * grow_cols,T(0)); |
| 236 |
size_t copy_rows = std::min(m_rows, new_rows); |
| 237 |
size_t copy_cols = std::min(m_cols, new_cols); |
| 238 |
|
| 239 |
for (size_t i = 0; i < copy_rows; ++i) |
| 240 |
{ |
| 241 |
for (size_t j = 0; j < copy_cols; ++j) |
| 242 |
{ |
| 243 |
new_buf[i * grow_cols + j] = m_buffer[index(i, j)]; |
| 244 |
} |
| 245 |
} |
| 246 |
// Swap in the new buffer and update capacities |
| 247 |
m_buffer.swap(new_buf); |
| 248 |
m_buffer_rows = grow_rows; |
| 249 |
m_buffer_cols = grow_cols; |
| 250 |
} |
| 251 |
else if (new_rows < m_rows || new_cols < m_cols) |
| 252 |
{ |
| 253 |
// Efficiently clear only the unused region without reallocating |
| 254 |
// Zero rows beyond new_rows |
| 255 |
for (size_t i = new_rows; i < m_buffer_rows; ++i) |
| 256 |
{ |
| 257 |
size_t base = i * m_buffer_cols; |
| •258 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + m_buffer_cols, T(0)); |
| 259 |
} |
| 260 |
// Zero columns beyond new_cols in remaining rows |
| 261 |
for (size_t i = 0; i < new_rows; ++i) |
| 262 |
{ |
| 263 |
size_t base = i * m_buffer_cols + new_cols; |
| •264 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + (m_buffer_cols - new_cols), T(0)); |
| 265 |
} |
| 266 |
} |
| 267 |
else if (new_rows > m_rows || new_cols > m_cols) |
| 268 |
{ |
| 269 |
// Initialize new regions to zero |
| 270 |
|
| 271 |
// Zero new rows |
| 272 |
for (size_t i = m_rows; i < new_rows; ++i) |
| 273 |
{ |
| 274 |
size_t base = i * m_buffer_cols; |
| •275 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + m_buffer_cols, T(0)); |
| 276 |
} |
| 277 |
|
| 278 |
// Zero new columns in existing rows |
| 279 |
for (size_t i = 0; i < m_rows; ++i) |
| 280 |
{ |
| 281 |
size_t base = i * m_buffer_cols + m_cols; |
| 282 |
size_t new_cols_in_row = std::min(new_cols, m_buffer_cols) - m_cols; |
| 283 |
if (new_cols_in_row > 0) |
| 284 |
{ |
| •285 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + new_cols_in_row, T(0)); |
| 286 |
} |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
// Finally, we update logical dimensions |
| 291 |
m_rows = new_rows; |
| 292 |
m_cols = new_cols; |
| 293 |
} |
| 294 |
|
| 295 |
// Legacy overloads for compatibility |
| 296 |
void resize(int new_n, int new_m) |
| 297 |
{ |
| 298 |
resize(static_cast<size_t>(new_n), static_cast<size_t>(new_m)); |
| 299 |
} |
| 300 |
|
| 301 |
void resize() |
| 302 |
{ |
| 303 |
resize(m_rows, m_cols); |
| 304 |
} |
| 305 |
|
| 306 |
/** |
| 307 |
* @brief Efficiently resize only the first dimension (rows) while keeping columns unchanged. |
| 308 |
* |
| 309 |
* @note This method assumes columns remain constant. If you need to change both |
| 310 |
* dimensions, use the general resize(rows, cols) method instead. |
| 311 |
*/ |
| 312 |
void resize_along_first(size_t new_rows) |
| 313 |
{ |
| 314 |
if(new_rows > m_buffer_rows) // growth case |
| 315 |
{ |
| 316 |
// So first we calculate how much to grow the buffer and then we over-allocate to avoid frequent reallocations |
| 317 |
size_t candidate = static_cast<size_t>(m_buffer_rows * m_growth_factor) + 1; |
| 318 |
size_t grow_rows = std::max(new_rows,candidate); |
| 319 |
|
| 320 |
// now we create a new buffer with new row capacity , while the column capacity remains same |
| 321 |
std::vector<T> new_buf(grow_rows * m_buffer_cols,T(0)); |
| 322 |
|
| 323 |
// Figure out how many rows of existing data we can preserve |
| 324 |
size_t copy_rows = std::min(m_rows, new_rows); |
| 325 |
|
| 326 |
if ( std::is_trivially_copyable<T>::value && copy_rows > 0) |
| 327 |
{ |
| 328 |
// We copy one complete row in a single memcpy operation ... much faster than copying element by element |
| 329 |
for (size_t i = 0; i < copy_rows; ++i) |
| 330 |
{ |
| •331 |
std::memcpy(new_buf.data() + i * m_buffer_cols, // destination: row i in new buffer |
| 332 |
m_buffer.data() + i * m_buffer_cols, // source: row i in old buffer |
| 333 |
m_buffer_cols * sizeof(T) // size: entire row |
| 334 |
); |
| 335 |
} |
| 336 |
} |
| 337 |
else |
| 338 |
{ |
| 339 |
for (size_t i =0; i< copy_rows; i++) |
| 340 |
{ |
| 341 |
for (size_t j =0; j < m_buffer_cols; ++j) |
| 342 |
{ |
| 343 |
new_buf[i*m_buffer_cols +j] = m_buffer[index(i,j)]; |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
m_buffer.swap(new_buf); |
| 349 |
m_buffer_rows = grow_rows; |
| 350 |
} |
| 351 |
else if (new_rows < m_rows) // shrinkage case |
| 352 |
{ |
| 353 |
// As we are reducing the number of rows , so we zero out deleted rows |
| 354 |
for ( size_t i = new_rows; i < m_rows ; ++i) |
| 355 |
{ |
| 356 |
size_t base = i * m_buffer_cols; |
| 357 |
|
| 358 |
// Zero out the entire row in one operation |
| •359 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + m_buffer_cols, T(0)); |
| 360 |
} |
| 361 |
|
| 362 |
/* Note: We don't shrink the actual buffer capacity here |
| 363 |
* This is intentional for performance - if you're shrinking temporarily, |
| 364 |
* you don't want to pay the cost of reallocation when you grow again. |
| 365 |
* Call shrink_to_fit() explicitly if you need to reclaim memory. |
| 366 |
*/ |
| 367 |
} |
| 368 |
else if (new_rows > m_rows) |
| 369 |
{ |
| 370 |
// Initialize new rows to zero |
| 371 |
for (size_t i = m_rows; i < new_rows; ++i) |
| 372 |
{ |
| 373 |
size_t base = i * m_buffer_cols; |
| •374 |
std::fill(m_buffer.begin() + base, m_buffer.begin() + base + m_buffer_cols, T(0)); |
| 375 |
} |
| 376 |
} |
| 377 |
// We just update the logical row count to reflect the new size |
| 378 |
m_rows =new_rows; |
| 379 |
} |
| 380 |
|
| 381 |
|
| 382 |
/** |
| 383 |
* @brief Shrink array to exact new shape, freeing unused memory |
| 384 |
* @param new_rows Must be <= current logical rows |
| 385 |
* @param new_cols Must be <= current logical cols |
| 386 |
*/ |
| 387 |
void shrink(size_t new_rows, size_t new_cols) |
| 388 |
{ |
| 389 |
if (new_rows > m_rows || new_cols > m_cols) { |
| 390 |
// Don't allow growing via shrink |
| 391 |
return; |
| 392 |
} |
| 393 |
|
| 394 |
if (new_rows < m_rows || new_cols < m_cols) { |
| 395 |
// Create new compact buffer |
| 396 |
std::vector<T> new_buffer(new_rows * new_cols); |
| 397 |
|
| 398 |
// Copy existing data row by row |
| 399 |
for (size_t i = 0; i < new_rows; ++i) { |
| 400 |
if (std::is_trivially_copyable<T>::value && new_cols > 0) { |
| •401 |
std::memcpy(new_buffer.data() + i * new_cols, |
| 402 |
m_buffer.data() + i * m_buffer_cols, |
| 403 |
new_cols * sizeof(T)); |
| 404 |
} else { |
| 405 |
for (size_t j = 0; j < new_cols; ++j) { |
| 406 |
new_buffer[i * new_cols + j] = m_buffer[index(i, j)]; |
| 407 |
} |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
// Replace buffer and update dimensions |
| 412 |
m_buffer.swap(new_buffer); |
| 413 |
m_rows = new_rows; |
| 414 |
m_cols = new_cols; |
| 415 |
m_buffer_rows = new_rows; |
| 416 |
m_buffer_cols = new_cols; |
| 417 |
} |
| 418 |
// If dimensions unchanged, just compact buffer |
| 419 |
else { |
| 420 |
shrink_to_fit(); |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
// Convenience overload for 1D shrink (just rows) |
| 425 |
void shrink(size_t new_rows) { |
| 426 |
shrink(new_rows, m_cols); |
| 427 |
} |
| 428 |
|
| 429 |
/** |
| 430 |
* Shrink buffer to exact size |
| 431 |
* Warning: Invalidates pointers and defeats growth optimization |
| 432 |
*/ |
| 433 |
void shrink_to_fit() |
| 434 |
{ |
| 435 |
if (m_rows < m_buffer_rows || m_cols < m_buffer_cols) |
| 436 |
{ |
| 437 |
std::vector<T> new_buffer(m_rows * m_cols); |
| 438 |
|
| 439 |
// Copy data to compact buffer |
| 440 |
for (size_t i = 0; i < m_rows; ++i) |
| 441 |
{ |
| 442 |
if (std::is_trivially_copyable<T>::value) |
| 443 |
{ |
| •444 |
std::memcpy(new_buffer.data() + i * m_cols, m_buffer.data() + index(i, 0), m_cols * sizeof(T)); |
| 445 |
} |
| 446 |
else |
| 447 |
{ |
| 448 |
for (size_t j = 0; j < m_cols; ++j) |
| 449 |
{ |
| 450 |
new_buffer[i * m_cols + j] = m_buffer[index(i, j)]; |
| 451 |
} |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
m_buffer.swap(new_buffer); |
| 456 |
m_buffer_rows = m_rows; |
| 457 |
m_buffer_cols = m_cols; |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
// Dimension getters |
| 462 |
size_t rows() const { return m_rows; } |
| 463 |
size_t cols() const { return m_cols; } |
| 464 |
size_t stride() const { return m_buffer_cols; } // for numpy stride calculationx |
| 465 |
|
| 466 |
/** |
| 467 |
* Raw data access for numpy integration |
| 468 |
* Returns pointer to start of buffer |
| 469 |
* Note: stride() != cols() when buffer is over-allocated |
| 470 |
*/ |
| 471 |
T *get_data_ptr() { return m_buffer.data(); } |
| 472 |
const T *get_data_ptr() const { return m_buffer.data(); } |
| 473 |
|
| 474 |
// 2D element access ... |
| 475 |
inline T &operator()(size_t i, size_t j) { return m_buffer[index(i, j)]; } |
| 476 |
inline const T &operator()(size_t i, size_t j) const { return m_buffer[index(i, j)]; } |
| 477 |
|
| 478 |
// Overloads for int indices for backward compatibility. |
| 479 |
inline T &operator()(int i, int j) { return operator()(static_cast<size_t>(i), static_cast<size_t>(j)); } |
| 480 |
inline const T &operator()(int i, int j) const { return operator()(static_cast<size_t>(i), static_cast<size_t>(j)); } |
| 481 |
|
| 482 |
// mixed-type overloads to resolve ambiguity |
| 483 |
inline T &operator()(size_t i, int j) { return operator()(i, static_cast<size_t>(j));} |
| 484 |
inline T &operator()(int i, size_t j) { return operator()(static_cast<size_t>(i), j);} |
| 485 |
|
| 486 |
/** |
| 487 |
* @brief Returns a copy of row i as std::vector<T>. |
| 488 |
*/ |
| 489 |
std::vector<T> operator()(size_t i) const |
| 490 |
{ |
| 491 |
std::vector<T> row(m_cols); |
| 492 |
for (size_t j = 0; j < m_cols; ++j) |
| 493 |
{ |
| 494 |
row[j] = m_buffer[index(i, j)]; |
| 495 |
} |
| 496 |
return row; |
| 497 |
} |
| 498 |
}; |
| 499 |
|
| 500 |
#endif |