Datalit: A macro to generate fluent, readable static binary data

⚓ Rust    📅 2025-09-14    👤 surdeus    👁️ 2      

surdeus

I just published the datalit crate, which provides a fluent, readable DSL for
generating static binary data at compile time. It's targeted at anyone writing
code that has to work with structured binary data, especially to create data
for tests.

Highlights:

  • Uses existing Rust literal syntax to make data easy to read.
  • Handles byte order and endianness without needing to work with raw bytes.
  • Allows for named labels in the data, and can generate offsets without having
    to manually count bytes.
  • Generates data entirely at compile time, and works in no_std contexts.

Example:

This creates a PNG file header and data block:

# use datalit::datalit;
let png_data = datalit!(
  // PNG Signature:
  {
    // High bit set to differentiate it from text files
    0x89,

    // Literal name in header
    b"PNG",

    // DOS-style line ending to catch if a DOS->Unix text file conversion
    // happened.
    0x0D0A,

    // DOS end-of-file character.
    0x1A,

    // Unix-style line ending to catch if a Unix->DOS text file conversion
    // happened.
    0x0A,
  },

  // Set integer mode to big-endian
  @endian = be,

  // PNG Chunk:

  // Length of the chunk data
  len('chunk1): u32,

  // The PNG chunk type is a 4-byte ASCII code.
  b"IHDR",
  'chunk1: {
    // Image width
    256u32,
    // Image height
    256u32,

    // Bit depth
    16u8,
    // Color type (2 == Truecolor)
    2u8,
    // Compression, Filter, Interlace
    0u8, 0u8, 0u8
  },
  // The CRC. Not supported (yet?).
  0xDEADBEEF,
);

Notes: no_std, no unsafe, MSRV 1.89.

Why?: I was working on a crate for some obscure file formats and realized
maintainable tests would be hard when everything is raw binary. I wanted test
fixtures that are readable and reviewable yet still directly usable by the code
under test. I'm using this crate for that purpose, and it's worked well so far!

If you think this could be useful, you're welcome to try it out! The docs are also available.

1 post - 1 participant

Read full topic

🏷️ Rust_feed