[ANN] Inscription.jl - zero allocation reading and writing of arbitrary values

I’m excited to announce my new package Inscription.jl.

In brief, Inscription provides abstractions for reading and writing values to I/O or memory. The abstractions are:

  • Generic over BufferIO’s abstract readers and writers (and also work for reading and writing directly from/into MemoryViews’ memory types)
  • Zero allocation and fast, even in the generic case.
  • Recoverable: You never read or write half a value before erroring, and errors are actionable.

The whole premise of Inscription really is the zero allocation goal. Inscription’s entire design sort of fell out of an effort to create fast, generic abstractions for reading and writing arbitrary values without allocating.

When to use Inscription

Inscription is especially useful as a building block for I/O-heavy packages, e.g. BSON or GZIP parsers.

You may want to look into Inscription if you:

  • Care how many nanoseconds and allocations it takes to print an integer into an IO;
  • Find yourself using unsafe_load and unsafe_store! to do I/O operations for performance;
  • Find yourself writing boilerplate to handle early EOF when reading a UInt32 from a stream.

I imagine someone like @quinnj or @nhz2 might be interested.

On the other hand, you probably don’t want to use Inscription if you’re fine with the OK, but not great, performance of Base’s IO, and don’t need detailed error handling. In these cases, Base can serve you just fine, and it’s not worth learning a new set of abstractions.

It’s especially important to know that Inscription has not been designed to be easy to use. Whenever there was a design tradeoff between ease of use and what I believed to be semantics that were consistent and conducive to high performance, I chose the latter.
I don’t think Inscription is overengineered, though. I really do think each of its many abstractions maps onto something I’ve been hand-implementing several times before.

Try it out

You can try it out at GitHub - BioJulia/Inscription.jl: Read and write any value directly into I/O objects with zero allocations. · GitHub. I’ll register it shortly, but I should say that the package is currently not polished. I would like to get feedback about the overall feel of the package before I put a lot of work into polishing the details.
In particular, I’d like to warn that:

  • The docs are about half written by AI, so they’re characteristically verbose and unfocused. I’ll rewrite them entirely soon-ish.

  • I still need to dogfood it some more. I plan on using this package in a few BioJulia packages, which hopefully should refine the design a little more. However, the overall design is settled now.

So, the package is a little half-baked yet, and I post this here not to evangelize this package that I’m 100% sure is amazingly useful, but to get feedback from others than my AI agents and my own dogfooding.

Background

As you may know, I’ve been developing and evangelizing dogfooding my BufferIO package for about a year now (1, 2). BufferIO is the implementation of the idea that I/O objects ought to provide the buffer straight to users to copy bytes from or into.

Once you have that abstraction, it’s pretty obvious to ask why you can’t just write whatever into the BufferIO-provided buffer so all your low-level I/O operations are allocation free. And indeed earlier versions of BufferIO included methods like write(::AbstractBufWriter, ::Float64). But the abstraction was never a good fit for BufferIO, and I eventually removed such methods. Nearly all my BufferIO-based packages now contain functions that load/store using pointer operations, while manually dealing with the lower-level buffer details that pointer operations require, in each downstream package.

That worked, but it didn’t feel right: I had identified a need (writing non-UInt8 types into BufferIO types), and identified that BufferIO’s existing abstractions couldn’t express that without complicating BufferIO, so surely the solution is to solve this once, in a package?
After a few dead-end attempts and a lot of AI prototyping, about six months of intermittent work later, I arrived at a design I liked, which is Inscription.

Examples

Reading and writing values

You can load values from an AbstractBufReader, or store them to an AbstractBufWriter, using an Encoding, which is a trait type describing how a type is serialized.

Inscription provides a whole bunch of functions to read and write - e.g. try_load for error handling, load_all! to fill an array, or decode to read from a vector without a reader. Below, I just use the basic load and store.

using Inscription: Encoding, load, store
using BufferIO: AbstractBufReader, AbstractBufWriter

# Store each value in `src` to `io`, each followed by a space
function store_values(io::AbstractBufWriter, src::AbstractVector, enc::Encoding)
    for x in src
        store(io, x, enc)
        write(io, UInt8(' '))
    end
    return io
end

# Load values of type `T` into `dst`, each followed by a space
function load_values!(dst::AbstractVector{T}, io::AbstractBufReader, enc::Encoding) where {T}
    for i in eachindex(dst)
        dst[i] = load(io, T, enc)
        read(io, UInt8) == UInt8(' ') || error("Expected a space")
    end
    return dst
end

Implementing reading / writing for custom types

You implement a “codec” for each type / Encoding combination, which then makes all of Inscription’s reading and writing functions work.
Inscription provides a series of codec schemes for cases of varying complexity. I’ll show one that is easy to implement, and one that is complex.

Easy

Declare the BitsLoadable() codec scheme to opt into (safe) pointer-based I/O. This is the easiest and fastest option.

using Inscription: Inscription, BitsLoadable, Endianness

struct Point2D
    x::Float32
    y::Float32
end

Inscription.codec_scheme(::Type{Point2D}, ::Endianness) = BitsLoadable()

Complex

Here, I write a manual codec to parse a UInt32 from decimal text, and to write it as decimal text, using a custom Encoding.
We also define a custom error type for users’ error handling.

using Inscription: Inscription, Encoding, DecodeInput, EncodeOutput,
    peek_byte, reserve_bytes, Invalid, Unbounded, @?

struct ASCIIDecimal <: Encoding end

@enum ASCIIParseErrors emptyint overflow

function Inscription.codec_max_encoded_size(::Type{UInt32}, ::ASCIIDecimal)
    return Unbounded()
end

function Inscription.codec_decode_invalid_type(::Type{UInt32}, ::ASCIIDecimal)
    return ASCIIParseErrors
end

function Inscription.codec_try_decode(
        input::DecodeInput,
        ::Type{UInt32},
        ::ASCIIDecimal
    )
    value = UInt64(0)
    n_bytes_read = 0
    while true
        byte = @? peek_byte(input, n_bytes_read + 1)
        (byte !== nothing && in(byte, 0x30:0x39)) || break
        value = value * 10 + (byte - 0x30)
        value > typemax(UInt32) && return Invalid(overflow)
        n_bytes_read += 1
    end
    iszero(n_bytes_read) && return Invalid(emptyint)
    return (value % UInt32, n_bytes_read)
end

function Inscription.codec_try_encode!(
        output::EncodeOutput,
        x::UInt32,
        ::ASCIIDecimal
    )
    n = ndigits(x)
    mem = @? reserve_bytes(output, n)
    for i in n:-1:1
        (x, r) = divrem(x, UInt32(10))
        mem[i] = UInt8('0') + r % UInt8
    end
    return n
end

Benchmarks

I ran store_values and load_values! from the first example with the two codecs above and computed the average per-element load or store time. The Base timings compare to equivalent hand-rolled implementations that use Base’s IOBuffer, read and write (and for decimal integers, print, readuntil and parse).

The store timings for ASCII decimals could be made even faster by using Base’s algorithm for printing integers in decimal. I opted for a simpler algorithm for demonstration purposes. The codec above still beats Base because it skips allocating a String and copying it into the IOBuffer.

Type, encoding Operation Inscription Base
Point2D, little endian store 1.8 ns, 0 allocs 14.9 ns, 2 allocs
load 0.9 ns, 0 allocs 1.0 ns, 0 allocs
UInt32, ASCII decimal store 10.8 ns, 0 allocs 15.6 ns, 1 alloc
load 7.1 ns, 0 allocs 33.5 ns, 3 allocs

(these timings are on Julia 1.14-beta1 and BufferIO’s master branch)

1 Like