Add tuner components
[satune.git] / src / Collections / cppvector.h
1 #ifndef CPPVECTOR_H
2 #define CPPVECTOR_H
3 #include <string.h>
4
5 #define VECTOR_DEFCAP 8
6
7 template<typename type>
8 class Vector {
9 public:
10         Vector(uint _capacity = VECTOR_DEFCAP) :
11                 size(0),
12                 capacity(_capacity),
13                 array((type *) ourmalloc(sizeof(type) * _capacity)) {
14         }
15
16         Vector(uint _capacity, type *_array)  :
17                 size(_capacity),
18                 capacity(_capacity),
19                 array((type *) ourmalloc(sizeof(type) * _capacity)) {
20                 memcpy(array, _array, capacity * sizeof(type));
21         }
22
23         Vector(Vector<type> *v) :
24                 size(v->size),
25                 capacity(v->capacity),
26                 array((type *) ourmalloc(sizeof(type) * v->capacity)) {
27                 memcpy(array, v->array, capacity * sizeof(type));
28         }
29         void pop() {
30                 size--;
31         }
32
33         type last() const {
34                 return array[size - 1];
35         }
36
37         void setSize(uint _size) {
38                 if (_size <= size) {
39                         size = _size;
40                         return;
41                 } else if (_size > capacity) {
42                         array = (type *)ourrealloc(array, _size * sizeof(type));
43                         capacity = _size;
44                 }
45                 bzero(&array[size], (_size - size) * sizeof(type));
46                 size = _size;
47         }
48
49         void push(type item) {
50                 if (size >= capacity) {
51                         uint newcap = capacity << 1;
52                         array = (type *)ourrealloc(array, newcap * sizeof(type));
53                         capacity = newcap;
54                 }
55                 array[size++] = item;
56         }
57
58         type get(uint index) const {
59                 return array[index];
60         }
61
62         void setExpand(uint index, type item) {
63                 if (index >= size)
64                         setSize(index + 1);
65                 set(index, item);
66         }
67
68         void set(uint index, type item) {
69                 array[index] = item;
70         }
71
72         inline uint getSize() const {
73                 return size;
74         }
75
76         ~Vector() {
77                 ourfree(array);
78         }
79
80         void clear() {
81                 size = 0;
82         }
83
84         type *expose() {
85                 return array;
86         }
87         CMEMALLOC;
88 private:
89         uint size;
90         uint capacity;
91         type *array;
92 };
93 #endif