mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
arrays: move carray_to_varray from builtin, make it generic (#15503)
This commit is contained in:
parent
2dde7ff5ba
commit
9dd8228f91
@ -570,3 +570,12 @@ fn can_copy_bits<T>() bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// carray_to_varray copies a C byte array into a V array of type `T`.
|
||||
// See also: `cstring_to_vstring`
|
||||
[unsafe]
|
||||
pub fn carray_to_varray<T>(c_array voidptr, c_array_len int) []T {
|
||||
mut v_array := []T{len: c_array_len}
|
||||
unsafe { vmemcpy(v_array.data, c_array, c_array_len * int(sizeof(T))) }
|
||||
return v_array
|
||||
}
|
||||
|
@ -126,15 +126,6 @@ fn new_array_from_c_array_no_alloc(len int, cap int, elm_size int, c_array voidp
|
||||
return arr
|
||||
}
|
||||
|
||||
// carray_to_varray copies a C byte array into a V `u8` array.
|
||||
// See also: `cstring_to_vstring`
|
||||
[unsafe]
|
||||
pub fn carray_to_varray(c_array voidptr, c_array_len int) []u8 {
|
||||
mut v_array := []u8{len: c_array_len}
|
||||
unsafe { vmemcpy(v_array.data, c_array, c_array_len * int(sizeof(u8))) }
|
||||
return v_array
|
||||
}
|
||||
|
||||
// Private function. Increases the `cap` of an array to the
|
||||
// required value by copying the data to a new memory location
|
||||
// (creating a clone) unless `a.cap` is already large enough.
|
||||
|
@ -6,3 +6,10 @@ void* gen_c_array(int size) {
|
||||
return c_array;
|
||||
}
|
||||
|
||||
void* gen_c_int_array(int size) {
|
||||
int *c_array = malloc(size);
|
||||
for(int i = 0; i < size; i++) {
|
||||
c_array[i] = i & 0xFF;
|
||||
}
|
||||
return c_array;
|
||||
}
|
||||
|
@ -1,14 +1,26 @@
|
||||
import arrays
|
||||
|
||||
#insert "@VEXEROOT/vlib/v/tests/c_array_test.c"
|
||||
|
||||
fn C.gen_c_array(size int) voidptr
|
||||
|
||||
fn C.gen_c_int_array(size int) voidptr
|
||||
|
||||
fn test_carray_to_varray() {
|
||||
size := 10
|
||||
mut c_array := C.gen_c_array(size)
|
||||
v_array := unsafe { carray_to_varray(c_array, size) }
|
||||
v_u8_array := unsafe { arrays.carray_to_varray<u8>(c_array, size) }
|
||||
unsafe { C.free(c_array) }
|
||||
assert v_array.len == size
|
||||
for i, elem in v_array {
|
||||
assert v_u8_array.len == size
|
||||
for i, elem in v_u8_array {
|
||||
assert elem == i
|
||||
}
|
||||
|
||||
c_int_array := C.gen_c_int_array(size)
|
||||
v_int_array := unsafe { arrays.carray_to_varray<int>(c_int_array, size) }
|
||||
unsafe { C.free(c_int_array) }
|
||||
assert v_int_array.len == size
|
||||
for i, elem in v_int_array {
|
||||
assert elem == i
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user