From fae601fe39eba91f47ef2aed64e74ab6a0c4bdb6 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 11 Jul 2020 19:17:11 +0800 Subject: [PATCH] array: add `reverse_in_place` for performance (#5798) --- vlib/builtin/array.v | 15 +++++++++++++++ vlib/builtin/array_test.v | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 6fb2c6bdc6..f2088df01f 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -400,6 +400,21 @@ pub fn (mut a3 array) push_many(val voidptr, size int) { a3.len += size } +pub fn (mut a array) reverse_in_place() { + if a.len < 2 { + return + } + unsafe { + mut tmp_value := malloc(a.element_size) + for i in 0..a.len/2 { + C.memcpy(tmp_value, byteptr(a.data) + i * a.element_size, a.element_size) + C.memcpy(byteptr(a.data) + i * a.element_size, byteptr(a.data) + (a.len-1-i) * a.element_size, a.element_size) + C.memcpy(byteptr(a.data) + (a.len-1-i) * a.element_size, tmp_value, a.element_size) + } + free(tmp_value) + } +} + // array.reverse returns a new array with the elements of // the original array in reverse order. pub fn (a array) reverse() array { diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index eb3e0fdf6f..06f1f78e3a 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -932,3 +932,17 @@ fn test_array_add_in_mut() { add_nums(mut nums) assert nums == [1, 2, 3, 4] } + +fn test_reverse_in_place() { + mut a := [1, 2, 3, 4] + a.reverse_in_place() + assert a == [4, 3, 2, 1] + + mut b := ['a', 'b', 'c'] + b.reverse_in_place() + assert b == ['c', 'b', 'a'] + + mut c := [[1, 2], [3, 4], [5, 6]] + c.reverse_in_place() + assert c == [[5, 6], [3, 4], [1, 2]] +}