Apache Thrift compact-protocol codec
README.md

thrift #

Apache Parquet stores its file footer and every page header in the Thrift compact protocol, so reading or writing a Parquet file starts with a Thrift codec. thrift is that codec in OCaml, without the Thrift IDL compiler or RPC runtime. A caller describes a struct with typed combinators (Thrift.Codec), or reads any message as a schema-free value tree (Thrift.Value) and walks it with a cursor (Thrift.Cursor).

The codec covers:

  • structs and their fields, in both the short and the long field-header forms, with booleans carried in the field header. In the short form, one byte holds the field id minus the previous field's id (when that delta is 1 to 15) in its high nibble and the type in its low nibble; otherwise, in the long form, the high nibble is 0 and the id follows as a zig-zag varint. Type 1 means boolean true and type 2 boolean false, so no value byte follows a boolean field;
  • the base types bool, byte, i16, i32 and i64 (zig-zag varints: zig-zag maps signed to unsigned so that small magnitudes stay small, 0, -1, 1, -2 becoming 0, 1, 2, 3, and the result is written seven bits per byte, least significant first, with the high bit set on every byte but the last), double (little-endian), binary (also used for strings) and uuid;
  • the containers list, set and map;
  • streaming decode with Thrift.of_reader, which stops on the byte after the struct, so a page header followed by its page data leaves the reader on the data.

Installation #

$ opam install thrift

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install thrift

Usage #

A value carries its own type, so encoding round-trips through decoding:

# let roundtrips v = Thrift.of_string_exn Thrift.Codec.Value.t (Thrift.to_string Thrift.Codec.Value.t v) = v
val roundtrips : Thrift.t -> bool = <fun>
# roundtrips (Thrift.Struct [ (1, Thrift.I64 42L); (2, Thrift.Binary "hi") ])
- : bool = true

An empty struct is a single stop byte:

# Thrift.to_string Thrift.Codec.Value.t (Thrift.Struct []) |> String.length
- : int = 1

Booleans inside a struct cost no value bytes, since the value lives in the field header: 0x11 is delta 1 and type 1, field 1 set to true, and the 0x00 stop byte ends the struct:

# Thrift.to_string Thrift.Codec.Value.t (Thrift.Struct [ (1, Thrift.Bool true) ]) |> String.length
- : int = 2