1 /************************************************************************************************************************
2 Copyright: Copyright © 2018-2023, Dawid Masiukiewicz, Michał Masiukiewicz
3 License: BSD 3-clause, see LICENSE file in project root folder.
4 */
5 module bubel.ecs.simple_vector;
6 
7 import bubel.ecs.std;
8 
9 //import core.stdc.string;
10 
11 /************************************************************************************************************************
12 Vector for byte data. Simpler than standard template-based implementation designed for better performance. \
13 Rellocates 1024 elements at once instead of doubling size.
14 */
15 struct SimpleVector
16 {
17 
18     @disable this(this);
19     
20     ~this() nothrow @nogc
21     {
22         if(data)
23             Mallocator.dispose(data);
24     }
25 
26     ///Add element to vector
27     void add(ubyte el) nothrow @nogc
28     {
29         while (used >= data.length)
30         {
31             if (data is null)
32                 data = Mallocator.makeArray!ubyte(1024);
33             else
34                 data = Mallocator.expandArray(data, data.length);
35         }
36         data[used++] = el;
37     }
38 
39     ///Add array of elements to vector
40     void add(ubyte[] el) nothrow @nogc
41     {
42         while (used + el.length >= data.length)
43         {
44             if (data is null)
45                 data = Mallocator.makeArray!ubyte(1024);
46             else
47                 data = Mallocator.expandArray(data, data.length);
48         }
49         memcpy(data.ptr + used, el.ptr, el.length);
50         used += el.length;
51     }
52 
53     ///Return vector length
54     size_t length() nothrow @nogc
55     {
56         return used;
57     }
58 
59     export ref ubyte opIndex(size_t pos) nothrow @nogc
60     {
61         return data[pos];
62     }
63 
64     export ubyte[] opSlice() nothrow @nogc
65     {
66         return data[0 .. used];
67     }
68 
69     export ubyte[] opSlice(size_t x, size_t y) nothrow @nogc
70     {
71         return data[x .. y];
72     }
73 
74     export size_t opDollar() nothrow @nogc
75     {
76         return used;
77     }
78 
79     ///set vector length to 0
80     void clear() nothrow @nogc
81     {
82         used = 0;
83     }
84 
85     ubyte[] data = null;
86     size_t used = 0;
87 }