array: add `reverse_in_place` for performance (#5798)

pull/5801/head
yuyi 2020-07-11 19:17:11 +08:00 committed by GitHub
parent b92ce38593
commit fae601fe39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -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 {

View File

@ -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]]
}