From bc80d4be049c499a8c2c09c77cfc6b334129ea07 Mon Sep 17 00:00:00 2001 From: John Soo Date: Sun, 1 Aug 2021 23:09:52 -0700 Subject: [PATCH] common: Add Bitwise functor for bitwise enums. --- common/bitwise.ml | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 common/bitwise.ml diff --git a/common/bitwise.ml b/common/bitwise.ml new file mode 100644 index 0000000..5fe02be --- /dev/null +++ b/common/bitwise.ml @@ -0,0 +1,40 @@ +open Ctypes + +module type Size = sig + type t + val zero : t + val logor : t -> t -> t + val logand : t -> t -> t +end + +module type Elems = sig + type t + module Size : Size + val size : Size.t typ + val desc : (t * Size.t) list +end + +module type Enum = sig + type elem + type t + val t : t +end + +module Make (E : Elems) : Enum = struct + type elem = E.t + type t = E.t list typ + let t : t = + let read i = + List.filter_map (fun (x, cst) -> + if (E.Size.logand i cst) <> E.Size.zero then + Some x + else None + ) E.desc + in + let write items = + List.fold_left (fun i item -> + E.Size.logor (List.assoc item E.desc) i + ) E.Size.zero items + in + view ~read ~write E.size +end