blob: 13a24c476aba21e5990c9de0391f5d1eb8670421 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
#ifndef STRUCTS_ALIST_H
#define STRUCTS_ALIST_H
#include <knob/format.h>
#include <knob/block.h>
#include <knob/panic.h>
#include <knob/heap.h>
#include <stdint.h>
template<class data>
class alist {
public:
uint32_t n_entries;
uint32_t buf_size;
uint32_t expand_by;
data *buf;
alist(uint32_t default_size = 10, uint32_t expand_by = 10)
: n_entries(0), buf_size(default_size), expand_by(expand_by),
buf(new data[default_size]) {}
//from is copied
alist(const data *from, uint32_t count, uint32_t extra_size = 10, uint32_t expand_by = 10)
: n_entries(count), buf_size(count + extra_size), expand_by(expand_by),
buf(new data[count + extra_size]) {
for (uint32_t i = 0; i < count; ++i)
buf[i] = from[i];
}
~alist() {
delete[] buf;
}
void copy_from(const data *from, uint32_t count) {
expand_to(count);
n_entries = count;
for (uint32_t i = 0; i < count; ++i)
buf[i] = from[i];
}
void expand_to(uint32_t size) {
if (size <= buf_size)
return;
data *const new_buf = new data[size * sizeof(data)];
for (uint32_t i = 0; i < buf_size; ++i)
new_buf[i] = buf[i];
delete[] buf;
buf = new_buf;
buf_size = size;
}
void copy_from(const alist<data> &other) {
expand_to(n_entries = other.n_entries);
for (uint32_t i = 0; i < n_entries; ++i)
buf[i] = other.buf[i];
}
void add_back(data d) {
if (n_entries == buf_size)
expand_to(buf_size + expand_by);
buf[n_entries++] = d;
}
void insert(uint32_t i, data d) {
if (n_entries == buf_size)
expand_to(buf_size + expand_by);
for (uint32_t n = n_entries; n > i; --n)
buf[n] = buf[n - 1];
buf[i] = d;
++n_entries;
}
void remove(uint32_t i) {
--n_entries;
for (uint32_t n = i; n < n_entries; ++n)
buf[n] = buf[n + 1];
}
//returns -1 if not found
uint32_t index_of(data d) {
for (uint32_t i = 0; i < n_entries; ++i)
if (buf[i] == d)
return i;
return -1;
}
};
#endif
|