3135c8945736e6da547c56aa386e6d930a9a8cf0
[ocaml-bitstring.git] / bitmatch.ml
1 (* Bitmatch library.
2  * $Id: bitmatch.ml,v 1.1 2008-03-31 22:52:17 rjones Exp $
3  *)
4
5 (* A bitstring is simply the data itself (as a string), and the
6  * bitoffset and the bitlength within the string.  Note offset/length
7  * are counted in bits, not bytes.
8  *)
9 type bitstring = string * int * int
10
11 (* Functions to create and load bitstrings. *)
12 let empty_bitstring = "", 0, 0
13
14 let make_bitstring len c = String.make ((len+7) lsr 3) c, 0, len
15
16 let create_bitstring len = make_bitstring len '\000'
17
18 let bitstring_of_chan chan =
19   let tmpsize = 16384 in
20   let buf = Buffer.create tmpsize in
21   let tmp = String.create tmpsize in
22   let n = ref 0 in
23   while n := input chan tmp 0 tmpsize; !n > 0 do
24     Buffer.add_substring buf tmp 0 !n;
25   done;
26   Buffer.contents buf, 0, Buffer.length buf lsl 3
27
28 let bitstring_of_file fname =
29   let chan = open_in_bin fname in
30   let bs = bitstring_of_chan chan in
31   close_in chan;
32   bs
33
34 (* Extraction functions (internal: called from the generated macros,
35  * and the parameters should have been checked for sanity already).
36  *)
37 let extract_bitstring data off len flen =
38   (data, off, flen), off+flen, len-flen
39
40 let extract_remainder data off len =
41   (data, off, len), off+len, 0
42
43 (* Extract and convert to numeric. *)
44 let extract_bit data off len _ =        (* final param is always 1 *)
45   let byteoff = off lsr 3 in
46   let bitmask = 1 lsl (7 - (off land 7)) in
47   let b = Char.code data.[byteoff] land bitmask <> 0 in
48   b, off+1, len-1