jc/array/dynamic_array.jai

106 lines
2.7 KiB
Text

// @todo(judah): replace array_add
append :: inline (arr: *[..]$T, value: T) -> *T {
mem.lazy_set_allocator(arr);
ptr := basic.array_add(arr,, allocator = arr.allocator);
ptr.* = value;
return ptr;
}
append :: inline (arr: *[..]$T, values: ..T) -> *T {
mem.lazy_set_allocator(arr);
count := arr.count;
basic.array_add(arr, ..values,, allocator = arr.allocator);
return *arr.data[count];
}
append :: inline (arr: *[..]$T) -> *T {
mem.lazy_set_allocator(arr);
return basic.array_add(arr,, allocator = arr.allocator);
}
resize :: inline (arr: *[..]$T, new_count: int) {
mem.lazy_set_allocator(arr);
if new_count <= arr.allocated return;
basic.array_reserve(arr, new_count,, allocator = arr.allocator);
}
remove_ordered :: inline (arr: *[..]$T, index: int, loc := #caller_location) #no_abc {
meta.check_bounds(index, arr.count, loc = loc);
memcpy(arr.data + index, arr.data + index + 1, (arr.count - index - 1) * size_of(T));
arr.count -= 1;
}
remove_unordered :: inline (arr: *[..]$T, index: int, loc := #caller_location) #no_abc {
meta.check_bounds(index, arr.count, loc = loc);
arr.data[index] = arr.data[arr.count - 1];
arr.count -= 1;
}
reset :: inline (arr: *[..]$T) {
arr.count = 0;
}
find :: (a: [..]$T, $predicate: (T) -> bool) -> T, bool, int {
for a if inline predicate(it) return it, true, it_index;
return mem.undefined_of(T), false, -1;
}
find_pointer :: (a: *[..]$T, $predicate: (T) -> bool) -> *T, bool, int {
for * a if inline predicate(it.*) return it, true, it_index;
return null, false, -1;
}
#scope_file;
mem :: #import "jc/memory";
meta :: #import "jc/meta";
basic :: #import "Basic"; // @future
#if RUN_TESTS #run {
test.run("remove_ordered", t => {
a: [..]int;
append(*a, 10, 20, 30);
remove_ordered(*a, 1);
test.expect(t, a.count == 2);
test.expect(t, a.data[0] == 10);
test.expect(t, a.data[1] == 30);
remove_ordered(*a, 0);
test.expect(t, a.count == 1);
test.expect(t, a.data[0] == 30);
remove_ordered(*a, 0);
test.expect(t, a.count == 0);
append(*a, 10);
test.expect(t, a.count == 1);
test.expect(t, a.data[0] == 10);
});
test.run("remove_unordered", t => {
a: [..]int;
append(*a, 10, 20, 30);
remove_unordered(*a, 1);
test.expect(t, a.count == 2);
test.expect(t, a.data[0] == 10);
test.expect(t, a.data[1] == 30);
remove_unordered(*a, 0);
test.expect(t, a.count == 1);
test.expect(t, a.data[0] == 30);
remove_unordered(*a, 0);
test.expect(t, a.count == 0);
append(*a, 10);
test.expect(t, a.count == 1);
test.expect(t, a.data[0] == 10);
});
}