arrays: add generic copy fn (#13677)

pull/13685/head
Nick Treleaven 2022-03-08 07:44:04 +00:00 committed by GitHub
parent beb1b8ce1b
commit 17fcc788f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 2 deletions

View File

@ -530,3 +530,15 @@ fn swap_nonoverlapping<T>(x_ &T, y_ &T, count int) {
memswap(x, y, len) memswap(x, y, len)
} }
} }
// copy copies the `src` array elements to the `dst` array.
// The number of the elements copied is the minimum of the length of both arrays.
// Returns the number of elements copied.
pub fn copy<T>(dst []T, src []T) int {
min := if dst.len < src.len { dst.len } else { src.len }
if min > 0 {
blen := min * int(sizeof(T))
unsafe { vmemmove(&T(dst.data), src.data, blen) }
}
return min
}

View File

@ -264,3 +264,20 @@ fn test_rotate_left_string() {
rotate_left(mut x, 2) rotate_left(mut x, 2)
assert x == ['x3', 'x4', 'x5', 'x6', 'x1', 'x2'] assert x == ['x3', 'x4', 'x5', 'x6', 'x1', 'x2']
} }
fn test_copy() {
mut a := [1, 2, 3]
mut b := [4, 5, 6]
assert copy(b, a) == 3
assert b == [1, 2, 3]
// check independent copies
b[0] = 99
assert a[0] == 1
// check longer src
b << 7
assert copy(a, b) == 3
assert a == [99, 2, 3]
// check longer dst
assert copy(b, [8, 9]) == 2
assert b == [8, 9, 3, 7]
}

View File

@ -815,11 +815,11 @@ pub fn (b []byte) hex() string {
// The number of the elements copied is the minimum of the length of both arrays. // The number of the elements copied is the minimum of the length of both arrays.
// Returns the number of elements copied. // Returns the number of elements copied.
// NOTE: This is not an `array` method. It is a function that takes two arrays of bytes. // NOTE: This is not an `array` method. It is a function that takes two arrays of bytes.
// TODO: implement for all types // See also: `arrays.copy`.
pub fn copy(dst []byte, src []byte) int { pub fn copy(dst []byte, src []byte) int {
min := if dst.len < src.len { dst.len } else { src.len } min := if dst.len < src.len { dst.len } else { src.len }
if min > 0 { if min > 0 {
unsafe { vmemcpy(&byte(dst.data), src.data, min) } unsafe { vmemmove(&byte(dst.data), src.data, min) }
} }
return min return min
} }