array: fix multiple array clone

pull/5423/head
yuyi 2020-06-19 19:32:55 +08:00 committed by GitHub
parent 8a5ca4cbdc
commit dc8b82e9a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 1 deletions

View File

@ -282,7 +282,17 @@ pub fn (a &array) clone() array {
len: a.len
cap: a.cap
}
C.memcpy(byteptr(arr.data), a.data, a.cap * a.element_size)
// Recursively clone-generated elements if array element is array type
if a.element_size == sizeof(array) {
for i in 0..a.len {
ar := array{}
C.memcpy(&ar, byteptr(a.data) + i * a.element_size, sizeof(array))
ar_clone := ar.clone()
C.memcpy(byteptr(arr.data) + i * a.element_size, &ar_clone, a.element_size)
}
} else {
C.memcpy(byteptr(arr.data), a.data, a.cap * a.element_size)
}
return arr
}

View File

@ -361,6 +361,16 @@ fn test_clone() {
assert nums.slice(1, 3).str() == '[2, 3]'
}
fn test_mutli_array_clone() {
mut array1 := [[1, 2, 3], [4, 5, 6]]
mut array2 := array1.clone()
array1[0][1] = 0
assert array1 == [[1, 0, 3], [4, 5, 6]]
assert array2 == [[1, 2, 3], [4, 5, 6]]
}
fn test_doubling() {
mut nums := [1, 2, 3, 4, 5]
for i in 0..nums.len {