Skip to content

Commit

Permalink
xapi-idl: Refactor out find_index and add it to Listext
Browse files Browse the repository at this point in the history
The function is implemented using foldleft using a weird form, use a recursive
form instead.

Unfortunately the function was introduced in OCaml 5.1, so it had to be moved
to Listext so it can be reused.

Signed-off-by: Pau Ruiz Safont <[email protected]>
  • Loading branch information
psafont committed Jul 31, 2024
1 parent bc511a3 commit 4b691d1
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
11 changes: 11 additions & 0 deletions ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.ml
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,15 @@ module List = struct
let find_minimum compare =
let min a b = if compare a b <= 0 then a else b in
function [] -> None | x :: xs -> Some (List.fold_left min x xs)

let find_index f l =
let rec loop i = function
| [] ->
None
| x :: _ when f x ->
Some i
| _ :: xs ->
loop (i + 1) xs
in
loop 0 l
end
7 changes: 7 additions & 0 deletions ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.mli
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ module List : sig
the sort order of [cmp], or [None] if the list is empty. When two ore
more elements match the lowest value, the left-most is returned. *)

val find_index : ('a -> bool) -> 'a list -> int option
(** [find_index f l] returns the position of the first element in [l] that
satisfies [f x]. If there is no such element, returns [None].
When using OCaml compilers 5.1 or later, please use the standard library
instead. *)

(** {1 Using indices to manipulate lists} *)

val chop : int -> 'a list -> 'a list * 'a list
Expand Down
12 changes: 7 additions & 5 deletions ocaml/xapi-idl/xen/device_number.ml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module Listext = Xapi_stdext_std.Listext.List

type bus_type = Xen | Scsi | Floppy | Ide [@@deriving rpcty]

type t = bus_type * int * int [@@deriving rpcty]
Expand Down Expand Up @@ -76,11 +78,11 @@ let of_xenstore_int x =
(Floppy, (x lsr 4) land ((1 lsl 4) - 1), x land ((1 lsl 4) - 1))
| n ->
let idx =
snd
(List.fold_left
(fun (i, res) e -> (i + 1, if e = n then i else res))
(0, -1) deprecated_ide_table
)
match Listext.find_index (Int.equal n) deprecated_ide_table with
| Some idx ->
idx
| None ->
failwith (Printf.sprintf "Unknown device number: %d" x)
in
let disk = ((x lsr 6) land ((1 lsl 2) - 1)) + (idx * 2) in
let partition = x land ((1 lsl 6) - 1) in
Expand Down
1 change: 1 addition & 0 deletions ocaml/xapi-idl/xen/dune
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
sexplib0
threads
xapi-idl
xapi-stdext-std
)
(wrapped false)
(preprocess (pps ppx_deriving_rpc ppx_sexp_conv)))
Expand Down

0 comments on commit 4b691d1

Please sign in to comment.