Somewhat better attempt at a META file.
[ocaml-bitstring.git] / bitmatch.mli
1 (** Bitmatch library. *)
2 (* Copyright (C) 2008 Red Hat Inc., Richard W.M. Jones
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *
18  * $Id$
19  *)
20
21 (**
22    {{:#reference}Jump straight to the reference section for
23    documentation on types and functions}.
24
25    {2 Introduction}
26
27    Bitmatch adds Erlang-style bitstrings and matching over bitstrings
28    as a syntax extension and library for OCaml.  You can use
29    this module to both parse and generate binary formats, for
30    example, communications protocols, disk formats and binary files.
31
32    {{:http://code.google.com/p/bitmatch/}OCaml bitmatch website}
33
34    {2 Examples}
35
36    A function which can parse IPv4 packets:
37
38 {[
39 let display pkt =
40   bitmatch pkt with
41   (* IPv4 packet header
42     0                   1                   2                   3   
43     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
44    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
45    |   4   |  IHL  |Type of Service|          Total Length         |
46    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
47    |         Identification        |Flags|      Fragment Offset    |
48    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
49    |  Time to Live |    Protocol   |         Header Checksum       |
50    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
51    |                       Source Address                          |
52    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
53    |                    Destination Address                        |
54    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
55    |                    Options                    |    Padding    |
56    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
57   *)
58   | { 4 : 4; hdrlen : 4; tos : 8;   length : 16;
59       identification : 16;          flags : 3; fragoffset : 13;
60       ttl : 8; protocol : 8;        checksum : 16;
61       source : 32;
62       dest : 32;
63       options : (hdrlen-5)*32 : bitstring;
64       payload : -1 : bitstring } ->
65
66     printf "IPv4:\n";
67     printf "  header length: %d * 32 bit words\n" hdrlen;
68     printf "  type of service: %d\n" tos;
69     printf "  packet length: %d bytes\n" length;
70     printf "  identification: %d\n" identification;
71     printf "  flags: %d\n" flags;
72     printf "  fragment offset: %d\n" fragoffset;
73     printf "  ttl: %d\n" ttl;
74     printf "  protocol: %d\n" protocol;
75     printf "  checksum: %d\n" checksum;
76     printf "  source: %lx  dest: %lx\n" source dest;
77     printf "  header options + padding:\n";
78     Bitmatch.hexdump_bitstring stdout options;
79     printf "  packet payload:\n";
80     Bitmatch.hexdump_bitstring stdout payload
81
82   | { version : 4 } ->
83     eprintf "unknown IP version %d\n" version;
84     exit 1
85
86   | { _ } as pkt ->
87     eprintf "data is smaller than one nibble:\n";
88     Bitmatch.hexdump_bitstring stderr pkt;
89     exit 1
90 ]}
91
92    A program which can parse
93    {{:http://lxr.linux.no/linux/include/linux/ext3_fs.h}Linux EXT3 filesystem superblocks}:
94
95 {[
96 let bits = Bitmatch.bitstring_of_file "tests/ext3_sb"
97
98 let () =
99   bitmatch bits with
100   | { s_inodes_count : 32 : littleendian;       (* Inodes count *)
101       s_blocks_count : 32 : littleendian;       (* Blocks count *)
102       s_r_blocks_count : 32 : littleendian;     (* Reserved blocks count *)
103       s_free_blocks_count : 32 : littleendian;  (* Free blocks count *)
104       s_free_inodes_count : 32 : littleendian;  (* Free inodes count *)
105       s_first_data_block : 32 : littleendian;   (* First Data Block *)
106       s_log_block_size : 32 : littleendian;     (* Block size *)
107       s_log_frag_size : 32 : littleendian;      (* Fragment size *)
108       s_blocks_per_group : 32 : littleendian;   (* # Blocks per group *)
109       s_frags_per_group : 32 : littleendian;    (* # Fragments per group *)
110       s_inodes_per_group : 32 : littleendian;   (* # Inodes per group *)
111       s_mtime : 32 : littleendian;              (* Mount time *)
112       s_wtime : 32 : littleendian;              (* Write time *)
113       s_mnt_count : 16 : littleendian;          (* Mount count *)
114       s_max_mnt_count : 16 : littleendian;      (* Maximal mount count *)
115       0xef53 : 16 : littleendian } ->           (* Magic signature *)
116
117     printf "ext3 superblock:\n";
118     printf "  s_inodes_count = %ld\n" s_inodes_count;
119     printf "  s_blocks_count = %ld\n" s_blocks_count;
120     printf "  s_free_inodes_count = %ld\n" s_free_inodes_count;
121     printf "  s_free_blocks_count = %ld\n" s_free_blocks_count
122
123   | { _ } ->
124     eprintf "not an ext3 superblock!\n%!";
125     exit 2
126 ]}
127
128    Constructing packets for a simple binary message
129    protocol:
130
131 {[
132 (*
133   +---------------+---------------+--------------------------+
134   | type          | subtype       | parameter                |
135   +---------------+---------------+--------------------------+
136    <-- 16 bits --> <-- 16 bits --> <------- 32 bits -------->
137
138   All fields are in network byte order.
139 *)
140
141 let make_message typ subtype param =
142   (BITSTRING {
143      typ : 16;
144      subtype : 16;
145      param : 32
146    }) ;;
147 ]}
148
149    {2 Loading, creating bitstrings}
150
151    The basic data type is the {!bitstring}, a string of bits of
152    arbitrary length.  Bitstrings can be any length in bits and
153    operations do not need to be byte-aligned (although they will
154    generally be more efficient if they are byte-aligned).
155
156    Internally a bitstring is stored as a normal OCaml [string]
157    together with an offset and length, where the offset and length are
158    measured in bits.  Thus one can efficiently form substrings of
159    bitstrings, overlay a bitstring on existing data, and load and save
160    bitstrings from files or other external sources.
161
162    To load a bitstring from a file use {!bitstring_of_file} or
163    {!bitstring_of_chan}.
164
165    There are also functions to create bitstrings from arbitrary data.
166    See the {{:#reference}reference} below.
167
168    {2 Matching bitstrings with patterns}
169
170    Use the [bitmatch] operator (part of the syntax extension) to break
171    apart a bitstring into its fields.  [bitmatch] works a lot like the
172    OCaml [match] operator.
173
174    The general form of [bitmatch] is:
175
176    [bitmatch] {i bitstring-expression} [with]
177
178    [| {] {i pattern} [} ->] {i code}
179
180    [| {] {i pattern} [} ->] {i code}
181
182    [|] ...
183
184    As with normal match, the statement attempts to match the
185    bitstring against each pattern in turn.  If none of the patterns
186    match then the standard library [Match_failure] exception is
187    thrown.
188
189    Patterns look a bit different from normal match patterns.  They
190    consist of a list of bitfields separated by [;] where each bitfield
191    contains a bind variable, the width (in bits) of the field, and
192    other information.  Some example patterns:
193
194 {[
195 bitmatch bits with
196
197 | { version : 8; name : 8; param : 8 } -> ...
198
199    (* Bitstring of at least 3 bytes.  First byte is the version
200       number, second byte is a field called name, third byte is
201       a field called parameter. *)
202
203 | { flag : 1 } ->
204    printf "flag is %b\n" flag
205
206    (* A single flag bit (mapped into an OCaml boolean). *)
207
208 | { len : 4; data : 1+len } ->
209    printf "len = %d, data = 0x%Lx\n" len data
210
211    (* A 4-bit length, followed by 1-16 bits of data, where the
212       length of the data is computed from len. *)
213
214 | { ipv6_source : 128 : bitstring;
215     ipv6_dest : 128 : bitstring } -> ...
216
217    (* IPv6 source and destination addresses.  Each is 128 bits
218       and is mapped into a bitstring type which will be a substring
219       of the main bitstring expression. *)
220 ]}
221
222    You can also add conditional when-clauses:
223
224 {[
225 | { version : 4 }
226     when version = 4 || version = 6 -> ...
227
228    (* Only match and run the code when version is 4 or 6.  If
229       it isn't we will drop through to the next case. *)
230 ]}
231
232    Note that the pattern is only compared against the first part of
233    the bitstring (there may be more data in the bitstring following
234    the pattern, which is not matched).  In terms of regular
235    expressions you might say that the pattern matches [^pattern], not
236    [^pattern$].  To ensure that the bitstring contains only the
237    pattern, add a length -1 bitstring to the end and test that its
238    length is zero in the when-clause:
239
240 {[
241 | { n : 4;
242     rest : -1 : bitstring }
243     when Bitmatch.bitstring_length rest = 0 -> ...
244
245    (* Only matches exactly 4 bits. *)
246 ]}
247
248    Normally the first part of each field is a binding variable,
249    but you can also match a constant, as in:
250
251 {[
252 | { (4|6) : 4 } -> ...
253
254    (* Only matches if the first 4 bits contain either
255       the integer 4 or the integer 6. *)
256 ]}
257
258    One may also match on strings:
259
260 {[
261 | { "MAGIC" : 5*8 : string } -> ...
262
263    (* Only matches if the string "MAGIC" appears at the start
264       of the input. *)
265 ]}
266
267    {3:patternfieldreference Pattern field reference}
268
269    The exact format of each pattern field is:
270
271    [pattern : length [: qualifier [,qualifier ...]]]
272
273    [pattern] is the pattern, binding variable name, or constant to
274    match.  [length] is the length in bits which may be either a
275    constant or an expression.  The length expression is just an OCaml
276    expression and can use any values defined in the program, and refer
277    back to earlier fields (but not to later fields).
278
279    Integers can only have lengths in the range \[1..64\] bits.  See the
280    {{:#integertypes}integer types} section below for how these are
281    mapped to the OCaml int/int32/int64 types.  This is checked
282    at compile time if the length expression is constant, otherwise it is
283    checked at runtime and you will get a runtime exception eg. in
284    the case of a computed length expression.
285
286    A bitstring field of length -1 matches all the rest of the
287    bitstring (thus this is only useful as the last field in a
288    pattern).
289
290    A bitstring field of length 0 matches an empty bitstring
291    (occasionally useful when matching optional subfields).
292
293    Qualifiers are a list of identifiers/expressions which control the type,
294    signedness and endianness of the field.  Permissible qualifiers are:
295
296    - [int]: field has an integer type
297    - [string]: field is a string type
298    - [bitstring]: field is a bitstring type
299    - [signed]: field is signed
300    - [unsigned]: field is unsigned
301    - [bigendian]: field is big endian - a.k.a network byte order
302    - [littleendian]: field is little endian - a.k.a Intel byte order
303    - [nativeendian]: field is same endianness as the machine
304    - [endian (expr)]: [expr] should be an expression which evaluates to
305        a {!endian} type, ie. [LittleEndian], [BigEndian] or [NativeEndian].
306        The expression is an arbitrary OCaml expression and can use the
307        value of earlier fields in the bitmatch.
308    - [offset (expr)]: see {{:#computedoffsets}computed offsets} below.
309
310    The default settings are [int], [unsigned], [bigendian], no offset.
311
312    Note that many of these qualifiers cannot be used together,
313    eg. bitstrings do not have endianness.  The syntax extension should
314    give you a compile-time error if you use incompatible qualifiers.
315
316    {3 Other cases in bitmatch}
317
318    As well as a list of fields, it is possible to name the
319    bitstring and/or have a default match case:
320
321 {[
322 | { _ } -> ...
323
324    (* Default match case. *)
325
326 | { _ } as pkt -> ...
327
328    (* Default match case, with 'pkt' bound to the whole bitstring. *)
329 ]}
330
331    {2 Constructing bitstrings}
332
333    Bitstrings may be constructed using the [BITSTRING] operator (as an
334    expression).  The [BITSTRING] operator takes a list of fields,
335    similar to the list of fields for matching:
336
337 {[
338 let version = 1 ;;
339 let data = 10 ;;
340 let bits =
341   BITSTRING {
342     version : 4;
343     data : 12
344   } ;;
345
346    (* Constructs a 16-bit bitstring with the first four bits containing
347       the integer 1, and the following 12 bits containing the integer 10,
348       arranged in network byte order. *)
349
350 Bitmatch.hexdump_bitstring stdout bits ;;
351
352    (* Prints:
353
354       00000000  10 0a         |..              |
355     *)
356 ]}
357
358    The format of each field is the same as for pattern fields (see
359    {{:#patternfieldreference}Pattern field reference section}), and
360    things like computed length fields, fixed value fields, insertion
361    of bitstrings within bitstrings, etc. are all supported.
362
363    {3 Construction exception}
364
365    The [BITSTRING] operator may throw a {!Construct_failure}
366    exception at runtime.
367
368    Runtime errors include:
369
370    - int field length not in the range \[1..64\]
371    - a bitstring with a length declared which doesn't have the
372      same length at runtime
373    - trying to insert an out of range value into an int field
374      (eg. an unsigned int field which is 2 bits wide can only
375      take values in the range \[0..3\]).
376
377    {2:integertypes Integer types}
378
379    Integer types are mapped to OCaml types [bool], [int], [int32] or
380    [int64] using a system which tries to ensure that (a) the types are
381    reasonably predictable and (b) the most efficient type is
382    preferred.
383
384    The rules are slightly different depending on whether the bit
385    length expression in the field is a compile-time constant or a
386    computed expression.
387
388    Detection of compile-time constants is quite simplistic so only
389    simple integer literals and simple expressions (eg. [5*8]) are
390    recognized as constants.
391
392    In any case the bit size of an integer is limited to the range
393    \[1..64\].  This is detected as a compile-time error if that is
394    possible, otherwise a runtime check is added which can throw an
395    [Invalid_argument] exception.
396
397    The mapping is thus:
398
399    {v
400    Bit size         ---- OCaml type ----
401                 Constant        Computed expression
402
403    1            bool            int64
404    2..31        int             int64
405    32           int32           int64
406    33..64       int64           int64
407    v}
408
409    A possible future extension may allow people with 64 bit computers
410    to specify a more optimal [int] type for bit sizes in the range
411    [32..63].  If this was implemented then such code {i could not even
412    be compiled} on 32 bit platforms, so it would limit portability.
413
414    Another future extension may be to allow computed
415    expressions to assert min/max range for the bit size,
416    allowing a more efficient data type than int64 to be
417    used.  (Of course under such circumstances there would
418    still need to be a runtime check to enforce the
419    size).
420
421    {2:computedoffsets Computed offsets}
422
423    You can add an [offset(..)] qualifier to bitmatch patterns in order
424    to move the current offset within the bitstring forwards.
425
426    For example:
427
428 {[
429 bitmatch bits with
430 | { field1 : 8;
431     field2 : 8 : offset(160) } -> ...
432 ]}
433
434    matches [field1] at the start of the bitstring and [field2]
435    at 160 bits into the bitstring.  The middle 152 bits go
436    unmatched (ie. can be anything).
437
438    The generated code is efficient.  If field lengths and offsets
439    are known to be constant at compile time, then almost all
440    runtime checks are avoided.  Non-constant field lengths and/or
441    non-constant offsets can result in more runtime checks being added.
442
443    Note that moving the offset backwards, and moving the offset in
444    [BITSTRING] constructors, are both not supported at present.
445
446    {2 Named patterns and persistent patterns}
447
448    Please see {!Bitmatch_persistent} for documentation on this subject.
449
450    {2 Compiling}
451
452    Using the compiler directly you can do:
453
454    {v
455    ocamlc -I +bitmatch \
456      -pp "camlp4o bitmatch.cma bitmatch_persistent.cma \
457             `ocamlc -where`/bitmatch/pa_bitmatch.cmo" \
458      unix.cma bitmatch.cma test.ml -o test
459    v}
460
461    Simpler method using findlib:
462
463    {v
464    ocamlfind ocamlc \
465      -package bitmatch,bitmatch.syntax -syntax bitmatch.syntax \
466      -linkpkg test.ml -o test
467    v}
468
469    {2 Security and type safety}
470
471    {3 Security on input}
472
473    The main concerns for input are buffer overflows and denial
474    of service.
475
476    It is believed that this library is robust against attempted buffer
477    overflows.  In addition to OCaml's normal bounds checks, we check
478    that field lengths are >= 0, and many additional checks.
479
480    Denial of service attacks are more problematic.  We only work
481    forwards through the bitstring, thus computation will eventually
482    terminate.  As for computed lengths, code such as this is thought
483    to be secure:
484
485    {[
486    bitmatch bits with
487    | { len : 64;
488        buffer : Int64.to_int len : bitstring } ->
489    ]}
490
491    The [len] field can be set arbitrarily large by an attacker, but
492    when pattern-matching against the [buffer] field this merely causes
493    a test such as [if len <= remaining_size] to fail.  Even if the
494    length is chosen so that [buffer] bitstring is allocated, the
495    allocation of sub-bitstrings is efficient and doesn't involve an
496    arbitary-sized allocation or any copying.
497
498    However the above does not necessarily apply to strings used in
499    matching, since they may cause the library to use the
500    {!Bitmatch.string_of_bitstring} function, which allocates a string.
501    So you should take care if you use the [string] type particularly
502    with a computed length that is derived from external input.
503
504    The main protection against attackers should be to ensure that the
505    main program will only read input bitstrings up to a certain
506    length, which is outside the scope of this library.
507
508    {3 Security on output}
509
510    As with the input side, computed lengths are believed to be
511    safe.  For example:
512
513    {[
514    let len = read_untrusted_source () in
515    let buffer = allocate_bitstring () in
516    BITSTRING {
517      buffer : len : bitstring
518    }
519    ]}
520
521    This code merely causes a check that buffer's length is the same as
522    [len].  However the program function [allocate_bitstring] must
523    refuse to allocate an oversized buffer (but that is outside the
524    scope of this library).
525
526    {3 Order of evaluation}
527
528    In [bitmatch] statements, fields are evaluated left to right.
529
530    Note that the when-clause is evaluated {i last}, so if you are
531    relying on the when-clause to filter cases then your code may do a
532    lot of extra and unncessary pattern-matching work on fields which
533    may never be needed just to evaluate the when-clause.  You can
534    usually rearrange the code to do only the first part of the match,
535    followed by the when-clause, followed by a second inner bitmatch.
536
537    {3 Safety}
538
539    The current implementation is believed to be fully type-safe,
540    and makes compile and run-time checks where appropriate.  If
541    you find a case where a check is missing please submit a
542    bug report or a patch.
543
544    {2 Limits}
545
546    These are thought to be the current limits:
547
548    Integers: \[1..64\] bits.
549
550    Bitstrings (32 bit platforms): maximum length is limited
551    by the string size, ie. 16 MBytes.
552
553    Bitstrings (64 bit platforms): maximum length is thought to be
554    limited by the string size, ie. effectively unlimited.
555
556    Bitstrings must be loaded into memory before we can match against
557    them.  Thus available memory may be considered a limit for some
558    applications.
559
560    {2:reference Reference}
561    {3 Types}
562 *)
563
564 type endian = BigEndian | LittleEndian | NativeEndian
565
566 val string_of_endian : endian -> string
567 (** Endianness. *)
568
569 type bitstring = string * int * int
570 (** [bitstring] is the basic type used to store bitstrings.
571
572     The type contains the underlying data (a string),
573     the current bit offset within the string and the
574     current bit length of the string (counting from the
575     bit offset).  Note that the offset and length are
576     in {b bits}, not bytes.
577
578     Normally you don't need to use the bitstring type
579     directly, since there are functions and syntax
580     extensions which hide the details.
581
582     See also {!bitstring_of_string}, {!bitstring_of_file},
583     {!hexdump_bitstring}, {!bitstring_length}.
584 *)
585
586 (** {3 Exceptions} *)
587
588 exception Construct_failure of string * string * int * int
589 (** [Construct_failure (message, file, line, char)] may be
590     raised by the [BITSTRING] constructor.
591
592     Common reasons are that values are out of range of
593     the fields that contain them, or that computed lengths
594     are impossible (eg. negative length bitfields).
595
596     [message] is the error message.
597
598     [file], [line] and [char] point to the original source
599     location of the [BITSTRING] constructor that failed.
600 *)
601
602 (** {3 Bitstrings} *)
603
604 val empty_bitstring : bitstring
605 (** [empty_bitstring] is the empty, zero-length bitstring. *)
606
607 val create_bitstring : int -> bitstring
608 (** [create_bitstring n] creates an [n] bit bitstring
609     containing all zeroes. *)
610
611 val make_bitstring : int -> char -> bitstring
612 (** [make_bitstring n c] creates an [n] bit bitstring
613     containing the repeated 8 bit pattern in [c].
614
615     For example, [make_bitstring 16 '\x5a'] will create
616     the bitstring [0x5a5a] or in binary [0101 1010 0101 1010].
617
618     Note that the length is in bits, not bytes.  The length does NOT
619     need to be a multiple of 8. *)
620
621 val zeroes_bitstring : int -> bitstring
622 (** [zeroes_bitstring] creates an [n] bit bitstring of all 0's.
623
624     Actually this is the same as {!create_bitstring}. *)
625
626 val ones_bitstring : int -> bitstring
627 (** [ones_bitstring] creates an [n] bit bitstring of all 1's. *)
628
629 val bitstring_of_string : string -> bitstring
630 (** [bitstring_of_string str] creates a bitstring
631     of length [String.length str * 8] (bits) containing the
632     bits in [str].
633
634     Note that the bitstring uses [str] as the underlying
635     string (see the representation of {!bitstring}) so you
636     should not change [str] after calling this. *)
637
638 val bitstring_of_file : string -> bitstring
639 (** [bitstring_of_file filename] loads the named file
640     into a bitstring. *)
641
642 val bitstring_of_chan : in_channel -> bitstring
643 (** [bitstring_of_chan chan] loads the contents of
644     the input channel [chan] as a bitstring.
645
646     The length of the final bitstring is determined
647     by the remaining input in [chan], but will always
648     be a multiple of 8 bits.
649
650     See also {!bitstring_of_chan_max}. *)
651
652 val bitstring_of_chan_max : in_channel -> int -> bitstring
653 (** [bitstring_of_chan_max chan max] works like
654     {!bitstring_of_chan} but will only read up to
655     [max] bytes from the channel (or fewer if the end of input
656     occurs before that). *)
657
658 val bitstring_of_file_descr : Unix.file_descr -> bitstring
659 (** [bitstring_of_file_descr fd] loads the contents of
660     the file descriptor [fd] as a bitstring.
661
662     See also {!bitstring_of_chan}, {!bitstring_of_file_descr_max}. *)
663
664 val bitstring_of_file_descr_max : Unix.file_descr -> int -> bitstring
665 (** [bitstring_of_file_descr_max fd max] works like
666     {!bitstring_of_file_descr} but will only read up to
667     [max] bytes from the channel (or fewer if the end of input
668     occurs before that). *)
669
670 val bitstring_length : bitstring -> int
671 (** [bitstring_length bitstring] returns the length of
672     the bitstring in bits. *)
673
674 val string_of_bitstring : bitstring -> string
675 (** [string_of_bitstring bitstring] converts a bitstring to a string
676     (eg. to allow comparison).
677
678     This function is inefficient.  In the best case when the bitstring
679     is nicely byte-aligned we do a [String.sub] operation.  If the
680     bitstring isn't aligned then this involves a lot of bit twiddling
681     and is particularly inefficient.
682
683     If the bitstring is not a multiple of 8 bits wide then the
684     final byte of the string contains the high bits set to the
685     remaining bits and the low bits set to 0. *)
686
687 val bitstring_to_file : bitstring -> string -> unit
688 (** [bitstring_to_file bits filename] writes the bitstring [bits]
689     to the file [filename].  It overwrites the output file.
690
691     Some restrictions apply, see {!bitstring_to_chan}. *)
692
693 val bitstring_to_chan : bitstring -> out_channel -> unit
694 (** [bitstring_to_file bits filename] writes the bitstring [bits]
695     to the channel [chan].
696
697     Channels are made up of bytes, bitstrings can be any bit length
698     including fractions of bytes.  So this function only works
699     if the length of the bitstring is an exact multiple of 8 bits
700     (otherwise it raises [Invalid_argument "bitstring_to_chan"]).
701
702     Furthermore the function is efficient only in the case where
703     the bitstring is stored fully aligned, otherwise it has to
704     do inefficient bit twiddling like {!string_of_bitstring}.
705
706     In the common case where the bitstring was generated by the
707     [BITSTRING] operator and is an exact multiple of 8 bits wide,
708     then this function will always work efficiently.
709 *)
710
711 (** {3 Printing bitstrings} *)
712
713 val hexdump_bitstring : out_channel -> bitstring -> unit
714 (** [hexdump_bitstring chan bitstring] prints the bitstring
715     to the output channel in a format similar to the
716     Unix command [hexdump -C]. *)
717
718 (** {3 Bitstring buffer} *)
719
720 module Buffer : sig
721   type t
722   val create : unit -> t
723   val contents : t -> bitstring
724   val add_bits : t -> string -> int -> unit
725   val add_bit : t -> bool -> unit
726   val add_byte : t -> int -> unit
727 end
728 (** Buffers are mainly used by the [BITSTRING] constructor, but
729     may also be useful for end users.  They work much like the
730     standard library [Buffer] module. *)
731
732 (** {3 Miscellaneous} *)
733
734 val package : string
735 (** The package name, always ["ocaml-bitmatch"] *)
736
737 val version : string
738 (** The package version as a string. *)
739
740 val debug : bool ref
741 (** Set this variable to true to enable extended debugging.
742     This only works if debugging was also enabled in the
743     [pa_bitmatch.ml] file at compile time, otherwise it
744     does nothing. *)
745
746 (**/**)
747
748 (* Private functions, called from generated code.  Do not use
749  * these directly - they are not safe.
750  *)
751
752 val extract_bitstring : string -> int -> int -> int -> bitstring * int * int
753
754 val extract_remainder : string -> int -> int -> bitstring * int * int
755
756 val extract_bit : string -> int -> int -> int -> bool * int * int
757
758 val extract_char_unsigned : string -> int -> int -> int -> int * int * int
759
760 val extract_int_be_unsigned : string -> int -> int -> int -> int * int * int
761
762 val extract_int_le_unsigned : string -> int -> int -> int -> int * int * int
763
764 val extract_int_ne_unsigned : string -> int -> int -> int -> int * int * int
765
766 val extract_int_ee_unsigned : endian -> string -> int -> int -> int -> int * int * int
767
768 val extract_int32_be_unsigned : string -> int -> int -> int -> int32 * int * int
769
770 val extract_int32_le_unsigned : string -> int -> int -> int -> int32 * int * int
771
772 val extract_int32_ne_unsigned : string -> int -> int -> int -> int32 * int * int
773
774 val extract_int32_ee_unsigned : endian -> string -> int -> int -> int -> int32 * int * int
775
776 val extract_int64_be_unsigned : string -> int -> int -> int -> int64 * int * int
777
778 val extract_int64_le_unsigned : string -> int -> int -> int -> int64 * int * int
779
780 val extract_int64_ne_unsigned : string -> int -> int -> int -> int64 * int * int
781
782 val extract_int64_ee_unsigned : endian -> string -> int -> int -> int -> int64 * int * int
783
784 val construct_bit : Buffer.t -> bool -> int -> exn -> unit
785
786 val construct_char_unsigned : Buffer.t -> int -> int -> exn -> unit
787
788 val construct_int_be_unsigned : Buffer.t -> int -> int -> exn -> unit
789
790 val construct_int_ne_unsigned : Buffer.t -> int -> int -> exn -> unit
791
792 val construct_int_ee_unsigned : endian -> Buffer.t -> int -> int -> exn -> unit
793
794 val construct_int32_be_unsigned : Buffer.t -> int32 -> int -> exn -> unit
795
796 val construct_int32_ne_unsigned : Buffer.t -> int32 -> int -> exn -> unit
797
798 val construct_int32_ee_unsigned : endian -> Buffer.t -> int32 -> int -> exn -> unit
799
800 val construct_int64_be_unsigned : Buffer.t -> int64 -> int -> exn -> unit
801
802 val construct_int64_ne_unsigned : Buffer.t -> int64 -> int -> exn -> unit
803
804 val construct_int64_ee_unsigned : endian -> Buffer.t -> int64 -> int -> exn -> unit
805
806 val construct_string : Buffer.t -> string -> unit
807
808 val construct_bitstring : Buffer.t -> bitstring -> unit