bubel-ecs/source/bubel/ecs/simple_vector.d
2022-07-09 20:27:01 +00:00

87 lines
2.1 KiB
D

/************************************************************************************************************************
Copyright: Copyright © 2018-2019, Dawid Masiukiewicz, Michał Masiukiewicz
License: BSD 3-clause, see LICENSE file in project root folder.
*/
module bubel.ecs.simple_vector;
import bubel.ecs.std;
//import core.stdc.string;
/************************************************************************************************************************
Vector for byte data. Simpler than standard template-based implementation designed for better performance. \
Rellocates 1024 elements at once instead of doubling size.
*/
struct SimpleVector
{
@disable this(this);
~this() nothrow @nogc
{
if(data)
Mallocator.dispose(data);
}
///Add element to vector
void add(ubyte el) nothrow @nogc
{
while (used >= data.length)
{
if (data is null)
data = Mallocator.makeArray!ubyte(1024);
else
data = Mallocator.expandArray(data, data.length);
}
data[used++] = el;
}
///Add array of elements to vector
void add(ubyte[] el) nothrow @nogc
{
while (used + el.length >= data.length)
{
if (data is null)
data = Mallocator.makeArray!ubyte(1024);
else
data = Mallocator.expandArray(data, data.length);
}
memcpy(data.ptr + used, el.ptr, el.length);
used += el.length;
}
///Return vector length
size_t length() nothrow @nogc
{
return used;
}
export ref ubyte opIndex(size_t pos) nothrow @nogc
{
return data[pos];
}
export ubyte[] opSlice() nothrow @nogc
{
return data[0 .. used];
}
export ubyte[] opSlice(size_t x, size_t y) nothrow @nogc
{
return data[x .. y];
}
export size_t opDollar() nothrow @nogc
{
return used;
}
///set vector length to 0
void clear() nothrow @nogc
{
used = 0;
}
ubyte[] data = null;
size_t used = 0;
}