Skip to content

Commit bc80d4b

Browse files
committed
common: Add Bitwise functor for bitwise enums.
1 parent a8dee0b commit bc80d4b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

common/bitwise.ml

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
open Ctypes
2+
3+
module type Size = sig
4+
type t
5+
val zero : t
6+
val logor : t -> t -> t
7+
val logand : t -> t -> t
8+
end
9+
10+
module type Elems = sig
11+
type t
12+
module Size : Size
13+
val size : Size.t typ
14+
val desc : (t * Size.t) list
15+
end
16+
17+
module type Enum = sig
18+
type elem
19+
type t
20+
val t : t
21+
end
22+
23+
module Make (E : Elems) : Enum = struct
24+
type elem = E.t
25+
type t = E.t list typ
26+
let t : t =
27+
let read i =
28+
List.filter_map (fun (x, cst) ->
29+
if (E.Size.logand i cst) <> E.Size.zero then
30+
Some x
31+
else None
32+
) E.desc
33+
in
34+
let write items =
35+
List.fold_left (fun i item ->
36+
E.Size.logor (List.assoc item E.desc) i
37+
) E.Size.zero items
38+
in
39+
view ~read ~write E.size
40+
end

0 commit comments

Comments
 (0)