Skip to content

Commit 17fcc78

Browse files
authored
arrays: add generic copy fn (#13677)
1 parent beb1b8c commit 17fcc78

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

vlib/arrays/arrays.v

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,3 +530,15 @@ fn swap_nonoverlapping<T>(x_ &T, y_ &T, count int) {
530530
memswap(x, y, len)
531531
}
532532
}
533+
534+
// copy copies the `src` array elements to the `dst` array.
535+
// The number of the elements copied is the minimum of the length of both arrays.
536+
// Returns the number of elements copied.
537+
pub fn copy<T>(dst []T, src []T) int {
538+
min := if dst.len < src.len { dst.len } else { src.len }
539+
if min > 0 {
540+
blen := min * int(sizeof(T))
541+
unsafe { vmemmove(&T(dst.data), src.data, blen) }
542+
}
543+
return min
544+
}

vlib/arrays/arrays_test.v

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,3 +264,20 @@ fn test_rotate_left_string() {
264264
rotate_left(mut x, 2)
265265
assert x == ['x3', 'x4', 'x5', 'x6', 'x1', 'x2']
266266
}
267+
268+
fn test_copy() {
269+
mut a := [1, 2, 3]
270+
mut b := [4, 5, 6]
271+
assert copy(b, a) == 3
272+
assert b == [1, 2, 3]
273+
// check independent copies
274+
b[0] = 99
275+
assert a[0] == 1
276+
// check longer src
277+
b << 7
278+
assert copy(a, b) == 3
279+
assert a == [99, 2, 3]
280+
// check longer dst
281+
assert copy(b, [8, 9]) == 2
282+
assert b == [8, 9, 3, 7]
283+
}

vlib/builtin/array.v

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -815,11 +815,11 @@ pub fn (b []byte) hex() string {
815815
// The number of the elements copied is the minimum of the length of both arrays.
816816
// Returns the number of elements copied.
817817
// NOTE: This is not an `array` method. It is a function that takes two arrays of bytes.
818-
// TODO: implement for all types
818+
// See also: `arrays.copy`.
819819
pub fn copy(dst []byte, src []byte) int {
820820
min := if dst.len < src.len { dst.len } else { src.len }
821821
if min > 0 {
822-
unsafe { vmemcpy(&byte(dst.data), src.data, min) }
822+
unsafe { vmemmove(&byte(dst.data), src.data, min) }
823823
}
824824
return min
825825
}

0 commit comments

Comments
 (0)