Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CArray.iteri #775

Merged
merged 1 commit into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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