diff --git a/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.ml b/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.ml index e89cefba3da..c290ab8e569 100644 --- a/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.ml +++ b/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.ml @@ -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 diff --git a/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.mli b/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.mli index d836c751230..231c3891060 100644 --- a/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.mli +++ b/ocaml/libs/xapi-stdext/lib/xapi-stdext-std/listext.mli @@ -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 diff --git a/ocaml/xapi-idl/xen/device_number.ml b/ocaml/xapi-idl/xen/device_number.ml index 31943b7e123..2233354b030 100644 --- a/ocaml/xapi-idl/xen/device_number.ml +++ b/ocaml/xapi-idl/xen/device_number.ml @@ -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] @@ -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 diff --git a/ocaml/xapi-idl/xen/dune b/ocaml/xapi-idl/xen/dune index 7f19e4a2714..16ed23ecd22 100644 --- a/ocaml/xapi-idl/xen/dune +++ b/ocaml/xapi-idl/xen/dune @@ -11,6 +11,7 @@ sexplib0 threads xapi-idl + xapi-stdext-std ) (wrapped false) (preprocess (pps ppx_deriving_rpc ppx_sexp_conv)))