blob: e5f58eb249030ff0143cdbc2d5da7ea4ef10c2e3 (
plain)
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
89
90
91
92
93
|
# Define vector struct
struct Vector {
~void data,
int
size,
count,
_elsz
}
# Consts used in impl
int VECT_DEFAULT_SIZE = 4
int VECT_MAX_GROW = 128
~uint8 PUSH_STR = "Push %d\n\0"
# Methods on the struct
/; method Vector
# Initialize a new vector with elements
# 'elsz' bytes long
/; init (int elsz)
self.size = VECT_DEFAULT_SIZE
self._elsz = elsz
self.count = 0
self.data = _alloc(elsz * VECT_DEFAULT_SIZE)
;/
# Grow the size of the vector by 'size' elements
/; _grow (int size)
/; if (size > VECT_MAX_GROW)
size = VECT_MAX_GROW
;/
self.size = self.size + size
self.data = _realloc(self.data, self.size * self._elsz)
;/
# Shrink the size of the vector by 'size' elements
/; _shrink (int size)
/; if (self.size - size < 0)
self.size = 1
;; else
self.size = self.size - size
;/
/; if (self.count < self.size)
self.count = self.size
;/
self.data = _realloc(self.data, self.size * self._elsz)
;/
# Push an element onto the end of the vector
/; push (~void data)
/; if (self.count == self.size - 1)
self._grow(self.size)
;/
int offset = self._elsz * self.count
/; loop (int i = 0; i < self._elsz) [i++]
~uint8 to = self.data + offset + i
~uint8 from = data + i
to` = from`
;/
self.count++
;/
# Pop an element off of the end of the vector
/; pop
self.count--
/; if (self.count < self.size / 2)
self._shrink(self.size / 3)
;/
;/
# Get a pointer to the start of an element in the vector
/; get (int index) [~void]
return self.data
;/
# Free all memory associated with the vector
/; end
_delete(self.data)
self.size = 0
self._elsz = 0
self.count = 0
;/
;/
|