From dc8b82e9a4da97316b2b5dde8b30f50af79f7c78 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 19 Jun 2020 19:32:55 +0800 Subject: [PATCH] array: fix multiple array clone --- vlib/builtin/array.v | 12 +++++++++++- vlib/builtin/array_test.v | 10 ++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 7e60133cb1..c3c0a69499 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -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 } diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index 4c3cea21b9..1b4a958c95 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -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 {