Skip to content

Commit 2361c61

Browse files
committed
add vector remove-front and remove-back
1 parent 712d21e commit 2361c61

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

PLATFORM/C/LIB/vector.lsts

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ let mk-vector(type: Type<t>, capacity: U64): Vector<t> = (
66
Vector { (malloc(data-sz) as t[]), 0_u64, capacity }
77
);
88

9-
# does not change length
9+
# does not change length!
1010
let .realloc(v: Vector<t>, target-capacity: U64): Vector<t> = (
1111
let data-sz = sizeof(t) * target-capacity;
1212
let newp = realloc(v.data as ?[], data-sz) as t[];
@@ -27,20 +27,49 @@ let .push(v: Vector<t>, i: t): Vector<t> = (
2727
v
2828
);
2929

30+
# shrinks the vector if it has way too many elements. shouldn't be called manually
31+
let .shrink(v: Vector<t>): Vector<t> = (
32+
let too-much = v.capacity - v.length;
33+
let minimum = (v.length << 1) + v.length; # mul 1.5
34+
if too-much > minimum {
35+
v = v.realloc(minimum);
36+
};
37+
v
38+
);
39+
40+
let .remove-front(v: Vector<t>, num: U64): Vector<t> = (
41+
if num > v.length() {
42+
fail("tried to remove \{num} elements from vector, but only have \{v.length()}");
43+
};
44+
45+
let i = num;
46+
while i < v.length() {
47+
v[i-num] = v[i];
48+
i = i + 1;
49+
};
50+
v.length = v.length - num;
51+
52+
v.shrink();
53+
);
54+
55+
let .remove-back(v: Vector<t>, num: U64): Vector<t> = (
56+
if num > v.length() {
57+
fail("tried to remove \{num} elements from vector, but only have \{v.length()}");
58+
};
59+
60+
v.length = v.length - num;
61+
62+
v.shrink();
63+
);
64+
3065
let .pop(v: Vector<t>): Tuple<Vector<t>, t> = (
3166
if v.length() == 0 {
3267
fail("Tried to pop from empty Vector.");
3368
};
69+
3470
let lasti = v.length - 1;
3571
let last = v[lasti];
36-
v.length = lasti;
37-
v.capacity = v.capacity;
38-
39-
let too-much = v.capacity - v.length;
40-
let minimum = (v.length << 1) + v.length; # mul 1.5
41-
if too-much > minimum {
42-
v = v.realloc(minimum);
43-
};
72+
v = v.remove-back(1);
4473

4574
Tuple { v, last }
4675
);

0 commit comments

Comments
 (0)