From dda475bcc8c4168bc45439cb08a844fd59a80c2d Mon Sep 17 00:00:00 2001 From: Larpon Date: Mon, 22 Aug 2022 19:15:54 +0200 Subject: [PATCH] builtin: add carray_to_varray, closes #15493 (#15499) --- vlib/builtin/array.v | 9 +++++++++ vlib/v/tests/c_array_test.c | 8 ++++++++ vlib/v/tests/c_array_test.v | 14 ++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 vlib/v/tests/c_array_test.c create mode 100644 vlib/v/tests/c_array_test.v diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index b2dee67c15..181f09bcbd 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -126,6 +126,15 @@ 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. diff --git a/vlib/v/tests/c_array_test.c b/vlib/v/tests/c_array_test.c new file mode 100644 index 0000000000..dbb60790cc --- /dev/null +++ b/vlib/v/tests/c_array_test.c @@ -0,0 +1,8 @@ +void* gen_c_array(int size) { + unsigned char *c_array = malloc(size); + for(int i = 0; i < size; i++) { + c_array[i] = i & 0xFF; + } + return c_array; +} + diff --git a/vlib/v/tests/c_array_test.v b/vlib/v/tests/c_array_test.v new file mode 100644 index 0000000000..5ec66da8d4 --- /dev/null +++ b/vlib/v/tests/c_array_test.v @@ -0,0 +1,14 @@ +#insert "@VEXEROOT/vlib/v/tests/c_array_test.c" + +fn C.gen_c_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) } + unsafe { C.free(c_array) } + assert v_array.len == size + for i, elem in v_array { + assert elem == i + } +}