#ifndef B2_GROWABLE_BUFFER_H
#define B2_GROWABLE_BUFFER_H
#include "b2_api.h"
#include "b2_block_allocator.h"
#include <string.h>
#include <memory.h>
#include <algorithm>
template <typename T>
class B2_API b2GrowableBuffer
{
public:
b2GrowableBuffer(b2BlockAllocator& allocator) :
data(nullptr),
count(0),
capacity(0),
allocator(&allocator)
{
#if defined(LIQUIDFUN_SIMD_NEON)
b2Assert((intptr_t)&data - (intptr_t)(this) == 0
&& (intptr_t)&capacity - (intptr_t)(this) == 8);
#endif }
b2GrowableBuffer(const b2GrowableBuffer<T>& rhs) :
data(nullptr),
count(rhs.count),
capacity(rhs.capacity),
allocator(rhs.allocator)
{
if (rhs.data != nullptr)
{
data = (T*) allocator->Allocate(sizeof(T) * capacity);
memcpy(data, rhs.data, sizeof(T) * count);
}
}
~b2GrowableBuffer()
{
Free();
}
T& Append()
{
if (count >= capacity)
{
Grow();
}
return data[count++];
}
void Reserve(int32 newCapacity)
{
if (capacity >= newCapacity)
return;
T* newData = (T*) allocator->Allocate(sizeof(T) * newCapacity);
if (data)
{
memcpy(newData, data, sizeof(T) * count);
allocator->Free(data, sizeof(T) * capacity);
}
capacity = newCapacity;
data = newData;
}
void Grow()
{
int32 newCapacity = capacity ? 2 * capacity
: b2_minParticleSystemBufferCapacity;
b2Assert(newCapacity > capacity);
Reserve(newCapacity);
}
void Free()
{
if (data == nullptr)
return;
allocator->Free(data, sizeof(data[0]) * capacity);
data = nullptr;
capacity = 0;
count = 0;
}
void Shorten(const T* newEnd)
{
b2Assert(newEnd >= data);
count = (int32) (newEnd - data);
}
T& operator[](int i)
{
return data[i];
}
const T& operator[](int i) const
{
return data[i];
}
T* Data()
{
return data;
}
const T* Data() const
{
return data;
}
T* Begin()
{
return data;
}
const T* Begin() const
{
return data;
}
T* End()
{
return &data[count];
}
const T* End() const
{
return &data[count];
}
int32 GetCount() const
{
return count;
}
void SetCount(int32 newCount)
{
b2Assert(0 <= newCount && newCount <= capacity);
count = newCount;
}
int32 GetCapacity() const
{
return capacity;
}
template<class UnaryPredicate>
T* RemoveIf(UnaryPredicate pred)
{
T* newEnd = std::remove_if(data, data + count, pred);
Shorten(newEnd);
return newEnd;
}
template<class BinaryPredicate>
T* Unique(BinaryPredicate pred)
{
T* newEnd = std::unique(data, data + count, pred);
Shorten(newEnd);
return newEnd;
}
private:
T* data;
int32 count;
int32 capacity;
b2BlockAllocator* allocator;
};
#endif