mirror of
https://github.com/vlang/v.git
synced 2025-09-08 06:41:58 -04:00
builtin: add an unsafe { a.reset() }
method, for quickly setting all bytes in an array to 0
This commit is contained in:
parent
413da8be62
commit
ec9ac7715a
@ -389,6 +389,16 @@ pub fn (mut a array) clear() {
|
||||
a.len = 0
|
||||
}
|
||||
|
||||
// reset quickly sets the bytes of all elements of the array to 0.
|
||||
// Useful mainly for numeric arrays. Note, that calling reset()
|
||||
// is not safe, when your array contains more complex elements,
|
||||
// like structs, maps, pointers etc, since setting them to 0,
|
||||
// can later lead to hard to find bugs.
|
||||
[unsafe]
|
||||
pub fn (mut a array) reset() {
|
||||
unsafe { vmemset(a.data, 0, a.len * a.element_size) }
|
||||
}
|
||||
|
||||
// trim trims the array length to `index` without modifying the allocated data.
|
||||
// If `index` is greater than `len` nothing will be changed.
|
||||
// Example: a.trim(3) // `a.len` is now <= 3
|
||||
|
@ -1622,3 +1622,23 @@ fn test_array_of_struct_with_map_field() {
|
||||
2: 2
|
||||
}
|
||||
}
|
||||
|
||||
fn test_reset() {
|
||||
mut a := []int{len: 5, init: index * 10}
|
||||
assert a == [0, 10, 20, 30, 40]
|
||||
unsafe { a.reset() }
|
||||
assert a == [0, 0, 0, 0, 0]
|
||||
|
||||
mut b := []f64{len: 5, init: f64(index) / 10.0}
|
||||
assert b == [0.0, 0.1, 0.2, 0.3, 0.4]
|
||||
unsafe { b.reset() }
|
||||
assert b == [0.0, 0.0, 0.0, 0.0, 0.0]
|
||||
|
||||
mut s := []string{len: 5, init: index.str()}
|
||||
assert s == ['0', '1', '2', '3', '4']
|
||||
unsafe { s.reset() }
|
||||
for e in s {
|
||||
assert e.str == unsafe { nil }
|
||||
assert e.len == unsafe { nil }
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user