| 1 |
type t = |
| 2 |
{ len : int |
| 3 |
; bits : Bytes.t |
| 4 |
} |
| 5 |
|
| 6 |
let byte s i = Char.code (Bytes.unsafe_get s i) |
| 7 |
let set_byte s i x = Bytes.unsafe_set s i (Char.chr x) |
| 8 |
let length t = t.len |
| 9 |
|
| 10 |
let unsafe_set v n b = |
| 11 |
let i = n lsr 3 in |
| 12 |
let c = byte v.bits i in |
| 13 |
let mask = 1 lsl (n land 7) in |
| 14 |
set_byte v.bits i (if b then c lor mask else c land lnot mask) |
| 15 |
;; |
| 16 |
|
| 17 |
let set v n b = |
| 18 |
if n < 0 || n >= v.len then invalid_arg "Bit_vector.set"; |
| 19 |
unsafe_set v n b |
| 20 |
;; |
| 21 |
|
| 22 |
let unsafe_get v n = |
| 23 |
let i = n lsr 3 in |
| 24 |
byte v.bits i land (1 lsl (n land 7)) > 0 |
| 25 |
;; |
| 26 |
|
| 27 |
let get v n = |
| 28 |
if n < 0 || n >= v.len then invalid_arg "Bit_vector.get"; |
| 29 |
unsafe_get v n |
| 30 |
;; |
| 31 |
|
| 32 |
let reset_zero t = Bytes.fill t.bits 0 (Bytes.length t.bits) '\000' |
| 33 |
|
| 34 |
let create_zero len = |
| 35 |
let bits = |
| 36 |
let r = len land 7 in |
| 37 |
let q = len lsr 3 in |
| 38 |
let len = if r = 0 then q else q + 1 in |
| 39 |
Bytes.make len '\000' |
| 40 |
in |
| 41 |
{ len; bits } |
| 42 |
;; |
| 43 |
|
| 44 |
let pp fmt { len; bits } = |
| 45 |
let len fmt () = Fmt.sexp fmt "len" Fmt.int len in |
| 46 |
let bits fmt () = Fmt.sexp fmt "bits" Fmt.bytes bits in |
| 47 |
Format.fprintf fmt "%a@.%a@." len () bits () |
| 48 |
;; |