From ec9ac7715ab658d3e6a42c4e05ece5825d4ef08a Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sun, 1 Oct 2023 07:21:09 +0300 Subject: [PATCH] builtin: add an `unsafe { a.reset() }` method, for quickly setting all bytes in an array to 0 --- vlib/builtin/array.v | 10 ++++++++++ vlib/builtin/array_test.v | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 1276fd9ed3..9ec29d3d6c 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -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 diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index 9d68f9b710..085a422af6 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -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 } + } +}