module Std::Array { extern func bux_alloc(size: uint) -> *void; extern func bux_realloc(ptr: *void, size: uint) -> *void; extern func bux_free(ptr: *void); extern func bux_bounds_check(index: uint, len: uint); struct Array { data: *T, len: uint, cap: uint, } func Array_New(cap: uint) -> Array { let data = bux_alloc(cap * sizeof(T)) as *T; return Array { data: data, len: 0, cap: cap }; } func Array_Push(self: *Array, value: T) { if self.len >= self.cap { self.cap = self.cap * 2; self.data = bux_realloc(self.data as *void, self.cap * sizeof(T)) as *T; } self.data[self.len] = value; self.len = self.len + 1; } func Array_Get(self: *Array, index: uint) -> T { bux_bounds_check(index, self.len); return self.data[index]; } func Array_Set(self: *Array, index: uint, value: T) { bux_bounds_check(index, self.len); self.data[index] = value; } func Array_Len(self: *Array) -> uint { return self.len; } func Array_Free(self: *Array) { bux_free(self.data as *void); self.data = null as *T; self.len = 0; self.cap = 0; } func Array_Drop(self: *Array) { Array_Free(self); } func Array_operator_index_get(self: *Array, idx: uint) -> T { return Array_Get(self, idx); } func Array_operator_index_set(self: *Array, idx: uint, value: T) { Array_Set(self, idx, value); } /* True if the array has no elements */ func Array_IsEmpty(self: *Array) -> bool { return self.len == 0; } /* Current capacity (not length) */ func Array_Cap(self: *Array) -> uint { return self.cap; } /* Drop length to zero; keeps allocated capacity */ func Array_Clear(self: *Array) { self.len = 0; } /* Ensure capacity is at least minCap (does not shrink) */ func Array_Reserve(self: *Array, minCap: uint) { if minCap <= self.cap { return; } self.cap = minCap; self.data = bux_realloc(self.data as *void, self.cap * sizeof(T)) as *T; } /* First element (panics if empty via bounds check) */ func Array_First(self: *Array) -> T { return Array_Get(self, 0); } /* Last element (panics if empty via bounds check) */ func Array_Last(self: *Array) -> T { return Array_Get(self, self.len - 1); } /* Remove and return the last element (panics if empty) */ func Array_Pop(self: *Array) -> T { bux_bounds_check(0, self.len); self.len = self.len - 1; return self.data[self.len]; } /* Linear search: true if value is present (uses ==) */ func Array_Contains(self: *Array, value: T) -> bool { var i: uint = 0; while i < self.len { if self.data[i] == value { return true; } i = i + 1; } return false; } /* Index of first equal element, or -1 if not found */ func Array_IndexOf(self: *Array, value: T) -> int { var i: uint = 0; while i < self.len { if self.data[i] == value { return i as int; } i = i + 1; } return -1; } /* Append all elements of other onto self */ func Array_Extend(self: *Array, other: *Array) { var i: uint = 0; while i < other.len { Array_Push(self, other.data[i]); i = i + 1; } } }