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