Skip to content

Commit

Permalink
Add CArray.copy
Browse files Browse the repository at this point in the history
  • Loading branch information
yallop committed Sep 19, 2016
1 parent 3acdde2 commit 9638eb3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/ctypes/ctypes.mli
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,11 @@ sig
used to initialise every element of the array. The argument [?finalise],
if present, will be called just before the memory is freed. *)

val copy : 'a t -> 'a t
(** [copy a] creates a fresh array with the same elements as [a]. *)

val element_type : 'a t -> 'a typ
(** Retrieve the element type of an array. *)
(** Retrieve the element type of an array. *)
end
(** Operations on C arrays. *)

Expand Down
8 changes: 8 additions & 0 deletions src/ctypes/ctypes_memory.ml
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,14 @@ struct
| None -> arr
| Some v -> fill arr v; arr

let copy {astart = CPointer src; alength} =
begin
let reftyp = Fat.reftype src in
let CPointer dst as r = allocate_n reftyp alength in
let () = Stubs.memcpy ~dst ~src ~size:(alength * sizeof reftyp) in
from_ptr r alength
end

let element_type { astart } = reference_type astart

let of_list typ list =
Expand Down
21 changes: 21 additions & 0 deletions tests/test-arrays/test_array.ml
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,24 @@ let test_fold_right _ =
let r = CArray.fold_right (fun _ -> assert false) a [] in
assert_equal r []

(*
Test the CArray.copy function
*)
let test_copy _ =
let a = CArray.of_list int [1; 2; 3] in
let r = CArray.copy a in

begin
assert_equal [1; 2; 3] (CArray.to_list a);
assert_equal [1; 2; 3] (CArray.to_list r);
CArray.set r 0 10;
assert_equal [1; 2; 3] (CArray.to_list a);
assert_equal [10; 2; 3] (CArray.to_list r);
CArray.set a 1 20;
assert_equal [1; 20; 3] (CArray.to_list a);
assert_equal [10; 2; 3] (CArray.to_list r);
end


(*
Test that creating an array initializes all elements appropriately.
Expand Down Expand Up @@ -286,6 +304,9 @@ let suite = "Array tests" >:::
"CArray.fold_right"
>:: test_fold_right;

"CArray.copy"
>:: test_copy;

"array initialization"
>:: test_array_initialiation;

Expand Down

0 comments on commit 9638eb3

Please sign in to comment.