Zero memory in small_array.resize and add non_zero_resize

This commit is contained in:
Damian Tarnawski
2025-09-15 14:40:58 +02:00
parent 935d9657a3
commit 3d66625de0

View File

@@ -2,6 +2,7 @@ package container_small_array
import "base:builtin"
import "base:runtime"
import "core:mem"
_ :: runtime
/*
@@ -250,6 +251,8 @@ set :: proc "contextless" (a: ^$A/Small_Array($N, $T), index: int, item: T) {
/*
Tries to resize the small-array to the specified length.
The memory of added elements will be zeroed out.
The new length will be:
- `length` if `length` <= capacity
- capacity if length > capacity
@@ -259,7 +262,7 @@ The new length will be:
- `length`: The new desired length
Example:
import "core:container/small_array"
import "core:fmt"
@@ -269,7 +272,7 @@ Example:
small_array.push_back(&a, 1)
small_array.push_back(&a, 2)
fmt.println(small_array.slice(&a))
small_array.resize(&a, 1)
fmt.println(small_array.slice(&a))
@@ -278,12 +281,56 @@ Example:
}
Output:
[1, 2]
[1]
[1, 2, 0, 0, 0]
*/
resize :: proc "contextless" (a: ^$A/Small_Array, length: int) {
prev_len := a.len
a.len = min(length, builtin.len(a.data))
if prev_len < a.len {
mem.zero_slice(a.data[prev_len:a.len])
}
}
/*
Tries to resize the small-array to the specified length.
The new length will be:
- `length` if `length` <= capacity
- capacity if length > capacity
**Inputs**
- `a`: A pointer to the small-array
- `length`: The new desired length
Example:
import "core:container/small_array"
import "core:fmt"
resize_example :: proc() {
a: small_array.Small_Array(5, int)
small_array.push_back(&a, 1)
small_array.push_back(&a, 2)
fmt.println(small_array.slice(&a))
small_array.resize(&a, 1)
fmt.println(small_array.slice(&a))
small_array.resize(&a, 100)
fmt.println(small_array.slice(&a))
}
Output:
[1, 2]
[1]
[1, 2, 0, 0, 0]
*/
non_zero_resize :: proc "contextless" (a: ^$A/Small_Array, length: int) {
a.len = min(length, builtin.len(a.data))
}