diff options
| author | Mustafa Quraish <[email protected]> | 2022-02-05 01:38:34 -0500 |
|---|---|---|
| committer | Mustafa Quraish <[email protected]> | 2022-02-05 08:56:15 -0500 |
| commit | 81a0df76cbcd46799134e688dabb8dc870da5351 (patch) | |
| tree | c272607d270b3ae8f1ba95cb6f6b28c9d0bc6075 /std | |
| parent | Miscellaneous stdlib additions (diff) | |
| download | cup-81a0df76cbcd46799134e688dabb8dc870da5351.tar.xz cup-81a0df76cbcd46799134e688dabb8dc870da5351.zip | |
Add support for some more binary ops: |, &, ^
Diffstat (limited to 'std')
| -rw-r--r-- | std/vector.cup | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/std/vector.cup b/std/vector.cup new file mode 100644 index 0000000..eb76155 --- /dev/null +++ b/std/vector.cup @@ -0,0 +1,40 @@ +import "std/common.cup" + +struct Vector { + size: int; + capacity: int; + data: void**; +}; + +fn vector_new_sized(capacity: int): Vector* { + let t: Vector* = malloc(sizeof(Vector)); + t.size = 0; + t.capacity = capacity; + t.data = malloc(capacity * sizeof(void*)); + return t; +} + +fn vector_new(): Vector* { + const initial_default_capacity = 4; + return vector_new_sized(initial_default_capacity); +} + +fn vector_push(vec: Vector*, item: void*) { + if (vec.size == vec.capacity) { + let new_capacity = vec.capacity * 2; + let new_data = malloc(new_capacity * sizeof(void*)); + memcpy(new_data, vec.data, vec.capacity * sizeof(void*)); + vec.data = new_data; + vec.capacity = new_capacity; + } + vec.data[vec.size] = item; + vec.size = vec.size + 1; +} + +fn vector_pop(vec: Vector*): void* { + if (vec.size == 0) + die("Vector is empty, nothing to pop."); + + vec.size = vec.size - 1; + return vec.data[vec.size]; +}
\ No newline at end of file |