Commits

Markus Mottl committed 34d3643

Renamed type-conv and bin-prot dirs to type_conv and bin_prot

Comments (0)

Files changed (136)

base/bin-prot/.hgignore.in

-INSTALL
-configure
-lib/bin_prot.mlpack
-lib/libbin_prot.clib
-lib/META
-setup.ml
-setup.log
-setup.data
-syntax/pa_bin_prot.mllib
-_oasis
-_build
-_tags
-Makefile
-myocamlbuild.ml

base/bin-prot/COPYRIGHT

-Most of this library was written by:
-
-  Markus Mottl          <markus.mottl@gmail.com>
-
-Part of this work is derived from the library "Tywith", version 0.45.
-The library "Tywith" was written and is distributed by:
-
-  Martin Sandin         <msandin@hotmail.com>
-
-The original license of "Tywith" can be found in the file
-"LICENSE.Tywith".  Files that were derived from "Tywith" contain a
-reference to the original author.
-
-The following company has sponsored and has copyright in part of this work:
-
-  Jane Street Holding, LLC
-  1 New York Plaza, 33rd Floor 
-  New York, NY 10004
-  USA

base/bin-prot/Changelog

-2012-02-28:  Improved portability by better supporting the C99-standard and
-             non-GNU compilers.
-
-2011-11-10:  Improved portability to older glibc distributions.
-
-2011-09-15:  Fixes to improve package dependency resolution.
-
-2011-07-04:  Internal updates to sync with Jane Street.
-
-2011-06-29:  Fixed bigstring layout bug, which should only affect value
-             comparisons with OCaml 3.12.1 or later.
-
-             Made 64-bit detection more reliable on Mac OS X.
-
-2010-03-20:  Fixed linking of toplevels to require bigarrays.
-
-             Improved compilation on Mac OS X.
-
-2010-03-17:  Fixed small name capture bug.
-
-2009-12-21:  Updated contact information.
-
-2009-09-19:  Added missing type cases for supporting variant types.
-
-             Fixed handling of variance annotations.
-
-2009-07-27:  Fixed build problem with gcc 4.4 due to stricter checking
-             for empty macro arguments.
-
-             Thanks to Nobuyuki Tomiza <nobuyuki.tomizawa@gmail.com>
-             for the patch!
-
-2009-07-20:  Merged tiny Jane Street improvements.
-
-2009-07-03:  Made byte swapping more portable.
-
-2009-07-02:  Added support for network byte order integers.
-
-2009-04-22:  Added macro support for all kinds of vectors (vec,
-             float32_vec, float64_vec) and matrices (mat, float32_mat,
-             float64_mat), and for bigstrings (bigstring).
-
-2009-04-16:  Fixed a bug leading to an exception when writing
-             extremely large values (>4 GB buffer size).  Does not cause
-             data corruption.
-
-             Switched to private types with "Nat0.t".
-
-             Added support for converting vectors (Bigarrays).
-
-             Added functor for generation of converters for "iterable"
-             types.
-
-             Some code cleanups.
-
-2009-03-09:  Synchronized with Jane Street version.
-
-2009-03-02:  Fixed another build problem on Mac OS X.
-
-2008-10-16:  Fixed build problem on Mac OS X.
-
-             Thanks to Alexy Khrabrov <alexy@khrabrov.net> for the patch!
-
-2008-09-19:  Fixed compilation problem in test suite.
-
-             Fixed compilation problem on 32bit platforms.  Fix bug in
-             architecture detection.
-
-2008-08-22:  Removed deprecated functionality and addressed code reviews.
-
-2008-08-20:  Fixed build problems.  Slightly improved API.
-
-2008-07-28:  Fixed 32bit compilation problem.
-
-2008-05-16:  Added reader for int64_bits + test cases for reader and writer.
-
-2008-04-29:  Final fixes before first public release.
-
-2008-04-03:  Added converter functor for types that should not be written
-             out in their original extensional representation.
-
-2008-03-18:  Fixed minor bin_prot code generation bug with empty types.
-
-2008-03-17:  Improved META-file.
-
-2008-02-11:  Fixed code generation problems with variance annotations
-             in signatures, and with empty types.
-
-2007-12-18:  Added support for bigstrings.
-
-2007-12-17:  Added support for signature generation.
-
-2007-10-31:  Synchronized with Jane Street version.
-
-2007-10-11:  Initial release.

base/bin-prot/LICENSE.Tywith

----------------------------------------------------------------------------
-Copyright (c) 2004 Martin Sandin
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-3. The name of the author may not be used to endorse or promote products
-   derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------

base/bin-prot/README

-      
-                                        
-                          README: library "Bin_prot"
-                          **************************
-             Copyright (C) 2007-2011  Jane Street Holding, LLC (1)
-            ======================================================
-                             Author: Markus Mottl 
-                            ======================
-                             New York, 2011-07-29
-                             ====================
-  
-
-1  Directory contents
-*=*=*=*=*=*=*=*=*=*=*
-
-   
-                                        
-      ------------------------------------------------------------------
-      |    Changelog      |           History of code changes          |
-      ------------------------------------------------------------------
-      |    COPYRIGHT      |              Notes on copyright            |
-      ------------------------------------------------------------------
-      |     INSTALL       |         Short notes on compiling and       |
-      |                   |            installing the library          |
-      ------------------------------------------------------------------
-      |     LICENSE       |           License of this library          |
-      ------------------------------------------------------------------
-      |  LICENSE.Tywith   |              License of Tywith             |
-      ------------------------------------------------------------------
-      |     Makefile      |                 Top Makefile               |
-      ------------------------------------------------------------------
-      |    README.txt     |          This text in ASCII format         |
-      ------------------------------------------------------------------
-      |       doc/        |         LaTeX sources for this text        |
-      ------------------------------------------------------------------
-      |       lib/        |               Library sources              |
-      ------------------------------------------------------------------
-      |    lib_test/      |  Test applications for the Bin_prot-library|
-      ------------------------------------------------------------------
-      |     syntax/       |      Preprocessor for type definitions     |
-      ------------------------------------------------------------------
-                                        
-  
-  
-
-2  What is "Bin_prot"
-*=*=*=*=*=*=*=*=*=*=*
-
-  
-  This library contains functionality for reading and writing OCaml-values in
-a type-safe binary protocol. It is extremely efficient, typically supporting
-type-safe marshalling and unmarshalling of even highly structured values at
-speeds sufficient to saturate a gigabit connection. The protocol is also
-heavily optimized for size, making it ideal for long-term storage of large
-amounts of data.
-   The library is highly dependable and safe to use: a rigorous test suite has
-to date guaranteed that this library has never exhibited a bug in production
-systems in several years of use. "Bin_prot" has been successfully employed in
-mission-critical financial applications, storing many terabytes of structured
-data derived from thousands of type definitions, and typically processing
-millions of messages a day in realtime for low-latency applications that must
-not crash.
-   Since version two this library should work with all CPU architectures
-currently supported by OCaml, no matter the word size (32 or 64 bit),
-endianness (2), or alignment requirements. It provides users with a convenient
-and safe way of performing I/O on any extensionally defined OCaml type (see
-later sections for details). Functions, objects, first-class modules, as well
-as values whose type is bound through a polymorphic record field are hence not
-supported. This is hardly ever a limitation in practice.
-   As of now, there is no support for cyclic or shared values. Cyclic values
-will lead to non-termination whereas shared values, besides requiring more
-space when encoded, may lead to a substantial increase in memory footprint
-when they are read back. It would not be trivial to support these kinds of
-values in a type-safe way without noticably sacrificing performance. If these
-kinds of values are needed, the user may want to use the as of today still
-unsafe marshalling functions provided by OCaml.
-   This library uses the machine stack for efficiency reasons. This can
-potentially lead to a crash if the stack limit is reached. Note that this is
-also a limitation of the (unsafe) standard marshalling functions shipped with
-OCaml. This problem can happen for large amounts of data if recursion in the
-type definition of the datastructure is not limited to the last element. Only
-in the latter case will tail-recursion allow for (practically) unlimited
-amounts of data. If this exceedingly rare limitation ever turned out to be an
-issue in a user application, it can often be solved by redefining the datatype
-to allow for tail-recursion. The limitation cannot be eliminated in this
-library without significant performance impact and increased complexity.
-  
-
-3  How can you use it?
-*=*=*=*=*=*=*=*=*=*=*=
-
-  
-  The API (.mli-files) in the library directory is fully documented. Module
-'Common' defines some globally used types, functions, exceptions, and values.
-'Nat0' implements natural numbers including zero.
-   Modules 'Read_ml' and 'Write_ml' contain read and write functions
-respectively for all basic types and are implemented in OCaml as far as
-reasonable. If you only want to read or write single, basic, unstructured
-values, this module is probably the most efficient and convenient for doing
-this.
-   Otherwise you should annotate your type definitions to generate type
-converters automatically (see later sections for details). The preprocessor in
-'pa_bin_prot.ml' will then generate highly optimized functions for converting
-your OCaml-values to and from the binary representation. This automatically
-generated code will use functions in modules 'Unsafe_common', 'Unsafe_read_c'
-and 'Unsafe_write_c', which employ unsafe internal representations to achieve
-this performance. The auto-generated code is extremely well-tested and should
-use these unsafe representations correctly. Developers who want to make manual
-use of these unsafe calling conventions for efficiency are strongly encouraged
-to test their code carefully.
-   The module 'Size' allows you to compute the size of basic OCaml-values in
-the binary representations before writing them to a buffer. The code generator
-will also provide you with functions for your user-defined types.
-   Module 'Std' predefines converters for most standard OCaml types. If you
-use the preprocessor macros to generate code from type definitions, make sure
-that the contents of this module is visible by e.g. adding the following at
-the top of files using this library:
-   
-<<  open Bin_prot.Std
->>
-  
-  Note that you can shadow the definitions in the above module in the unlikely
-event that the predefined ways of converting data are unsatisfactory to you.
-   The modules 'Read_c' and 'Write_c' wrap the unsafe low-level converters for
-basic values to ones accessible safely from within OCaml and vice versa. They
-also export functions for wrapping user-defined converters. This should help
-developers make their converters available in the respective other
-representation (low- or high-level). The test applications in the distribution
-use these wrappers to verify the correctness of implementations for low-level
-(C) and high-level (OCaml) representations.
-   The module 'Type_class' contains some extra definitions for type classes of
-basic values. These definitions can be passed to the function 'bin_dump' in
-module 'Utils' to marshal values into buffers of exact size using the binary
-protocol. However, if bounds on the size of values are known, it is usually
-more efficient to write them directly into preallocated buffers and just catch
-exceptions if the buffer limits are unexpectedly violated. Doing so should
-never cause a crash. That way one does not have to compute the size of the
-value, which can sometimes be almost as expensive as writing the value in the
-first place.
-   In module 'Utils' the function 'bin_read_stream' can be used to efficiently
-read size-prefixed values as written by 'bin_dump' there with the 'header'
-flag set to 'true'. This module also offers several useful functors. The ones
-for 'binable' types help users create readers and writers if a type needs to
-be converted to or from some intermediate representation before marshalling or
-after unmarshalling respectively. The functors for 'iterable' types are
-helpful if some (usually abstract) datatype offers iteration over elements and
-if the series of iterated-over elements alone is sufficient to reconstruct the
-original value. This allows for a more compact protocol and for robustness
-against changes to the internal representation of the datatype (e.g. sets,
-maps, etc.).
-  
-
-3.1  Examples
-=============
-  
-  E.g. given the following type definition:
-   
-<<  type t = A | B
-    with bin_io
->>
-  
-  This will generate functions 'bin_size_t', 'bin_write_t', and 'bin_read_t'.
-Furthermore the type class values 'bin_writer_t', 'bin_reader_t' and 'bin_t'.
-If you use the annotation 'bin_write' instead of 'bin_io', then only the write
-and size functions and their type class will be generated. Specifying
-'bin_read' will generate the read functions and associated type class only.
-The annotation 'bin_type_class' will generate the combined type class only,
-thus allowing the user to easily define their own reader and writer type
-classes. The code generator may also generate low-level entry points used for
-efficiency or backtracking.
-  
-  The preprocessor can also generate signatures for conversion functions. Just
-add the wanted annotation to the type in a module signature for that purpose.
-  
-
-4  Specification of the Binary Protocol
-*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
-
-  
-  The binary protocol does not contain any data other than the minimum needed
-to decode values. This means that the user is responsible for e.g. writing out
-the size of messages themselves if they want to be able to preallocate
-sufficiently sized buffers before reading. The 'Utils' module provides some
-simple functions for that matter, though users may obtain optimum efficiency
-by managing buffers themselves.
-   The basic OCaml-values are written out character-wise as described below
-using hex codes for the character encoding. Some of these values require
-size/length information to be written out before the value (e.g. for lists,
-hash tables, strings, etc.). Size information is always encoded as natural
-numbers ('Nat0.t'). The little-endian format is used in the protocol for the
-contents of integers on all platforms.
-   The following definitions will be used in the encoding specifications
-below:
-  
-  
-   - 'CODE_NEG_INT8' -> '0xff' 
-   - 'CODE_INT16' -> '0xfe' 
-   - 'CODE_INT32' -> '0xfd' 
-   - 'CODE_INT64' -> '0xfc' 
-  
-  
-
-4.1  Nat0.t
-===========
-  
-  If the value is:
-  
-  
-   - < '0x000000080' -> lower 8 bit of the integer. 
-   - < '0x000010000' -> 'CODE_INT16' followed by lower 16 bits of integer. 
-   - < '0x100000000' -> 'CODE_INT32' followed by lower 32 bits of integer. 
-   - >= '0x100000000' -> 'CODE_INT64' followed by all 64 bits of integer (3). 
-  
-  Appropriate exceptions will be raised if there is an overflow, e.g. if a 64
-bit encoding is read on a 32 bit platform, or if the 32 bit or 64 bit encoding
-overflowed the 30 bit or 62 bit capacity (4) of natural numbers on their
-respective platforms.
-  
-
-4.2  Unit values
-================
-  
-  
-  
-   - '()' -> '0x00' 
-  
-  
-
-4.3  Booleans
-=============
-  
-  
-  
-   - 'false' -> '0x00' 
-   - 'true' -> '0x01' 
-  
-  
-
-4.4  Strings
-============
-  
-  First the length of the string is written out as a 'Nat0.t'. Then the
-contents of the string is copied verbatim.
-  
-
-4.5  Characters
-===============
-  
-  Characters are written out verbatim.
-  
-
-4.6  Integers
-=============
-  
-  This includes all integer types: 'int, int32, int64, nativeint'. If the
-value is positive (including zero) and if it is:
-  
-  
-   - < '0x00000080' -> lower 8 bit of the integer. 
-   - < '0x00008000' -> 'CODE_INT16' followed by lower 16 bits of integer. 
-   - < '0x80000000' -> 'CODE_INT32' followed by lower 32 bits of integer. 
-   - >= '0x80000000' -> 'CODE_INT64' followed by all 64 bits of integer. 
-  
-  If the value is negative and if it is:
-  
-  
-   - >= '-0x00000080' -> 'CODE_NEG_INT8' followed by lower 8 bit of integer. 
-   - >= '-0x00008000' -> 'CODE_INT16' followed by lower 16 bits of integer. 
-   - >= '-0x80000000' -> 'CODE_INT32' followed by lower 32 bits of integer. 
-   - < '-0x80000000' -> 'CODE_INT64' followed by all 64 bits of integer. 
-  
-  All of the above branches will be considered when converting values of type
-'int64'. The case for 'CODE_INT64' will only be considered with types 'int'
-and 'nativeint' if the architecture supports it. 'int32' will never be encoded
-as a 'CODE_INT64'. Appropriate exceptions will be raised if the architecture
-of or the type requested by the reader does not support some encoding, or if
-there is an overflow (5).
-  
-
-4.7  Floats
-===========
-  
-  Floats are written out according to the 64 bit IEEE 754 floating point
-standard, i.e. their memory representation is copied verbatim.
-  
-
-4.8  References and lazy values
-===============================
-  
-  Same as the binary encoding of the value in the reference or of the value
-calculated lazily.
-  
-
-4.9  Option values
-==================
-  
-  If the value is:
-  
-  
-   - 'None' -> '0x00' 
-   - 'Some v' -> '0x01' followed by the encoding of 'v'. 
-  
-  
-
-4.10  Tuples and records
-========================
-  
-  Values in tuples and records are written out one after the other in the
-order as specified in the type specification without any extra information.
-Polymorphic record fields are supported unless a value of the type bound by
-the field were accessed, which would lead to an exception.
-  
-
-4.11  Sum types
-===============
-  
-  Each tag is assigned an integer from 0 to n - 1 in exactly the same order as
-they occur in the type, where n is the number of sum tags in the type. If a
-value of this type needs to be written out, then if:
-  
-  
-   - n <= 256 -> the integer associated with the tag is written out as one
-   character (lower 8 bits). 
-   - n <= 65536 -> the integer associated with the tag is written out as two
-   characters (lower 16 bits). 
-  
-  Sum types with more tags are currently not supported and highly unlikely to
-occur in practice. Arguments to the tag are written out in the order of
-occurrence without any extra information.
-  
-
-4.12  Polymorphic variants
-==========================
-  
-  The tags of these values are written out as four characters, more precisely
-as the 32 bit hash value computed by OCaml for the given tag in little-endian
-format. Any arguments associated with the tag are written out afterwards in
-the order of occurrence without any extra information.
-   When polymorphic variants are being read, they will be matched in order of
-occurrence (left-to-right) in the type and depth-first in the case of included
-polymorphic types. The first type containing a match for the variant will be
-used for reading. Note that this only matters if semantic invariants are used
-that may impose constraints on whether a value is legal. It is strongly
-suggested to not use different constraints for polymorphic variants with the
-same representation if it is used within the same type, since this is
-inconsistent and hence confusing.
-  
-
-4.13  Lists and arrays
-======================
-  
-  For lists and arrays the length is written out as a 'Nat0.t' first, followed
-by all values in the same order as in the datastructure without any extra
-information.
-  
-
-4.14  Hash tables
-=================
-  
-  First the size of the hash table is written out as 'Nat0.t'. Then the writer
-iterates over each binding in the hash table and writes out the key followed
-by the value without any extra information. Note that this makes reading
-somewhat slower than if we used the internal (extensional) representation of
-the hash table, because all values have to be rehashed. On the other hand, the
-format becomes more robust in case the hash table implementation changes.
-  
-
-4.15  Bigarrays of doubles and characters
-=========================================
-  
-  First the dimension(s) are written out as 'Nat0.t'. Then the contents is
-copied verbatim.
-  
-
-4.16  Polymorphic values
-========================
-  
-  There is nothing special about polymorphic values as long as there are
-conversion functions for the type parameters. E.g.:
-<<  type 'a t = A | B of 'a with bin_io
-    type foo = int t with bin_io
->>
-  
-  In the above case the conversion functions will behave as if 'foo' had been
-defined as a monomorphic version of 't' with ''a' replaced by 'int' on the
-right hand side.
-  
-
-4.17  Abstract datatypes
-========================
-  
-  If you want to convert an abstract datatype that may impose constraints on
-the well-formedness of values, you will have to roll your own conversion
-functions. Use the functions in module 'Read_c' and 'Write_c' to map between
-low-level and high-level representations, or implement those manually for
-maximum efficiency. The 'Utils' module may also come in handy as described in
-earlier sections, e.g. if the value can be converted to and from an
-intermediate representation that does not impose constraints, or if some sort
-of iteration is supported by the datatype.
-  
-
-5  Contact information
-*=*=*=*=*=*=*=*=*=*=*=
-
-  
-  In the case of bugs, feature requests and similar, you can contact us here:
-  
-     opensource@janestreet.com
-  
-   Up-to-date information concerning this library should be available here:
-  
-     http://www.janestreet.com/ocaml
-  
-   Enjoy!!
-  
-   
------------------------------------------------------------------------------
-  
-   This document was translated from LaTeX by HeVeA (6).
---------------------------------------
-  
-  
- (1) http://www.janestreet.com
- 
- (2) Endianness defines the byte order in which machine representations of
-   integers are stored in main memory.
- 
- (3) Only supported on 64 bit platforms.
- 
- (4) One bit is reserved by OCaml for GC-tagging, and the sign bit is lost.
- 
- (5) An overflow can only happen with int values: one bit is reserved by OCaml
-   for the GC-tag.
- 
- (6) http://hevea.inria.fr/index.html

base/bin-prot/doc/.hgignore.in

-README.pdf
-README.txt

base/bin-prot/doc/Makefile

-NAME        := README
-HEVEAFLAGS  := -w 78 -fix -exec ~/bin/xxdate.exe custom.hva 
-TRASH       := $(NAME).pdf $(NAME).fls
-
-all:	text pdf
-
-$(NAME).tex:
-	touch $@
-
--include HeveaMakefile

base/bin-prot/doc/README.tex

-\documentclass[12pt]{article}
-
-\usepackage{hevea}
-
-%BEGIN LATEX
-\usepackage{natbib}
-%END LATEX
-
-\newcommand{\mail}{\mailto{opensource@janestreet.com}}
-\newcommand{\homeurl}{http://www.janestreet.com}
-\newcommand{\athome}[2]{\ahref{\homeurl/#1}{#2}}
-\newcommand{\www}{\athome{}{Markus Mottl}}
-
-\newcommand{\ocaml}{\ahref{http://www.ocaml.org}{OCaml}}
-
-\newcommand{\myhref}[1]{\ahref{#1}{#1}}
-\newcommand{\ocsrc}[2]{\athome{ocaml/#1}{#2}}
-\newcommand{\myocsrc}[1]{\athome{ocaml/#1}{#1}}
-
-\newcommand{\janeshort}{\ahref{http://www.janestreet.com}{Jane Street Holding, LLC}}
-
-\newcommand{\trow}[2]{\quad #1 \quad&\quad #2 \quad\\}
-\newcommand{\trowl}[2]{\trow{#1}{#2}\hline}
-
-%BEGIN LATEX
-\newcommand{\theyear}{\number\year}
-%END LATEX
-
-\title{README: library ``Bin\_prot''}
-\author{
-  Copyright (C) 2007-\theyear \quad \janeshort\\
-  Author: Markus Mottl
-}
-\date{New York, 2011-07-29}
-
-% DOCUMENT
-\begin{document}
-\maketitle
-\section{Directory contents}
-\begin{center}
-\begin{tabular}{|c|c|}
-\hline
-\trowl{Changelog}{History of code changes}
-\trowl{COPYRIGHT}{Notes on copyright}
-\trow{INSTALL}{Short notes on compiling and}
-\trowl{}{installing the library}
-\trowl{LICENSE}{License of this library}
-\trowl{LICENSE.Tywith}{License of Tywith}
-\trowl{Makefile}{Top Makefile}
-\trowl{README.txt}{This text in ASCII format}
-\trowl{doc/}{LaTeX sources for this text}
-\trowl{lib/}{Library sources}
-\trowl{lib\_test/}{Test applications for the Bin\_prot-library}
-\trowl{syntax/}{Preprocessor for type definitions}
-\end{tabular}
-\end{center}
-
-\section{What is ``Bin\_prot''}
-
-This library contains functionality for reading and writing OCaml-values in a
-type-safe binary protocol.  It is extremely efficient, typically supporting
-type-safe marshalling and unmarshalling of even highly structured values at
-speeds sufficient to saturate a gigabit connection.  The protocol is also
-heavily optimized for size, making it ideal for long-term storage of large
-amounts of data.\\
-
-The library is highly dependable and safe to use: a rigorous test suite has
-to date guaranteed that this library has never exhibited a bug in production
-systems in several years of use.  ``Bin\_prot'' has been successfully
-employed in mission-critical financial applications, storing many terabytes
-of structured data derived from thousands of type definitions, and typically
-processing millions of messages a day in realtime for low-latency applications
-that must not crash.\\
-
-Since version two this library should work with all CPU architectures
-currently supported by OCaml, no matter the word size (32 or 64 bit),
-endianness\footnote{Endianness defines the byte order in which machine
-representations of integers are stored in main memory.}, or alignment
-requirements.  It provides users with a convenient and safe way of performing
-I/O on any extensionally defined OCaml type (see later sections for details).
-Functions, objects, first-class modules, as well as values whose type is
-bound through a polymorphic record field are hence not supported.  This is
-hardly ever a limitation in practice.\\
-
-As of now, there is no support for cyclic or shared values.  Cyclic values
-will lead to non-termination whereas shared values, besides requiring more
-space when encoded, may lead to a substantial increase in memory footprint
-when they are read back.  It would not be trivial to support these kinds
-of values in a type-safe way without noticably sacrificing performance.
-If these kinds of values are needed, the user may want to use the as of
-today still unsafe marshalling functions provided by OCaml.\\
-
-This library uses the machine stack for efficiency reasons.  This can
-potentially lead to a crash if the stack limit is reached.  Note that this
-is also a limitation of the (unsafe) standard marshalling functions shipped
-with OCaml.  This problem can happen for large amounts of data if recursion in
-the type definition of the datastructure is not limited to the last element.
-Only in the latter case will tail-recursion allow for (practically) unlimited
-amounts of data.  If this exceedingly rare limitation ever turned out to
-be an issue in a user application, it can often be solved by redefining the
-datatype to allow for tail-recursion.  The limitation cannot be eliminated in
-this library without significant performance impact and increased complexity.
-
-\section{How can you use it?}
-
-The API (.mli-files) in the library directory is fully documented.  Module
-\verb=Common= defines some globally used types, functions, exceptions,
-and values.  \verb=Nat0= implements natural numbers including zero.\\
-
-Modules \verb=Read_ml= and \verb=Write_ml= contain read and write functions
-respectively for all basic types and are implemented in OCaml as far as
-reasonable.  If you only want to read or write single, basic, unstructured
-values, this module is probably the most efficient and convenient for
-doing this.\\
-
-Otherwise you should annotate your type definitions to generate type
-converters automatically (see later sections for details).  The preprocessor
-in \verb=pa_bin_prot.ml= will then generate highly optimized functions
-for converting your OCaml-values to and from the binary representation.
-This automatically generated code will use functions in modules
-\verb=Unsafe_common=, \verb=Unsafe_read_c= and \verb=Unsafe_write_c=,
-which employ unsafe internal representations to achieve this performance.
-The auto-generated code is extremely well-tested and should use these unsafe
-representations correctly.  Developers who want to make manual use of these
-unsafe calling conventions for efficiency are strongly encouraged to test
-their code carefully.\\
-
-The module \verb=Size= allows you to compute the size of basic OCaml-values
-in the binary representations before writing them to a buffer.  The code
-generator will also provide you with functions for your user-defined types.\\
-
-Module \verb=Std= predefines converters for most standard OCaml types.
-If you use the preprocessor macros to generate code from type definitions,
-make sure that the contents of this module is visible by e.g.\ adding the
-following at the top of files using this library:\\
-
-\begin{verbatim}
-  open Bin_prot.Std
-\end{verbatim}
-
-Note that you can shadow the definitions in the above module in the unlikely
-event that the predefined ways of converting data are unsatisfactory to you.\\
-
-The modules \verb=Read_c= and \verb=Write_c= wrap the unsafe low-level
-converters for basic values to ones accessible safely from within OCaml and
-vice versa.  They also export functions for wrapping user-defined converters.
-This should help developers make their converters available in the respective
-other representation (low- or high-level).  The test applications in the
-distribution use these wrappers to verify the correctness of implementations
-for low-level (C) and high-level (OCaml) representations.\\
-
-The module \verb=Type_class= contains some extra definitions for type
-classes of basic values.  These definitions can be passed to the function
-\verb=bin_dump= in module \verb=Utils= to marshal values into buffers of
-exact size using the binary protocol.  However, if bounds on the size of
-values are known, it is usually more efficient to write them directly into
-preallocated buffers and just catch exceptions if the buffer limits are
-unexpectedly violated.  Doing so should never cause a crash.  That way one
-does not have to compute the size of the value, which can sometimes be almost
-as expensive as writing the value in the first place.\\
-
-In module \verb=Utils= the function \verb=bin_read_stream= can be used
-to efficiently read size-prefixed values as written by \verb=bin_dump=
-there with the \verb=header= flag set to \verb=true=.  This module also
-offers several useful functors.  The ones for \verb=binable= types help
-users create readers and writers if a type needs to be converted to or from
-some intermediate representation before marshalling or after unmarshalling
-respectively.  The functors for \verb=iterable= types are helpful if some
-(usually abstract) datatype offers iteration over elements and if the series of
-iterated-over elements alone is sufficient to reconstruct the original value.
-This allows for a more compact protocol and for robustness against changes
-to the internal representation of the datatype (e.g.\ sets, maps, etc.).
-
-\subsection{Examples}
-
-E.g. given the following type definition:\\
-
-\begin{verbatim}
-  type t = A | B
-  with bin_io
-\end{verbatim}
-
-This will generate functions \verb=bin_size_t=, \verb=bin_write_t=, and
-\verb=bin_read_t=.  Furthermore the type class values \verb=bin_writer_t=,
-\verb=bin_reader_t= and \verb=bin_t=.  If you use the annotation
-\verb=bin_write= instead of \verb=bin_io=, then only the write and size
-functions and their type class will be generated.  Specifying \verb=bin_read=
-will generate the read functions and associated type class only.
-The annotation \verb=bin_type_class= will generate the combined type class
-only, thus allowing the user to easily define their own reader and writer
-type classes.  The code generator may also generate low-level entry points
-used for efficiency or backtracking.\\ \\ The preprocessor can also generate
-signatures for conversion functions.  Just add the wanted annotation to the
-type in a module signature for that purpose.
-
-\section{Specification of the Binary Protocol}
-
-The binary protocol does not contain any data other than the minimum needed
-to decode values.  This means that the user is responsible for e.g.\
-writing out the size of messages themselves if they want to be able to
-preallocate sufficiently sized buffers before reading.  The \verb=Utils=
-module provides some simple functions for that matter, though users may
-obtain optimum efficiency by managing buffers themselves.\\
-
-The basic OCaml-values are written out character-wise as described below
-using hex codes for the character encoding.  Some of these values require
-size/length information to be written out before the value (e.g.\ for lists,
-hash tables, strings, etc.).  Size information is always encoded as natural
-numbers (\verb=Nat0.t=).  The little-endian format is used in the protocol
-for the contents of integers on all platforms.\\
-
-\noindent The following definitions will be used in the encoding specifications
-below:
-
-\begin{itemize}
-\item \verb=CODE_NEG_INT8= $\rightarrow$ \verb=0xff=
-\item \verb=CODE_INT16= $\rightarrow$ \verb=0xfe=
-\item \verb=CODE_INT32= $\rightarrow$ \verb=0xfd=
-\item \verb=CODE_INT64= $\rightarrow$ \verb=0xfc=
-\end{itemize}
-
-\subsection{Nat0.t}
-
-If the value is:
-
-\begin{itemize}
-\item $<$ \verb=0x000000080= $\rightarrow$ lower 8 bit of the integer.
-\item $<$ \verb=0x000010000= $\rightarrow$ \verb=CODE_INT16= followed by lower 16 bits of integer.
-\item $<$ \verb=0x100000000= $\rightarrow$ \verb=CODE_INT32= followed by lower 32 bits of integer.
-\item $\geq$ \verb=0x100000000= $\rightarrow$ \verb=CODE_INT64= followed by all 64 bits of integer\footnote{Only supported on 64 bit platforms.}.
-\end{itemize}
-
-Appropriate exceptions will be raised if there is an overflow, e.g.\ if
-a 64 bit encoding is read on a 32 bit platform, or if the 32 bit or 64
-bit encoding overflowed the 30 bit or 62 bit capacity\footnote{One bit is
-reserved by OCaml for GC-tagging, and the sign bit is lost.} of natural
-numbers on their respective platforms.
-
-\subsection{Unit values}
-
-\begin{itemize}
-\item \verb=()= $\rightarrow$ \verb=0x00=
-\end{itemize}
-
-\subsection{Booleans}
-
-\begin{itemize}
-\item \verb=false= $\rightarrow$ \verb=0x00=
-\item \verb=true= $\rightarrow$ \verb=0x01=
-\end{itemize}
-
-\subsection{Strings}
-
-First the length of the string is written out as a \verb=Nat0.t=.  Then the
-contents of the string is copied verbatim.
-
-\subsection{Characters}
-
-Characters are written out verbatim.
-
-\subsection{Integers}
-
-This includes all integer types: \verb=int, int32, int64, nativeint=.
-If the value is positive (including zero) and if it is:
-
-\begin{itemize}
-\item $<$ \verb=0x00000080= $\rightarrow$ lower 8 bit of the integer.
-\item $<$ \verb=0x00008000= $\rightarrow$ \verb=CODE_INT16= followed by lower 16 bits of integer.
-\item $<$ \verb=0x80000000= $\rightarrow$ \verb=CODE_INT32= followed by lower 32 bits of integer.
-\item $\geq$ \verb=0x80000000= $\rightarrow$ \verb=CODE_INT64= followed by all 64 bits of integer.
-\end{itemize}
-
-\noindent If the value is negative and if it is:
-
-\begin{itemize}
-\item $\geq$ \verb=-0x00000080= $\rightarrow$ \verb=CODE_NEG_INT8= followed by lower 8 bit of integer.
-\item $\geq$ \verb=-0x00008000= $\rightarrow$ \verb=CODE_INT16= followed by lower 16 bits of integer.
-\item $\geq$ \verb=-0x80000000= $\rightarrow$ \verb=CODE_INT32= followed by lower 32 bits of integer.
-\item $<$ \verb=-0x80000000= $\rightarrow$ \verb=CODE_INT64= followed by all 64 bits of integer.
-\end{itemize}
-
-All of the above branches will be considered when converting values of
-type \verb=int64=.  The case for \verb=CODE_INT64= will only be considered
-with types \verb=int= and \verb=nativeint= if the architecture supports it.
-\verb=int32= will never be encoded as a \verb=CODE_INT64=.  Appropriate
-exceptions will be raised if the architecture of or the type requested by the
-reader does not support some encoding, or if there is an overflow\footnote{An
-overflow can only happen with int values: one bit is reserved by OCaml for
-the GC-tag.}.
-
-\subsection{Floats}
-
-Floats are written out according to the 64 bit IEEE 754 floating point
-standard, i.e.\ their memory representation is copied verbatim.
-
-\subsection{References and lazy values}
-
-Same as the binary encoding of the value in the reference or of the value
-calculated lazily.
-
-\subsection{Option values}
-
-If the value is:
-
-\begin{itemize}
-\item \verb=None= $\rightarrow$ \verb=0x00=
-\item \verb=Some v= $\rightarrow$ \verb=0x01= followed by the encoding of \verb=v=.
-\end{itemize}
-
-\subsection{Tuples and records}
-
-Values in tuples and records are written out one after the other in the
-order as specified in the type specification without any extra information.
-Polymorphic record fields are supported unless a value of the type bound by
-the field were accessed, which would lead to an exception.
-
-\subsection{Sum types}
-
-Each tag is assigned an integer from $0$ to $n - 1$ in exactly the same order
-as they occur in the type, where $n$ is the number of sum tags in the type.
-If a value of this type needs to be written out, then if:
-
-\begin{itemize}
-\item $n \leq 256 \rightarrow$ the integer associated with the tag is written out as one character (lower 8 bits).
-\item $n \leq 65536 \rightarrow$ the integer associated with the tag is written out as two characters (lower 16 bits).
-\end{itemize}
-
-Sum types with more tags are currently not supported and highly unlikely
-to occur in practice.  Arguments to the tag are written out in the order of
-occurrence without any extra information.
-
-\subsection{Polymorphic variants}
-
-The tags of these values are written out as four characters, more
-precisely as the 32 bit hash value computed by OCaml for the given tag in
-little-endian format.  Any arguments associated with the tag are written
-out afterwards in the order of occurrence without any extra information.\\
-
-When polymorphic variants are being read, they will be matched in order
-of occurrence (left-to-right) in the type and depth-first in the case of
-included polymorphic types.  The first type containing a match for the
-variant will be used for reading.  Note that this only matters if semantic
-invariants are used that may impose constraints on whether a value is legal.
-It is strongly suggested to not use different constraints for polymorphic
-variants with the same representation if it is used within the same type,
-since this is inconsistent and hence confusing.
-
-\subsection{Lists and arrays}
-
-For lists and arrays the length is written out as a \verb=Nat0.t= first,
-followed by all values in the same order as in the datastructure without
-any extra information.
-
-\subsection{Hash tables}
-
-First the size of the hash table is written out as \verb=Nat0.t=.  Then the
-writer iterates over each binding in the hash table and writes out the
-key followed by the value without any extra information.  Note that this
-makes reading somewhat slower than if we used the internal (extensional)
-representation of the hash table, because all values have to be rehashed.
-On the other hand, the format becomes more robust in case the hash table
-implementation changes.
-
-\subsection{Bigarrays of doubles and characters}
-
-First the dimension(s) are written out as \verb=Nat0.t=.  Then the contents
-is copied verbatim.
-
-\subsection{Polymorphic values}
-
-There is nothing special about polymorphic values as long as there are
-conversion functions for the type parameters.  E.g.:
-
-\begin{verbatim}
-  type 'a t = A | B of 'a with bin_io
-  type foo = int t with bin_io
-\end{verbatim}
-
-In the above case the conversion functions will behave as if \verb=foo= had
-been defined as a monomorphic version of \verb=t= with \verb='a= replaced
-by \verb=int= on the right hand side.
-
-\subsection{Abstract datatypes}
-
-If you want to convert an abstract datatype that may impose constraints on
-the well-formedness of values, you will have to roll your own conversion
-functions.  Use the functions in module \verb=Read_c= and \verb=Write_c=
-to map between low-level and high-level representations, or implement those
-manually for maximum efficiency.  The \verb=Utils= module may also come in
-handy as described in earlier sections, e.g.\ if the value can be converted
-to and from an intermediate representation that does not impose constraints,
-or if some sort of iteration is supported by the datatype.
-
-\section{Contact information}
-
-\noindent In the case of bugs, feature requests and similar, you can contact
-us here:\\\\
-
-\hspace{2ex}\mail\\\\
-
-\noindent Up-to-date information concerning this library should be available
-here:\\\\
-
-\hspace{2ex}\homeurl/ocaml\\\\
-
-Enjoy!!\\\\
-
-\end{document}

base/bin-prot/doc/custom.hva

-% INPUT STYLE
-\input{article.hva}
-
-% FANCY SECTION HEADERS WITH NICE COLOURS
-\def\@color{194}
-\input{fancysection.hva}
-
-% FOREGROUND AND BACKGROUND COLOURS
-\renewcommand{\@bodyargs}{TEXT=black BGCOLOR=white}

base/bin-prot/doc/hevea.sty

-% hevea  : hevea.sty
-% This is a very basic style file for latex document to be processed
-% with hevea. It contains definitions of LaTeX environment which are
-% processed in a special way by the translator. 
-%  Mostly :
-%     - latexonly, not processed by hevea, processed by latex.
-%     - htmlonly , the reverse.
-%     - rawhtml,  to include raw HTML in hevea output.
-%     - toimage, to send text to the image file.
-% The package also provides hevea logos, html related commands (ahref
-% etc.), void cutting and image commands.
-\NeedsTeXFormat{LaTeX2e}
-\ProvidesPackage{hevea}[2002/01/11]
-\RequirePackage{comment}
-\newif\ifhevea\heveafalse
-\@ifundefined{ifimagen}{\newif\ifimagen\imagenfalse}
-\makeatletter%
-\newcommand{\heveasmup}[2]{%
-\raise #1\hbox{$\m@th$%
-  \csname S@\f@size\endcsname
-  \fontsize\sf@size 0%
-  \math@fontsfalse\selectfont
-#2%
-}}%
-\DeclareRobustCommand{\hevea}{H\kern-.15em\heveasmup{.2ex}{E}\kern-.15emV\kern-.15em\heveasmup{.2ex}{E}\kern-.15emA}%
-\DeclareRobustCommand{\hacha}{H\kern-.15em\heveasmup{.2ex}{A}\kern-.15emC\kern-.1em\heveasmup{.2ex}{H}\kern-.15emA}%
-\DeclareRobustCommand{\html}{\protect\heveasmup{0.ex}{HTML}}
-%%%%%%%%% Hyperlinks hevea style
-\newcommand{\ahref}[2]{{#2}}
-\newcommand{\ahrefloc}[2]{{#2}}
-\newcommand{\aname}[2]{{#2}}
-\newcommand{\ahrefurl}[1]{\texttt{#1}}
-\newcommand{\footahref}[2]{#2\footnote{\texttt{#1}}}
-\newcommand{\mailto}[1]{\texttt{#1}}
-\newcommand{\imgsrc}[2][]{}
-\newcommand{\home}[1]{\protect\raisebox{-.75ex}{\char126}#1}
-\AtBeginDocument
-{\@ifundefined{url}
-{%url package is not loaded
-\let\url\ahref\let\oneurl\ahrefurl\let\footurl\footahref}
-{}}
-%% Void cutting instructions
-\newcounter{cuttingdepth}
-\newcommand{\tocnumber}{}
-\newcommand{\notocnumber}{}
-\newcommand{\cuttingunit}{}
-\newcommand{\cutdef}[2][]{}
-\newcommand{\cuthere}[2]{}
-\newcommand{\cutend}{}
-\newcommand{\htmlhead}[1]{}
-\newcommand{\htmlfoot}[1]{}
-\newcommand{\htmlprefix}[1]{}
-\newenvironment{cutflow}[1]{}{}
-\newcommand{\cutname}[1]{}
-\newcommand{\toplinks}[3]{}
-%%%% Html only
-\excludecomment{rawhtml}
-\newcommand{\rawhtmlinput}[1]{}
-\excludecomment{htmlonly}
-%%%% Latex only
-\newenvironment{latexonly}{}{}
-\newenvironment{verblatex}{}{}
-%%%% Image file stuff
-\def\toimage{\endgroup}
-\def\endtoimage{\begingroup\def\@currenvir{toimage}}
-\def\verbimage{\endgroup}
-\def\endverbimage{\begingroup\def\@currenvir{verbimage}}
-\newcommand{\imageflush}[1][]{}
-%%% Bgcolor definition
-\newsavebox{\@bgcolorbin}
-\newenvironment{bgcolor}[2][]
-  {\newcommand{\@mycolor}{#2}\begin{lrbox}{\@bgcolorbin}\vbox\bgroup}
-  {\egroup\end{lrbox}%
-   \begin{flushleft}%
-   \colorbox{\@mycolor}{\usebox{\@bgcolorbin}}%
-   \end{flushleft}}
-%%% Postlude
-\makeatother

base/bin-prot/lib/TODO

-Testing:
-
-  bin_write_int_{8,16,32,64}bit
-  bin_size_...

base/bin-prot/lib/bin-prot.odocl

-# OASIS_START
-# DO NOT EDIT (digest: 587ff1270b3446e9490aea8b3ff16a98)
-Binable
-Nat0
-Common
-Unsafe_common
-Unsafe_write_c
-Unsafe_read_c
-Size
-Write_ml
-Read_ml
-Write_c
-Read_c
-Std
-Type_class
-Map_to_safe
-Utils
-# OASIS_STOP

base/bin-prot/lib/binable.ml

-(* Binable: signatures defining generated functions for the binary protocol *)
-
-module type S = sig
-  type t
-
-  val bin_size_t : t Size.sizer
-  val bin_write_t : t Map_to_safe.writer
-  val bin_write_t_ : t Unsafe_write_c.writer
-  val bin_read_t : t Read_ml.reader
-  val bin_read_t_ : t Unsafe_read_c.reader
-  val bin_read_t__ : (int -> t) Unsafe_read_c.reader
-  val bin_writer_t : t Type_class.writer
-  val bin_reader_t : t Type_class.reader
-  val bin_t : t Type_class.t
-end
-
-module type S1 = sig
-  type 'a t
-
-  val bin_size_t : ('a, 'a t) Size.sizer1
-  val bin_write_t :('a, 'a t) Map_to_safe.writer1
-  val bin_write_t_ :('a, 'a t) Unsafe_write_c.writer1
-  val bin_read_t : ('a, 'a t) Map_to_safe.reader1
-  val bin_read_t_ : ('a, 'a t) Unsafe_read_c.reader1
-  val bin_read_t__ : ('a, int -> 'a t) Unsafe_read_c.reader1
-  val bin_writer_t : ('a, 'a t) Type_class.S1.writer
-  val bin_reader_t : ('a, 'a t) Type_class.S1.reader
-  val bin_t : ('a, 'a t) Type_class.S1.t
-end
-
-module type S2 = sig
-  type ('a, 'b) t
-
-  val bin_size_t : ('a, 'b, ('a, 'b) t) Size.sizer2
-  val bin_write_t :('a, 'b, ('a, 'b) t) Map_to_safe.writer2
-  val bin_write_t_ :('a, 'b, ('a, 'b) t) Unsafe_write_c.writer2
-  val bin_read_t : ('a, 'b, ('a, 'b) t) Map_to_safe.reader2
-  val bin_read_t_ : ('a, 'b, ('a, 'b) t) Unsafe_read_c.reader2
-  val bin_read_t__ : ('a, 'b, int -> ('a, 'b) t) Unsafe_read_c.reader2
-  val bin_writer_t : ('a, 'b, ('a, 'b) t) Type_class.S2.writer
-  val bin_reader_t : ('a, 'b, ('a, 'b) t) Type_class.S2.reader
-  val bin_t : ('a, 'b, ('a, 'b) t) Type_class.S2.t
-end

base/bin-prot/lib/common.ml

-(* Common: common definitions used by binary protocol converters *)
-
-open Printf
-open Bigarray
-
-type pos = int
-
-(* Errors and exceptions *)
-
-exception Buffer_short
-exception No_variant_match
-
-module ReadError = struct
-  (* Order of variants matters.  It must jibe with read_stubs.c. *)
-  type t =
-    | Neg_int8
-    | Int_code
-    | Int_overflow
-    | Nat0_code
-    | Nat0_overflow
-    | Int32_code
-    | Int64_code
-    | Nativeint_code
-    | Unit_code
-    | Bool_code
-    | Option_code
-    | String_too_long
-    | Variant_tag
-    | Array_too_long
-    | Hashtbl_too_long
-    | Sum_tag of string
-    | Variant of string
-    | Poly_rec_bound of string
-    | Variant_wrong_type of string
-    | Silly_type of string
-    | Empty_type of string
-
-  let to_string = function
-    | Neg_int8 -> "Neg_int8"
-    | Int_code -> "Int_code"
-    | Int_overflow -> "Int_overflow"
-    | Nat0_code -> "Nat0_code"
-    | Nat0_overflow -> "Nat0_overflow"
-    | Int32_code -> "Int32_code"
-    | Int64_code -> "Int64_code"
-    | Nativeint_code -> "Nativeint_code"
-    | Unit_code -> "Unit_code"
-    | Bool_code -> "Bool_code"
-    | Option_code -> "Option_code"
-    | String_too_long -> "String_too_long"
-    | Variant_tag -> "Variant_tag"
-    | Array_too_long -> "Array_too_long"
-    | Hashtbl_too_long -> "Hashtbl_too_long"
-    | Sum_tag loc -> "Sum_tag / " ^ loc
-    | Variant loc -> "Variant / " ^ loc
-    | Poly_rec_bound loc -> "Poly_rec_bound / " ^ loc
-    | Variant_wrong_type loc -> "Variant_wrong_type / " ^ loc
-    | Silly_type loc -> "Silly_type / " ^ loc
-    | Empty_type loc -> "Empty_type / " ^ loc
-end
-
-exception Read_error of ReadError.t * pos
-exception Read_exc of exn * pos
-exception Poly_rec_write of string
-exception Empty_type of string
-
-let raise_read_error err pos = raise (Read_error (err, pos))
-let raise_read_exc exc pos = raise (Read_exc (exc, pos))
-
-let raise_concurrent_modification loc =
-  failwith (loc ^ ": concurrent modification")
-
-let array_bound_error () = invalid_arg "index out of bounds"
-
-
-(* Buffers *)
-
-type pos_ref = pos ref
-type buf = (char, int8_unsigned_elt, c_layout) Array1.t
-
-let create_buf n = Array1.create Bigarray.char c_layout n
-
-let check_pos (buf : buf) pos =
-  if pos >= Array1.dim buf then raise Buffer_short
-
-let safe_get_pos buf pos_ref =
-  let pos = !pos_ref in
-  check_pos buf pos;
-  pos
-
-let check_next (buf : buf) next =
-  if next > Array1.dim buf then raise Buffer_short
-
-let get_opt_pos ~loc ~var = function
-  | Some pos ->
-      if pos < 0 then
-        invalid_arg (sprintf "Bin_prot.Common.%s: %s < 0" loc var);
-      pos
-  | None -> 0
-
-external unsafe_blit_buf :
-  src_pos : int -> src : buf -> dst_pos : int -> dst : buf -> len : int -> unit
-  = "bin_prot_blit_buf_stub"
-
-let blit_buf ?src_pos ~src ?dst_pos ~dst len =
-  let loc = "blit_buf" in
-  let src_pos = get_opt_pos ~loc ~var:"src_pos" src_pos in
-  let dst_pos = get_opt_pos ~loc ~var:"dst_pos" dst_pos in
-  if len < 0 then invalid_arg "Bin_prot.Common.blit_buf: len < 0"
-  else if len = 0 then (
-    if src_pos > Array1.dim src then
-      invalid_arg "Bin_prot.Common.blit_buf: src_pos > src_len";
-    if dst_pos > Array1.dim dst then
-      invalid_arg "Bin_prot.Common.blit_buf: dst_pos > dst_len")
-  else (
-    if src_pos + len > Array1.dim src then
-      invalid_arg "Bin_prot.Common.blit_buf: src_pos + len > src_len"
-    else if dst_pos + len > Array1.dim dst then
-      invalid_arg "Bin_prot.Common.blit_buf: dst_pos + len > dst_len"
-    else unsafe_blit_buf ~src_pos ~src ~dst_pos ~dst ~len)
-
-external unsafe_blit_string_buf :
-  src_pos : int -> string -> dst_pos : int -> buf -> len : int -> unit
-  = "bin_prot_blit_string_buf_stub" "noalloc"
-
-let blit_string_buf ?src_pos str ?dst_pos buf ~len =
-  let loc = "blit_string_buf" in
-  let src_pos = get_opt_pos ~loc ~var:"src_pos" src_pos in
-  let dst_pos = get_opt_pos ~loc ~var:"dst_pos" dst_pos in
-  if len < 0 then invalid_arg "Bin_prot.Common.blit_string_buf: len < 0"
-  else if len = 0 then (
-    if src_pos > String.length str then
-      invalid_arg "Bin_prot.Common.blit_string_buf: src_pos > str_len";
-    if dst_pos > Array1.dim buf then
-      invalid_arg "Bin_prot.Common.blit_string_buf: src_pos > buf")
-  else (
-    if src_pos + len > String.length str then
-      invalid_arg "Bin_prot.Common.blit_string_buf: src_pos + len > str_len"
-    else if dst_pos + len > Array1.dim buf then
-      invalid_arg "Bin_prot.Common.blit_string_buf: src_pos + len > buf"
-    else unsafe_blit_string_buf ~src_pos str ~dst_pos buf ~len)
-
-external unsafe_blit_buf_string :
-  src_pos : int -> buf -> dst_pos : int -> string -> len : int -> unit
-  = "bin_prot_blit_buf_string_stub" "noalloc"
-
-let blit_buf_string ?src_pos buf ?dst_pos str ~len =
-  let loc = "blit_buf_string" in
-  let src_pos = get_opt_pos ~loc ~var:"src_pos" src_pos in
-  let dst_pos = get_opt_pos ~loc ~var:"dst_pos" dst_pos in
-  if len < 0 then invalid_arg "Bin_prot.Common.blit_buf_string: len < 0"
-  else if len = 0 then (
-    if src_pos > Array1.dim buf then
-      invalid_arg "Bin_prot.Common.blit_buf_string: src_pos > buf_len";
-    if dst_pos > String.length str then
-      invalid_arg "Bin_prot.Common.blit_buf_string: src_pos > str_len")
-  else (
-    if src_pos + len > Array1.dim buf then
-      invalid_arg "Bin_prot.Common.blit_buf_string: src_pos + len > buf_len"
-    else if dst_pos + len > String.length str then
-      invalid_arg "Bin_prot.Common.blit_buf_string: src_pos + len > str_len"
-    else unsafe_blit_buf_string ~src_pos buf ~dst_pos str ~len)
-
-
-(* Miscellaneous *)
-
-let rec copy_htbl_list htbl = function
-  | [] -> htbl
-  | (k, v) :: rest -> Hashtbl.add htbl k v; copy_htbl_list htbl rest
-
-external variant_of_int : int -> [> ] = "%identity"
-
-
-(* Bigarrays *)
-
-type vec32 = (float, float32_elt, fortran_layout) Array1.t
-type vec64 = (float, float64_elt, fortran_layout) Array1.t
-type vec = vec64
-
-type mat32 = (float, float32_elt, fortran_layout) Array2.t
-type mat64 = (float, float64_elt, fortran_layout) Array2.t
-type mat = mat64
-
-
-(* Initialisation *)
-
-external init : unit -> unit = "bin_prot_common_init_stub"
-
-let () =
-  Callback.register_exception "Bin_prot.Common.Buffer_short" Buffer_short;
-  init ()

base/bin-prot/lib/common.mli

-(** Common definitions used by binary protocol converters *)
-
-open Bigarray
-
-(** {2 Buffers} *)
-
-(** Position within buffers *)
-type pos = int
-
-(** Reference to a position within buffers *)
-type pos_ref = pos ref
-
-(** Buffers *)
-type buf = (char, int8_unsigned_elt, c_layout) Array1.t
-
-val create_buf : int -> buf
-(** [create_buf n] creates a buffer of size [n]. *)
-
-val check_pos : buf -> pos -> unit
-(** [check_pos buf pos] @raise Buffer_short if position [pos] exceeds
-    the length of buffer [buf]. *)
-
-val check_next : buf -> pos -> unit
-(** [check_next buf pos] @raise Buffer_short if the next position after
-    [pos] exceeds the length of buffer [buf]. *)
-
-val safe_get_pos : buf -> pos_ref -> pos
-(** [safe_get_pos buf pos_ref] @return the position referenced by
-    [pos_ref] within buffer [buf].  @raise Buffer_short if the position
-    exceeds the length of the buffer. *)
-
-val blit_string_buf :
-  ?src_pos : int -> string -> ?dst_pos : int -> buf -> len : int -> unit
-(** [blit_string_buf ?src_pos src ?dst_pos dst ~len] blits [len]
-    bytes of the source string [src] starting at position [src_pos]
-    to buffer [dst] starting at position [dst_pos].
-
-    @raise Invalid_argument if the designated ranges are invalid.
-*)
-
-val blit_buf_string :
-  ?src_pos : int -> buf -> ?dst_pos : int -> string -> len : int -> unit
-(** [blit_buf_string ?src_pos src ?dst_pos dst ~len] blits [len]
-    bytes of the source buffer [src] starting at position [src_pos]
-    to string [dst] starting at position [dst_pos].
-
-    @raise Invalid_argument if the designated ranges are invalid.
-*)
-
-val blit_buf :
-  ?src_pos : int -> src : buf -> ?dst_pos : int -> dst : buf -> int -> unit
-(** [blit_buf ?src_pos ~src ?dst_pos ~dst len] blits [len] bytes of the
-    source buffer [src] starting at position [src_pos] to destination
-    buffer [dst] starting at position [dst_pos].
-
-    @raise Invalid_argument if the designated ranges are invalid.
-*)
-
-
-(** {2 Errors and exceptions} *)
-
-exception Buffer_short  (** Buffer too short for read/write operation *)
-exception No_variant_match  (** Used internally for backtracking *)
-
-module ReadError : sig
-  type t =
-    | Neg_int8  (** Negative integer was positive or zero *)
-    | Int_code  (** Unknown integer code while reading integer *)
-    | Int_overflow  (** Overflow reading integer *)
-    | Nat0_code  (** Unknown integer code while reading natural number *)
-    | Nat0_overflow  (** Overflow reading natural number *)
-    | Int32_code  (** Unknown integer code while reading 32bit integer *)
-    | Int64_code  (** Unknown integer code while reading 64bit integer *)
-    | Nativeint_code  (** Unknown integer code while reading native integer *)
-    | Unit_code  (** Illegal unit value *)
-    | Bool_code  (** Illegal boolean value *)
-    | Option_code  (** Illegal option code *)
-    | String_too_long  (** String too long *)
-    | Variant_tag  (** Untagged integer encoding for variant tag *)
-    | Array_too_long  (** Array too long *)
-    | Hashtbl_too_long  (** Hashtable too long *)
-    | Sum_tag of string  (** Illegal sum tag for given type *)
-    | Variant of string  (** Illegal variant for given type *)
-    | Poly_rec_bound of string
-        (** Attempt to read data bound through polymorphic record fields *)
-    | Variant_wrong_type of string
-        (** Unexpected attempt to read variant with given non-variant type *)
-    | Silly_type of string
-        (** [Silly_type type_name] indicates unhandled but silly case
-            where a type of the sort [type 'a type_name = 'a] is used
-            with a polymorphic variant as type parameter and included
-            in another polymorphic variant type. *)
-    | Empty_type of string
-        (** Attempt to read data that corresponds to an empty type. *)
-
-  val to_string : t -> string
-  (** [to_string err] @return string representation of read error [err]. *)
-end
-
-exception Read_error of ReadError.t * pos
-(** [ReadError (err, err_pos)] *)
-
-exception Read_exc of exn * pos
-(** [ReadExc (exn, err_pos)] *)
-
-exception Poly_rec_write of string
-(** [PolyRecWrite type] gets raised when the user attempts to write or
-    estimate the size of a value of a type that is bound through a
-    polymorphic record field in type definition [type]. *)
-
-exception Empty_type of string
-(** [EmptyType] gets raised when the user attempts to write or estimate
-    the size of a value of an empty type, which would not make sense. *)
-
-val raise_read_error : ReadError.t -> pos -> 'a
-(** [raise_read_error err pos] *)
-
-val raise_read_exc : exn -> pos -> 'a
-(** [raise_read_exc exc pos] *)
-
-val raise_concurrent_modification : string -> 'a
-(** [raise_concurrent_modification loc] @raise Failure if a binary writer
-    detects a concurrent change to the underlying data structure. *)
-
-val array_bound_error : unit -> 'a
-(** [array_bound_error ()] *)
-
-
-(** {2 Bigarrays} *)
-
-type vec32 = (float, float32_elt, fortran_layout) Array1.t
-type vec64 = (float, float64_elt, fortran_layout) Array1.t
-type vec = vec64
-
-type mat32 = (float, float32_elt, fortran_layout) Array2.t
-type mat64 = (float, float64_elt, fortran_layout) Array2.t
-type mat = mat64
-
-
-(** {2 Miscellaneous} *)
-
-val copy_htbl_list : ('a, 'b) Hashtbl.t -> ('a * 'b) list -> ('a, 'b) Hashtbl.t
-(** [copy_htbl_list htbl lst] adds all [(key, value)] pairs in [lst]
-    to hash table [htbl]. *)
-
-external variant_of_int : int -> [> ] = "%identity"
-
-
-(** {2 NOTE: unsafe functions!!!} *)
-
-external unsafe_blit_buf :
-  src_pos : int -> src : buf -> dst_pos : int -> dst : buf -> len : int -> unit
-  = "bin_prot_blit_buf_stub"
-
-external unsafe_blit_string_buf :
-  src_pos : int -> string -> dst_pos : int -> buf -> len : int -> unit
-  = "bin_prot_blit_string_buf_stub" "noalloc"
-
-external unsafe_blit_buf_string :
-  src_pos : int -> buf -> dst_pos : int -> string -> len : int -> unit
-  = "bin_prot_blit_buf_string_stub" "noalloc"

base/bin-prot/lib/common_stubs.c

-/* Stubs for common binary protocol functions */
-
-#include "common_stubs.h"
-
-value *v_bin_prot_exc_Buffer_short;
-
-CAMLprim value bin_prot_common_init_stub(value __unused v_unit)
-{
-  v_bin_prot_exc_Buffer_short =
-    caml_named_value("Bin_prot.Common.Buffer_short");
-  return Val_unit;
-}
-
-
-/* Utility definitions */
-
-CAMLprim inline __pure value get_buf_ptr_stub(value v_buf, value v_pos)
-{
-  char *sptr = Caml_ba_data_val(v_buf);
-  char *eptr = sptr + Long_val(v_pos);
-  return (value) eptr;
-}
-
-CAMLprim inline __attribute__ ((const)) value
-get_buf_pos_stub(value v_start, value v_cur)
-{
-  return Val_long((char *) v_cur - (char *) v_start);
-}
-
-CAMLprim value get_safe_buf_pos_stub(
-  value __unused v_buf, value v_start, value v_cur)
-{
-  return get_buf_pos_stub(v_start, v_cur);
-}
-
-CAMLprim value shift_sptr_stub(char *sptr, value v_n)
-{
-  return (value) (sptr + Long_val(v_n));
-}
-
-CAMLprim value get_eptr_from_sptr_ptr(char **sptr_ptr, value v_pos)
-{
-  return (value) (*sptr_ptr + Long_val(v_pos));
-}
-
-CAMLprim __malloc char ** alloc_sptr_ptr_stub(value v_buf, value v_pos)
-{
-  char **sptr_ptr = caml_stat_alloc(sizeof(char *));
-  *sptr_ptr = (char *) get_buf_ptr_stub(v_buf, v_pos);
-  return sptr_ptr;
-}
-
-CAMLprim value dealloc_sptr_ptr_stub(value v_buf, char /*@only@*/ **sptr_ptr)
-{
-  unsigned long pos = (*sptr_ptr) - (char *) Caml_ba_data_val(v_buf);
-  free((char **) sptr_ptr);
-  return Val_long(pos);
-}
-
-CAMLprim value set_sptr_ptr_stub(char **sptr_ptr, value v_buf, value v_pos)
-{
-  *sptr_ptr = (char *) Caml_ba_data_val(v_buf) + Long_val(v_pos);
-  return Val_unit;
-}
-
-CAMLprim __pure value get_sptr_ptr_stub(char **sptr_ptr, value v_buf)
-{
-  return Val_long(*sptr_ptr - (char *) Caml_ba_data_val(v_buf));
-}
-
-CAMLprim __pure value get_sptr_ptr_sptr_stub(char **sptr_ptr)
-{
-  return (value) *sptr_ptr;
-}
-
-CAMLprim value set_sptr_ptr_sptr_stub(char **sptr_ptr, char *sptr)
-{
-  *sptr_ptr = sptr;
-  return Val_unit;
-}
-
-CAMLprim value get_ptr_string_stub(char *sptr, char *eptr)
-{
-  unsigned long len = eptr - sptr;
-  value v_str = caml_alloc_string((mlsize_t) len);
-  memcpy(String_val(v_str), sptr, (size_t) len);
-  return v_str;
-}
-
-
-/* Blitting strings to buffers */
-
-static inline __pure char * get_buf(value v_buf, value v_pos)
-{
-  return (char *) Caml_ba_data_val(v_buf) + Long_val(v_pos);
-}
-
-CAMLprim value bin_prot_blit_string_buf_stub(
-  value v_src_pos, value v_str, value v_dst_pos, value v_buf, value v_len)
-{
-  char *str = String_val(v_str) + Long_val(v_src_pos);
-  char *buf = get_buf(v_buf, v_dst_pos);
-  memcpy(buf, str, (size_t) Long_val(v_len));
-  return Val_unit;
-}
-
-CAMLprim value bin_prot_blit_buf_string_stub(
-  value v_src_pos, value v_buf, value v_dst_pos, value v_str, value v_len)
-{
-  char *buf = get_buf(v_buf, v_src_pos);
-  char *str = String_val(v_str) + Long_val(v_dst_pos);
-  memcpy(str, buf, (size_t) Long_val(v_len));
-  return Val_unit;
-}
-
-CAMLprim value bin_prot_blit_buf_stub(
-  value v_src_pos, value v_src, value v_dst_pos, value v_dst, value v_len)
-{
-  struct caml_ba_array *ba_src = Caml_ba_array_val(v_src);
-  struct caml_ba_array *ba_dst = Caml_ba_array_val(v_dst);
-  char *src = (char *) ba_src->data + Long_val(v_src_pos);
-  char *dst = (char *) ba_dst->data + Long_val(v_dst_pos);
-  size_t len = (size_t) Long_val(v_len);
-  if
-    (
-      unlikely(len > 65536)
-      || unlikely(((ba_src->flags & CAML_BA_MAPPED_FILE) != 0))
-      || unlikely(((ba_dst->flags & CAML_BA_MAPPED_FILE) != 0))
-    )
-  /* use [memmove] rather than [memcpy] because src and dst may overlap */
-  {
-    Begin_roots2(v_src, v_dst);
-    caml_enter_blocking_section();
-      memmove(dst, src, len);
-    caml_leave_blocking_section();
-    End_roots();
-  }
-  else memmove(dst, src, len);
-  return Val_unit;
-}

base/bin-prot/lib/common_stubs.h

-/* Common binary protocol definitions */
-
-#ifndef COMMON_STUBS_H
-#define COMMON_STUBS_H
-
-#define _BSD_SOURCE
-#include <sys/types.h>
-
-#include <string.h>
-#include <arpa/inet.h>
-
-#include <caml/config.h>
-#include <caml/memory.h>
-#include <caml/alloc.h>
-#include <caml/fail.h>
-#include <caml/bigarray.h>
-#include <caml/callback.h>
-#include <caml/signals.h>
-
-#ifdef ARCH_INT64_TYPE
-#include "int64_native.h"
-#else
-#include "int64_emul.h"
-#endif
-
-
-/* Endianness- and alignment-independent integer marshalling functions */
-
-#define le8dec(x) (*x)
-
-#ifndef le16dec  /* FreeBSD marshalling functions not available */
-
-#ifdef OS_DARWIN
-/* Darwin platform */
-#include <libkern/OSByteOrder.h>
-
-#define le16dec(ptr) OSReadLittleInt16(ptr, 0)
-#define le32dec(ptr) OSReadLittleInt32(ptr, 0)
-#define le64dec(ptr) OSReadLittleInt64(ptr, 0)
-
-#define be16dec(ptr) OSReadBigInt16(ptr, 0)
-#define be32dec(ptr) OSReadBigInt32(ptr, 0)
-#define be64dec(ptr) OSReadBigInt64(ptr, 0)
-
-#define le16enc(ptr, n) OSWriteLittleInt16(ptr, 0, n)
-#define le32enc(ptr, n) OSWriteLittleInt32(ptr, 0, n)
-#define le64enc(ptr, n) OSWriteLittleInt64(ptr, 0, n)
-
-#define be16enc(ptr, n) OSWriteBigInt16(ptr, 0, n)
-#define be32enc(ptr, n) OSWriteBigInt32(ptr, 0, n)
-#define be64enc(ptr, n) OSWriteBigInt64(ptr, 0, n)
-
-#else
-
-/* Non-Darwin platform */
-/* Emulate with memcpy and endianness conversion functions */
-
-/* Define BSD conversion functions if undefined */
-#ifndef le16toh
-
-/* Define portable byte swapping if undefined */
-/* WARNING: will not work on mixed endian machines! */
-/* WARNING: these functions must be defined by the system in the above case */
-#ifndef bswap_16
-#define bswap_16(value) \
-  (((uint16_t) ((value) & 0xff) << 8) | ((uint16_t) (value) >> 8))
-#endif
-
-#ifndef bswap_32
-#define bswap_32(value) \
-  (((uint32_t) bswap_16(((value) & 0xffff)) << 16) | \
-    (uint32_t) bswap_16(((value) >> 16)))
-#endif
-
-#ifndef bswap_64
-#define bswap_64(value) \
-  (((uint64_t) bswap_32(((value) & 0xffffffff)) << 32) | \
-    (uint64_t) bswap_32(((value) >> 32)))
-#endif
-
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-/* Little-endian architecture */
-#define htobe16(x) bswap_16 (x)
-#define htole16(x) (x)
-#define be16toh(x) bswap_16 (x)
-#define le16toh(x) (x)
-
-#define htobe32(x) bswap_32 (x)
-#define htole32(x) (x)
-#define be32toh(x) bswap_32 (x)
-#define le32toh(x) (x)
-
-#define htobe64(x) bswap_64 (x)
-#define htole64(x) (x)
-#define be64toh(x) bswap_64 (x)
-#define le64toh(x) (x)
-#else
-/* Big-endian architecture */
-#define htobe16(x) (x)
-#define htole16(x) bswap_16 (x)
-#define be16toh(x) (x)
-#define le16toh(x) bswap_16 (x)
-
-#define htobe32(x) (x)
-#define htole32(x) bswap_32 (x)
-#define be32toh(x) (x)
-#define le32toh(x) bswap_32 (x)
-
-#define htobe64(x) (x)
-#define htole64(x) bswap_64 (x)
-#define be64toh(x) (x)
-#define le64toh(x) bswap_64 (x)
-#endif  /* byte order */
-
-#endif  /* BSD conversion functions */
-
-#define le16dec(ptr) \
-  (__extension__ ({ uint16_t __n; memcpy(&__n, ptr, 2); le16toh(__n); }))
-#define le32dec(ptr) \
-  (__extension__ ({ uint32_t __n; memcpy(&__n, ptr, 4); le32toh(__n); }))
-#define le64dec(ptr) \
-  (__extension__ ({ uint64_t __n; memcpy(&__n, ptr, 8); le64toh(__n); }))
-
-#define be16dec(ptr) \
-  (__extension__ ({ uint16_t __n; memcpy(&__n, ptr, 2); be16toh(__n); }))
-#define be32dec(ptr) \
-  (__extension__ ({ uint32_t __n; memcpy(&__n, ptr, 4); be32toh(__n); }))
-#define be64dec(ptr) \
-  (__extension__ ({ uint64_t __n; memcpy(&__n, ptr, 8); be64toh(__n); }))
-
-#define le16enc(ptr, n) \
-  (__extension__ ({ uint16_t __n = htole16(n); memcpy(ptr, &__n, 2); }))
-#define le32enc(ptr, n) \
-  (__extension__ ({ uint32_t __n = htole32(n); memcpy(ptr, &__n, 4); }))
-#define le64enc(ptr, n) \
-  (__extension__ ({ uint64_t __n = htole64(n); memcpy(ptr, &__n, 8); }))
-
-#define be16enc(ptr, n) \
-  (__extension__ ({ uint16_t __n = htobe16(n); memcpy(ptr, &__n, 2); }))
-#define be32enc(ptr, n) \
-  (__extension__ ({ uint32_t __n = htobe32(n); memcpy(ptr, &__n, 4); }))
-#define be64enc(ptr, n) \
-  (__extension__ ({ uint64_t __n = htobe64(n); memcpy(ptr, &__n, 8); }))
-
-#endif  /* OS_DARWIN */
-
-#endif  /* FreeBSD marshalling functions */
-
-
-/* Bin-prot integer codes */
-
-#define CODE_NEG_INT8 (char) -1
-#define CODE_INT16 (char) -2
-#define CODE_INT32 (char) -3
-#define CODE_INT64 (char) -4
-
-
-/* Buffer short exception */
-
-extern value *v_bin_prot_exc_Buffer_short;
-
-
-/* Compiler pragmas and inlining */
-
-/* Forget any previous definition of inlining, it may not be what we mean */
-#ifdef inline
-# undef inline
-#endif
-
-/* The semantics of "inline" in C99 is not what we intend so just drop it */
-#if defined(__STDC__) && __STDC__ && \
-    defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
-# define inline
-#endif
-
-#if defined(__GNUC__) && __GNUC__ >= 3
-# ifndef inline
-#   define inline inline __attribute__ ((always_inline))
-# endif
-# ifndef __pure
-#   define __pure __attribute__ ((pure))
-# endif
-# ifndef __const
-#   define __const __attribute__ ((const))
-# endif
-# ifndef __malloc
-#   define __malloc __attribute__ ((malloc))
-# endif
-# ifndef __unused
-#   define __unused __attribute__ ((unused))
-# endif
-# ifndef __likely
-#   define likely(x) __builtin_expect (!!(x), 1)
-# endif
-# ifndef __unlikely
-#   define unlikely(x) __builtin_expect (!!(x), 0)
-# endif
-#else
-  /* Non-GNU compilers should always ignore "inline" no matter the C-standard */
-# ifndef inline
-#   define inline
-# endif
-# ifndef __pure
-#   define __pure
-# endif
-# ifndef  __const
-#   define __const
-# endif
-# ifndef  __malloc
-#   define __malloc
-# endif
-# ifndef  __unused
-#   define __unused
-# endif
-# ifndef  __likely
-#   define likely(x) (x)
-# endif
-# ifndef  __unlikely
-#   define unlikely(x) (x)
-# endif
-#endif
-
-#endif /* COMMON_STUBS_H */

base/bin-prot/lib/int64_emul.h

-/* Software emulation of 64-bit integer arithmetic, for C compilers
-   that do not support it.  */
-
-#ifndef CAML_INT64_EMUL_H
-#define CAML_INT64_EMUL_H
-
-#include <math.h>
-
-#ifdef ARCH_BIG_ENDIAN
-#define I64_literal(hi,lo) { hi, lo }
-#else
-#define I64_literal(hi,lo) { lo, hi }
-#endif
-
-#define I64_split(x,hi,lo) (hi = (x).h, lo = (x).l)
-
-/* Unsigned comparison */
-static int I64_ucompare(uint64 x, uint64 y)
-{
-  if (x.h > y.h) return 1;
-  if (x.h < y.h) return -1;
-  if (x.l > y.l) return 1;
-  if (x.l < y.l) return -1;
-  return 0;
-}
-
-#define I64_ult(x, y) (I64_ucompare(x, y) < 0)
-
-/* Signed comparison */
-static int I64_compare(int64 x, int64 y)
-{
-  if ((int32)x.h > (int32)y.h) return 1;
-  if ((int32)x.h < (int32)y.h) return -1;
-  if (x.l > y.l) return 1;
-  if (x.l < y.l) return -1;
-  return 0;
-}
-
-/* Negation */
-static int64 I64_neg(int64 x)
-{
-  int64 res;
-  res.l = -x.l;
-  res.h = ~x.h;
-  if (res.l == 0) res.h++;
-  return res;
-}
-
-/* Addition */
-static int64 I64_add(int64 x, int64 y)
-{
-  int64 res;
-  res.l = x.l + y.l;
-  res.h = x.h + y.h;
-  if (res.l < x.l) res.h++;
-  return res;
-}
-
-/* Subtraction */
-static int64 I64_sub(int64 x, int64 y)
-{
-  int64 res;
-  res.l = x.l - y.l;
-  res.h = x.h - y.h;
-  if (x.l < y.l) res.h--;
-  return res;
-}
-
-/* Multiplication */
-static int64 I64_mul(int64 x, int64 y)
-{
-  int64 res;
-  uint32 prod00 = (x.l & 0xFFFF) * (y.l & 0xFFFF);
-  uint32 prod10 = (x.l >> 16) * (y.l & 0xFFFF);
-  uint32 prod01 = (x.l & 0xFFFF) * (y.l >> 16);
-  uint32 prod11 = (x.l >> 16) * (y.l >> 16);
-  res.l = prod00;
-  res.h = prod11 + (prod01 >> 16) + (prod10 >> 16);
-  prod01 = prod01 << 16; res.l += prod01; if (res.l < prod01) res.h++;
-  prod10 = prod10 << 16; res.l += prod10; if (res.l < prod10) res.h++;
-  res.h += x.l * y.h + x.h * y.l;
-  return res;
-}
-
-#define I64_is_zero(x) (((x).l | (x).h) == 0)