Skip to content

Instantly share code, notes, and snippets.

@ALEXMORF
Created April 11, 2021 23:18
Show Gist options
  • Save ALEXMORF/5d1c1577c5d7885fbdecbcd24ce80b42 to your computer and use it in GitHub Desktop.
Save ALEXMORF/5d1c1577c5d7885fbdecbcd24ce80b42 to your computer and use it in GitHub Desktop.
simple stable growable array
#pragma once
#include "common.h"
#include "dynamic_array.h"
template <typename T>
struct Stable_Dynamic_Array {
// this is your usual unstable growable array like std::vector
Dynamic_Array<T *> blocks;
int count;
int cap;
void push(T elem) {
if (count >= cap) {
//NOTE(chen): equivalent to 2^N growth, same as dynamic_array
int new_block_size = cap + 1;
cap += new_block_size;
T *new_block = (T *)calloc(new_block_size, sizeof(T));
blocks.push(new_block);
}
++count;
operator[](count-1) = elem;
}
T &operator[](int index) {
assert(index >= 0 && index < count);
int block_index = 31 - nlz(u32(index+1)); // effectively floor(log2(index+1))
int local_index = index - ((1 << block_index) - 1);
return blocks[block_index][local_index];
}
T operator[](int index) const {
assert(index >= 0 && index < count);
int block_index = 31 - nlz(u32(index+1)); // effectively floor(log2(index+1))
int local_index = index - ((1 << block_index) - 1);
return blocks[block_index][local_index];
}
};
template <typename T>
void free(Stable_Dynamic_Array<T> array) {
for (int i = 0; i < array.blocks.count; ++i) {
free(array.blocks[i]);
}
free(array.blocks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment