Debian Codegraph @

README.md

raw symbols SCIP
1 Bin_prot - OCaml Type Converter for Binary Protocols
2 ====================================================
3
4 What is `Bin_prot`?
5 -------------------
6
7 This library contains functionality for reading and writing OCaml-values in a
8 type-safe binary protocol. It is extremely efficient, typically supporting
9 type-safe marshalling and unmarshalling of even highly structured values at
10 speeds sufficient to saturate a gigabit connection. The protocol is also
11 heavily optimized for size, making it ideal for long-term storage of large
12 amounts of data.
13
14 The library is highly dependable and safe to use: a rigorous test suite has
15 to date guaranteed that this library has never exhibited a bug in production
16 systems in several years of use. `Bin_prot` has been successfully deployed in
17 mission-critical financial applications, storing many terabytes of structured
18 data derived from thousands of type definitions and typically processing
19 millions of messages a day in realtime for low-latency applications that
20 must not crash.
21
22 Since version two this library should work with all CPU architectures currently
23 supported by OCaml, no matter the word size (32 or 64 bit), alignment
24 requirements, or endianness. Endianness defines the byte order in which
25 machine representations of integers (machine words) are stored in main memory.
26
27 `Bin_prot` provides users with a convenient and safe way of performing I/O
28 on any extensionally defined OCaml type (see later sections for details).
29 Functions, objects, first-class modules, as well as values whose type is
30 bound through a polymorphic record field are hence not supported. This is
31 hardly ever a limitation in practice.
32
33 As of now, there is no support for cyclic or shared values. Cyclic values
34 will lead to non-termination whereas shared values, besides requiring more
35 space when encoded, may lead to a substantial increase in memory footprint
36 when they are read back. It would not be trivial to support these kinds
37 of values in a type-safe way without noticeably sacrificing performance.
38 If these kinds of values are needed, the user may want to use the as of
39 today still unsafe marshalling functions provided by OCaml.
40
41 This library uses the machine stack for efficiency reasons. This can
42 potentially lead to a crash if the stack limit is reached. Note that this
43 is also a limitation of the (unsafe) standard marshalling functions shipped
44 with OCaml. This problem can happen for large amounts of data if recursion in
45 the type definition of the data structure is not limited to the last element.
46 Only in the latter case will tail-recursion allow for (practically) unlimited
47 amounts of data. If this exceedingly rare limitation ever turned out to be
48 an issue in a user application, it can often be solved by redefining the data
49 type to allow for tail-recursion. The limitation cannot be eliminated in
50 this library without significant performance impact and increased complexity.
51
52 Usage
53 -----
54
55 The API (`.mli`-files) in the `bin_prot` library directory (`lib`)
56 is fully documented, and HTML-documentation can be built from it on
57 installation. The documentation for the latest release can also be found
58 [online](https://v3.ocaml.org/p/bin_prot).
59
60 Module `Common` defines some globally used types, functions, exceptions,
61 and values. `Nat0` implements natural numbers including zero.
62
63 Modules `Read_ml` and `Write_ml` contain read and write functions respectively
64 for all basic types.
65
66 The module `Size` allows you to compute the size of basic OCaml-values in the
67 binary representation before writing them to a buffer. The code generator
68 will also provide you with functions for your user-defined types.
69
70 Module `Std` predefines converters for most standard OCaml types. If you
71 use the preprocessor macros to generate code from type definitions, make sure
72 that the contents of this module is visible by e.g. adding the following at
73 the top of files using this library:
74
75 :::ocaml
76 open Bin_prot.Std
77
78 Note that you can shadow the definitions in the above module in the unlikely
79 event that the predefined ways of converting data are unsatisfactory to you.
80
81 The module `Type_class` contains some extra definitions for type classes of
82 basic values. These definitions can be passed to the function `bin_dump` in
83 module `Utils` to marshal values into buffers of exact size using the binary
84 protocol. However, if bounds on the size of values are known, it is usually
85 more efficient to write them directly into preallocated buffers and just catch
86 exceptions if the buffer limits are unexpectedly violated. Doing so should
87 never cause a crash. That way one does not have to compute the size of the
88 value, which can sometimes be almost as expensive as writing the value in the
89 first place.
90
91 In module `Utils` the function `bin_read_stream` can be used to efficiently
92 read size-prefixed values as written by `bin_dump` with the `header` flag
93 set to `true`. This module also offers several useful functors. The ones
94 for `Binable` types help users create readers and writers if a type needs to
95 be converted to or from some intermediate representation before marshalling
96 or after unmarshalling respectively. The functors for `Iterable` types are
97 helpful if some (usually abstract) data type offers iteration over elements and
98 if the series of iterated-over elements alone is sufficient to reconstruct the
99 original value. This allows for a more compact protocol and for robustness
100 against changes to the internal representation of the data type (e.g. sets,
101 maps, etc.).
102
103 ### Examples
104
105 Consider the following type definition:
106
107 :::ocaml
108 type t = A | B [@@deriving bin_io]
109
110 This will generate the functions `bin_size_t`, `bin_write_t`, and `bin_read_t`,
111 as well as the type class values `bin_writer_t`, `bin_reader_t`, and `bin_t`.
112 If you use the annotation `bin_write` instead of `bin_io`, then only the
113 write and size functions and their type class will be generated. Specifying
114 `bin_read` will generate the read functions and associated type class only.
115 The annotation `bin_type_class` will generate the combined type class only,
116 thus allowing the user to easily define their own reader and writer type
117 classes. The code generator may also generate low-level entry points used
118 for efficiency or backtracking.
119
120 The preprocessor can also generate signatures for conversion functions. Just
121 add the wanted annotation to the type in a module signature for that purpose.
122
123 Specification of the Binary Protocol
124 ------------------------------------
125
126 The binary protocol does not contain any data other than the minimum needed
127 to decode values. This means that the user is responsible for e.g. writing
128 out the size of messages themselves if they want to be able to preallocate
129 sufficiently sized buffers before reading. The `Utils` module provides some
130 simple functions for that matter, though users may obtain optimum efficiency
131 by managing buffers themselves.
132
133 Basic OCaml-values are written out character-wise as described below.
134 The specification uses hex codes to define the character encoding. Some of
135 these values require size/length information to be written out before the
136 value (e.g. for lists, hash tables, strings, etc.). Size information is
137 always encoded as natural numbers (`Nat0.t`). The little-endian format is
138 used in the protocol for the contents of integers on all platforms.
139
140 The following definitions will be used in the encoding specifications below:
141
142 :::text
143 CODE_NEG_INT8 -> 0xff
144 CODE_INT16 -> 0xfe
145 CODE_INT32 -> 0xfd
146 CODE_INT64 -> 0xfc
147
148 ### Nat0.t
149
150 This type encodes natural numbers including zero. It is frequently used by
151 `Bin_prot` itself for encoding size information for e.g. lists, arrays, etc.,
152 and hence defined first here. Developers can reuse this type in their code,
153 too, of course.
154
155 If the value of the underlying integer is lower than a certain range,
156 this implies a certain encoding as provided on the right hand side of the
157 following definitions:
158
159 :::text
160 < 0x000000080 -> lower 8 bits of the integer (1 byte)
161 < 0x000010000 -> CODE_INT16 followed by lower 16 bits of integer (3 bytes)
162 < 0x100000000 -> CODE_INT32 followed by lower 32 bits of integer (5 bytes)
163 >= 0x100000000 -> CODE_INT64 followed by all 64 bits of integer (9 bytes)
164
165 The last line in the definitions above is only supported on 64 bit platforms
166 due to word size limitations.
167
168 Appropriate exceptions will be raised if there is an overflow, for example
169 if a 64 bit encoding is read on a 32 bit platform, or if the 32 bit or 64
170 bit encoding overflowed the 30 bit or 62 bit capacity of natural numbers
171 on their respective platforms. The last kind of overflow is due to OCaml
172 reserving one bit for GC-tagging and the sign bit being lost.
173
174 ### Unit values
175
176 :::text
177 () -> 0x00
178
179
180 ### Booleans
181
182 :::text
183 false -> 0x00
184 true -> 0x01
185
186 ### Strings
187
188 First the length of the string is written out as a `Nat0.t`. Then the
189 contents of the string is copied verbatim.
190
191 ### Characters
192
193 Characters are written out verbatim.
194
195 ### Integers
196
197 This includes all integer types: `int`, `int32`, `int64`, `nativeint`.
198 If the value is positive (including zero) and if it is:
199
200 :::text
201 < 0x00000080 -> lower 8 bits of the integer (1 byte)
202 < 0x00008000 -> CODE_INT16 followed by lower 16 bits of integer (3 bytes)
203 < 0x80000000 -> CODE_INT32 followed by lower 32 bits of integer (5 bytes)
204 >= 0x80000000 -> CODE_INT64 followed by all 64 bits of integer (9 bytes)
205
206 If the value is negative and if it is:
207
208 :::text
209 >= -0x00000080 -> CODE_NEG_INT8 followed by lower 8 bits of integer (2 bytes)
210 >= -0x00008000 -> CODE_INT16 followed by lower 16 bits of integer (3 bytes)
211 >= -0x80000000 -> CODE_INT32 followed by lower 32 bits of integer (5 bytes)
212 < -0x80000000 -> CODE_INT64 followed by all 64 bits of integer (9 bytes)
213
214 All of the above branches will be considered when converting values of type
215 `int64`. The case for `CODE_INT64` will only be considered with types `int`
216 and `nativeint` if the architecture supports it. `int32` will never be encoded
217 as a `CODE_INT64`. Appropriate exceptions will be raised if the architecture
218 of or the type requested by the reader does not support some encoding or
219 if there is an overflow. An overflow can only happen with values of type
220 `int`, because one bit is reserved by OCaml for the GC-tag again.
221
222 The reason for this peculiar encoding is of statistical nature. It was
223 assumed that small or positive numbers are much more frequent in practice
224 than big or negative ones. The code is biased accordingly to achieve good
225 compression and decoding performance. For example, a positive integer in
226 the range from `0` to `127` requires only a single byte on the wire and only
227 a single branch to identify it.
228
229 ### Floats
230
231 Floats are written out according to the 64 bit IEEE 754 floating point
232 standard, i.e. their memory representation is copied verbatim.
233
234 ### References and lazy values
235
236 Same as the binary encoding of the value in the reference or of the lazily
237 calculated value.
238
239 ### Option values
240
241 If the value is:
242
243 :::text
244 None -> 0x00
245 Some v -> 0x01 followed by the encoding of v
246
247 ### Tuples and records
248
249 Values in tuples and records are written out one after the other in the order
250 specified in the type definition. Polymorphic record fields are supported
251 unless a value of the type bound by the field were accessed, which would
252 lead to an exception.
253
254 ### Sum types
255
256 Each of the `n` tags in a sum type is assigned an integer from `0` to `n - 1`
257 in exactly the same order as they occur in the type. If a value of this
258 type needs to be written out, then if:
259
260 :::text
261 n <= 256 -> write out lower 8 bits of n (1 byte)
262 n <= 65536 -> write out lower 16 bits of n (2 bytes)
263
264 Sum types with more tags are currently not supported and highly unlikely
265 to occur in practice. Arguments to the tag are written out in the order
266 of occurrence.
267
268 ### Polymorphic variants
269
270 The tags of these values are written out as four characters, more precisely
271 as the 32 bit hash value computed by OCaml for the given tag in little-endian
272 format. Any arguments associated with the tag are written out afterwards
273 in the order of occurrence.
274
275 When polymorphic variants are being read, they will be matched in order
276 of occurrence (left-to-right) in the type and depth-first in the case of
277 included polymorphic types. The first type containing a match for the
278 variant will be used for reading. E.g.:
279
280 :::ocaml
281 type ab = [ `A | `B ] [@@deriving bin_io]
282 type cda = [ `C | `D | `A ] [@@deriving bin_io]
283 type abcda = [ ab | cda ] [@@deriving bin_io]
284
285 When reading type `abcda`, the reader associated with type `ab` rather than
286 `cda` will be invoked if a value of type ```A`` can be read. This may not
287 make a difference in this example, but is important to know if the user
288 manually overrides converters. It is strongly recommended to not merge
289 polymorphic variants if their readers might disagree about how to interpret
290 a certain tag. This is inconsistent, confusing, and hard to debug.
291
292 ### Lists and arrays
293
294 For lists and arrays the length is written out as a `Nat0.t` first, followed
295 by all values in the same order as in the data structure.
296
297 ### Hash tables
298
299 First the size of the hash table is written out as a `Nat0.t`. Then the
300 writer iterates over each binding in the hash table and writes out the key
301 followed by the value.
302
303 Note that this makes reading somewhat slower than if we used the internal
304 (extensional) representation of the hash table, because all values have to be
305 rehashed. On the other hand, the format becomes more robust in case the hash
306 table implementation changes. This has in fact already happened in practice
307 with the release of OCaml 4.00. Users should take note of this and make
308 sure that all of their serialization routines remain future-proof by defining
309 wire formats that are independent of the implementation of abstract data types.
310
311 ### Bigarrays of doubles (type `vec`) and characters (type `bigstring`)
312
313 First the dimension(s) are written out as `Nat0.t`. Then the contents is
314 copied verbatim.
315
316 ### Polymorphic values
317
318 There is nothing special about polymorphic values as long as there are
319 conversion functions for the type parameters. E.g.:
320
321 :::ocaml
322 type 'a t = A | B of 'a [@@deriving bin_io]
323 type foo = int t [@@deriving bin_io]
324
325 In the above case the conversion functions will behave as if `foo` had been
326 defined as a monomorphic version of `t` with `int` substituted for `'a`
327 on the right hand side.
328
329 ### Abstract data types
330
331 If you want to convert an abstract data type that may impose constraints on the
332 well-formedness of values, you will have to roll your own conversion functions.
333 Use the functions in module `Read_c` and `Write_c` to map between low-level and
334 high-level representations, or implement those manually for maximum efficiency.
335 The `Utils` module may also come in handy as described in earlier sections,
336 e.g. if the value can be converted to and from an intermediate representation
337 that does not impose constraints, or if some sort of iteration is supported
338 by the data type.