From 15a42f1f350b7a391ba0317170139f1ce47ff9ef Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Mon, 12 Aug 2019 14:41:34 +0300 Subject: [PATCH] array.clone() --- vlib/builtin/array.v | 11 +++++++++++ vlib/builtin/array_test.v | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 5c7d38ff54..2f1595d177 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -208,6 +208,17 @@ pub fn (a array) reverse() array { return arr } +pub fn (a array) clone() array { + arr := array { + len: a.len + cap: a.cap + element_size: a.element_size + data: malloc(a.cap * a.element_size) + } + C.memcpy(arr.data, a.data, a.cap * a.element_size) + return arr +} + //pub fn (a []int) free() { pub fn (a array) free() { //if a.is_slice { diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index f3c524bbbe..888b9b04a0 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -190,4 +190,12 @@ fn test_mut_slice() { assert n[2] == 777 println(n) } + +fn test_clone() { + nums := [1, 2, 3, 4, 100] + nums2 := nums.clone() + assert nums2.len == 5 + assert nums2.str() == '[1, 2, 3, 4, 100]' + assert nums.slice(1, 3).str() == '[2, 3]' +}