templated the C++ codes

This commit is contained in:
masterexplorer 2024-08-27 15:54:03 +02:00
parent 9a68f6970d
commit 1426a742dc
2 changed files with 16 additions and 8 deletions

View File

@ -17,22 +17,23 @@
#define TL_UNLIKELY(x) __builtin_expect(!!(x), 0) #define TL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#endif /* TL_UNLIKELY */ #endif /* TL_UNLIKELY */
template<typename T>
class TurboList { class TurboList {
int *old; T *old;
int *nex; T *nex;
uint32_t mid; // non-inclusive . . . m uint32_t mid; // non-inclusive . . . m
uint32_t end; // non-inclusive e . . . . uint32_t end; // non-inclusive e . . . .
uint32_t capacity; uint32_t capacity;
TL_NOINLINE void grow_and_insert(int elem) noexcept { TL_NOINLINE void grow_and_insert(T elem) noexcept {
// assert(mid == 0); // assert(mid == 0);
if(old) free(old); if(old) free(old);
old = nex; old = nex;
mid = end; mid = end;
capacity *= 2; capacity *= 2;
nex = (int *) malloc(this->capacity * sizeof(int)); nex = (int *) malloc(this->capacity * sizeof(T));
// Will go into the INSERT code path here // Will go into the INSERT code path here
insert(elem); insert(elem);
@ -45,7 +46,7 @@ public:
end(initial_size), end(initial_size),
capacity(initial_cap) { capacity(initial_cap) {
nex = (int *) malloc(this->capacity * sizeof(int)); nex = (int *) malloc(this->capacity * sizeof(T));
} }
inline ~TurboList() noexcept { inline ~TurboList() noexcept {
@ -53,11 +54,11 @@ public:
if(old) free(old); if(old) free(old);
} }
inline int& operator[](uint32_t i) noexcept { inline T& operator[](uint32_t i) noexcept {
return (i < mid) ? old[i] : nex[i]; return (i < mid) ? old[i] : nex[i];
} }
inline void insert(int elem) noexcept { inline void insert(T elem) noexcept {
if(TL_LIKELY(end < capacity)) { if(TL_LIKELY(end < capacity)) {
// INSERT // INSERT

View File

@ -24,6 +24,9 @@ static inline void printt(const char *prefix, size_t before, size_t after) noexc
} }
int main() { int main() {
// std::vector //
std::vector<int> vec; std::vector<int> vec;
auto before_vector = ms_now(); auto before_vector = ms_now();
for(int i = 0; i < N; ++i) { for(int i = 0; i < N; ++i) {
@ -32,7 +35,9 @@ int main() {
auto after_vector = ms_now(); auto after_vector = ms_now();
printt("vector", before_vector, after_vector); printt("vector", before_vector, after_vector);
TurboList list; // TurboList //
TurboList<int> list;
auto before_TurboList = ms_now(); auto before_TurboList = ms_now();
for(int i = 0; i < N; ++i) { for(int i = 0; i < N; ++i) {
@ -47,6 +52,8 @@ int main() {
} }
#endif /* PRINT_DBG */ #endif /* PRINT_DBG */
// C turbolist //
turbolist clist = turbolist_create(); turbolist clist = turbolist_create();
auto before_cturbolist = ms_now(); auto before_cturbolist = ms_now();