Last active
May 8, 2025 23:44
-
-
Save Lucrecious/01144ade95b08cddf9a75bb7740db053 to your computer and use it in GitHub Desktop.
orso dynamic array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
array_t :: (!u: type) -> type { | |
return struct { | |
items: &u = .{}; | |
count := 0; | |
capacity := 0; | |
}; | |
}; | |
push :: (arr: &!u, val: !v) -> void { | |
new_capacity := arr.capacity; | |
while arr.count >= new_capacity do | |
new_capacity = if new_capacity == 0 then 8 else new_capacity*2; | |
if new_capacity > arr.capacity { | |
if arr.items == (&v).{} then | |
arr.items = mreserve(sizeof([100_000_000]v)) as &v; // dumb way of doing it but this is just an example | |
mmarkrw(arr.items + (arr.capacity as ptrdiff_t), (new_capacity-arr.capacity) as size_t); | |
arr.capacity = new_capacity; | |
}; | |
place := arr.items + (arr.count as ptrdiff_t); | |
*place = val; | |
++arr.count; | |
}; | |
at :: (arr: &!u, index: int, ret: &!v) -> bool { | |
if index < 0 or index >= arr.count then return false; | |
addr := arr.items + (index as ptrdiff_t); | |
*ret = *addr; | |
return true; | |
}; | |
main :: () -> void { | |
arrayint_t :: @run array_t(int); | |
nums := arrayint_t.{}; | |
push(&nums, 10); | |
push(&nums, 20); | |
for i := 0; i < nums.count; ++i { | |
item := 0; | |
at(&nums, i, &item); | |
printint(item); | |
println(); | |
}; | |
arrayf_t :: @run array_t(f64); | |
dbls := arrayf_t.{}; | |
push(&dbls, 4.2); | |
push(&dbls, 2.4); | |
for i := 0; i < dbls.count; ++i { | |
item := 0.0; | |
at(&dbls, i, &item); | |
printf64(item); | |
println(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment