turbolist/TurboList.hpp
2024-08-27 11:20:20 +02:00

90 lines
1.6 KiB
C++

#ifndef TURBO_LIST_H
#define TURBO_LIST_H
#include<cstdint>
#include<cstdlib>
#include<cassert>
#ifndef TL_NOINLINE
#define TL_NOINLINE __attribute__((noinline))
#endif /* TL_NOINLINE */
#ifndef TL_LIKELY
#define TL_LIKELY(x) __builtin_expect(!!(x), 1)
#endif /* TL_LIKELY */
#ifndef TL_UNLIKELY
#define TL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#endif /* TL_UNLIKELY */
class TurboList {
int *old;
int *nex;
uint32_t mid; // non-inclusive . . . m
uint32_t end; // non-inclusive e . . . .
uint32_t capacity;
uint32_t count;
TL_NOINLINE void grow_and_insert(int elem) noexcept {
// assert(mid == 0);
if(old) free(old);
old = nex;
mid = end;
capacity *= 2;
nex = (int *) malloc(this->capacity * sizeof(int));
// Will go into the INSERT code path here
insert(elem);
}
public:
inline TurboList(uint32_t initial_cap = 16) noexcept :
old(nullptr),
mid(0),
end(0),
capacity(initial_cap),
count(0) {
nex = (int *) malloc(this->capacity * sizeof(int));
}
inline ~TurboList() noexcept {
if(nex) free(nex);
if(old) free(old);
}
inline int& operator[](uint32_t i) noexcept {
return (i < mid) ? old[i] : nex[i];
}
inline void insert(int elem) noexcept {
if(TL_LIKELY(count < capacity)) {
// INSERT
/* Same as this:
if(mid > 0) {
nex[mid - 1] = old[mid - 1];
--mid;
}
*/
bool hasmid = (mid > 0);
mid -= hasmid;
nex[mid] = hasmid ? old[mid] : nex[mid];
nex[end++] = elem;
++count;
} else {
// GROW
grow_and_insert(elem);
}
}
inline uint32_t size() noexcept {
return count;
}
};
#endif /* TURBO_LIST_H */