Skip to content

Commit

Permalink
Merge pull request #775 from Ant1-Provot/add-carray-iteri
Browse files Browse the repository at this point in the history
Add CArray.iteri
  • Loading branch information
yallop authored Jun 26, 2024
2 parents c6cd8eb + c61471e commit 4a134bc
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/ctypes/ctypes.mli
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,11 @@ sig
(** [iter f a] is analogous to [Array.iter f a]: it applies [f] in turn to
all the elements of [a]. *)

val iteri : (int -> 'a -> unit) -> 'a t -> unit
(** [iter f a] is analogous to [Array.iteri f a]: it applies [f] in turn to
all the elements of [a] but the function is applied to the index of the
element as first argument, and the element itself as second argument *)

val map : 'b typ -> ('a -> 'b) -> 'a t -> 'b t
(** [map t f a] is analogous to [Array.map f a]: it creates a new array with
element type [t] whose elements are obtained by applying [f] to the
Expand Down
5 changes: 5 additions & 0 deletions src/ctypes/ctypes_memory.ml
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,11 @@ struct
f (unsafe_get a i)
done

let iteri f a =
for i = 0 to length a - 1 do
f i (unsafe_get a i)
done

let map typ f a =
let l = length a in
let r = make typ l in
Expand Down
18 changes: 18 additions & 0 deletions tests/test-arrays/test_array.ml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,21 @@ let test_iter _ =
assert_equal !r 0


(*
Test the CArray.iteri function
*)
let test_iteri _ =
let r = ref 0 in
let a = CArray.of_list int [1; 2; 3] in
let () = CArray.iteri (fun i v -> r := !r + i + v) a in
assert_equal !r 9;

let r = ref 0 in
let a = CArray.of_list int [] in
let () = CArray.iteri (fun _ -> assert false) a in
assert_equal !r 0


(*
Test the CArray.map function
*)
Expand Down Expand Up @@ -370,6 +385,9 @@ let suite = "Array tests" >:::
"CArray.iter "
>:: test_iter;

"CArray.iteri "
>:: test_iteri;

"CArray.map "
>:: test_map;

Expand Down

0 comments on commit 4a134bc

Please sign in to comment.