96 lines
2.7 KiB
Text
96 lines
2.7 KiB
Text
Static_Array :: struct(capacity: int, T: Type) {
|
|
items: [capacity]T;
|
|
count: int;
|
|
|
|
Zero :: #run zero_value(T);
|
|
}
|
|
|
|
operator [] :: inline (a: Static_Array, index: int, loc := #caller_location) -> a.T #no_abc {
|
|
assert(index >= 0 && index < a.count, "invalid index: % (max: %)", index, a.count - 1, loc = loc);
|
|
return a.items[index];
|
|
}
|
|
|
|
operator *[] :: inline (a: *Static_Array, index: int, loc := #caller_location) -> *a.T #no_abc {
|
|
assert(index >= 0 && index < a.count, "invalid index: % (max: %)", index, a.count - 1, loc = loc);
|
|
return *a.items[index];
|
|
}
|
|
|
|
operator []= :: inline (a: *Static_Array, index: int, value: a.T, loc := #caller_location) #no_abc {
|
|
assert(index >= 0 && index < a.capacity, "invalid index: % (max: %)", index, a.count - 1, loc = loc);
|
|
a.items[index] = value;
|
|
}
|
|
|
|
for_expansion :: (a: *Static_Array, body: Code, flags: For_Flags) #expand {
|
|
view := make_view(a);
|
|
for *=(flags & .POINTER == .POINTEr) <=(flags & .REVERSE == .REVERSE) `it, `it_index: iter {
|
|
#insert,scope(body)(break = break it) body;
|
|
}
|
|
}
|
|
|
|
append :: inline (a: *Static_Array, item: a.T) -> *a.T {
|
|
ensure_array_has_room(a, 1);
|
|
ptr := *a[a.count];
|
|
ptr.* = item;
|
|
a.count += 1;
|
|
return ptr;
|
|
}
|
|
|
|
append :: inline (a: *Static_Array) -> *a.T {
|
|
ensure_array_has_room(a, 1);
|
|
ptr := *a[a.count];
|
|
a.count += 1;
|
|
return ptr;
|
|
}
|
|
|
|
append :: inline (a: *Static_Array, items: ..a.T) -> *a.T {
|
|
ensure_array_has_room(a, items.count);
|
|
first := *a.items[a.count];
|
|
memcpy(a.items.data + a.count, items.data, items.count * size_of(a.T));
|
|
a.count += items.count;
|
|
return first;
|
|
}
|
|
|
|
reset :: inline (a: *Static_Array, $keep_memory := true) {
|
|
#if keep_memory {
|
|
a.count = 0;
|
|
}
|
|
else {
|
|
for 0..a.count - 1 a.items[it] = a.Zero;
|
|
a.count = 0;
|
|
}
|
|
}
|
|
|
|
make_view :: (a: Static_Array) -> []a.T {
|
|
view := a.items.([]a.T);
|
|
view.count = a.count;
|
|
return view;
|
|
}
|
|
|
|
make_dynamic :: (a: *Static_Array) -> [..]a.T {
|
|
res: [..]a.T;
|
|
res.count = a.count;
|
|
res.allocated = a.count;
|
|
res.data = basic.alloc(a.count * size_of(a.T));
|
|
memcpy(res.data, a.items.data, a.count * size_of(a.T));
|
|
}
|
|
|
|
|
|
#scope_file;
|
|
|
|
ensure_array_has_room :: (array: *Static_Array, count: int, loc := #caller_location) #expand {
|
|
basic.assert(array.count + count <= array.capacity, "attempt to add too many elements! want: %, Max: %", array.count + count, array.capacity, loc = loc);
|
|
}
|
|
|
|
#if RUN_TESTS #run {
|
|
test :: #import,file "./test/module.jai";
|
|
|
|
test.run("basic operations", (t) => {
|
|
a: Static_Array(10, int);
|
|
|
|
test.expect(t, a.count == 0);
|
|
test.expect(t, a.capacity == 10);
|
|
|
|
append(*a, 10, 20, 30);
|
|
test.expect(t, a.count == 3, "count: %", a.count);
|
|
});
|
|
}
|