array: add `reverse_in_place` for performance (#5798)
parent
b92ce38593
commit
fae601fe39
|
@ -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 {
|
||||
|
|
|
@ -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]]
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue