Video in progress
You need to design your own binary file format (for example for an index or an export). What do you build in from the start to make it readable for years and safe?
A magic byte sequence and a format version at the start of the file, explicit endianness, a length and checksum on every block, an extensible header (so unknown fields can be skipped), and an upper bound on every length when reading. Optionally, a footer/index at the end.
📖 Answer
The costliest mistakes in a format show up later: you didn't include a version field and now the new reader can't recognize the old file; or a corrupt file forces the reader to allocate a 4 GB array.
I start from a structure like this:
Header: magic(4) | version(u16) | flags(u16) | headerLen(u32) | ...extra fields
Blocks: [type(u8) | len(u32) | payload | crc32c(u32)] ...
Footer: indexOffset(u64) | blockCount(u32) | crc32c(u32) | magic(4)
What each part is for:
- Magic. Identify the file type from the first 4 bytes: reject the wrong file before parsing it deeply.
- Version +
headerLen. If a new version adds a field to the header, an old reader skips the rest usingheaderLen. If the major version changes, a clear error. - Endianness. Chosen once and documented. Java's
ByteBufferis big-endian by default; native tools working with x86 may expect little-endian:buf.order(ByteOrder.LITTLE_ENDIAN). - Length + CRC on every block. You find the corruption in the block itself, and you cut off an incompletely written tail.
- Skipping unknown block types. Because
lenis there, an old reader skips a new block type without breaking: forward compatibility. - Footer + index. In a large file you can jump straight to the block you need; since the footer is at the end, the file is written sequentially and the index is added at the end (this is how Parquet works).
Security: assume the file comes from an untrusted source. Check every len against the file size and a logical maximum, set a depth limit on recursive structures, and test the parser with fuzzing (Jazzer works well for Java).
And ask the question up front: isn't a ready-made format enough? Parquet or Arrow for tabular data, Avro container files for a stream of records, SQLite for key-value. Your own format means your own library, your own documentation, and one team that can read it.
Sign up to mark studied questions and save your progress.