Files

78 lines
1.1 KiB
C
Raw Permalink Normal View History

2024-09-27 19:46:39 +02:00
#ifndef _PIUMA_LIB_ARRAY_H_
#define _PIUMA_LIB_ARRAY_H_
#include "types.h"
#include "math.h"
#include <assert.h>
template<typename T>
struct Array
{
T *data = NULL;
u64 count = 0;
u64 capacity = 0;
inline void reserve(u64 new_capacity = 4)
{
new_capacity = maximum(new_capacity, count);
if(new_capacity > capacity)
{
data = (T*)realloc(data, sizeof(T) * new_capacity);
capacity = new_capacity;
}
}
inline void clear()
{
count = 0;
}
inline void reset()
{
free(data);
data = NULL;
count = 0;
capacity = 0;
}
inline void push(T element)
{
if(count + 1 >= capacity)
reserve(maximum(count + 1, capacity * 2));
data[count++] = element;
}
inline void push_unchecked(T element)
{
data[count++] = element;
}
inline bool pop(T *element = NULL)
{
if(count <= 0)
return false;
count--;
if(element) *element = data[count];
return true;
}
inline T pop_unchecked()
{
return data[--count];
}
inline T &operator[](u64 index)
{
return data[index];
}
inline T &last()
{
return data[count - 1];
}
};
#endif