cstruct
Packed binary layouts for TypeScript — describe structs with Stage 3 decorators, then read and write Uint8Array data with explicit endianness. Inspired by binrw.
At a glance
| Step | Description |
|---|---|
| Define | @c.struct() classes with @c.field(...) on each member |
| Serialize | c.write(ctor, instance, endian?) → Uint8Array |
| Parse | c.read(ctor, bytes, endian?) → instance |
| Measure | c.sizeof(ctor) — packed size in bytes |
Endianness is "little" (default) or "big". Slice buffers when a struct does not start at offset zero.
Example
import { c } from "@craftycodie/cstruct";
@c.struct()
class Dog {
@c.field("u8")
bone_pile_count!: number;
@c.field("u16", { pad_before: 1 })
favorite_bone!: number;
@c.field(c.String(16))
name!: string;
}
const dog = new Dog();
dog.bone_pile_count = 2;
dog.favorite_bone = 0x12;
dog.name = "Rudy";
const bytes = c.write(Dog, dog, "little");
const parsed = c.read(Dog, bytes, "little");
console.log(parsed.favorite_bone); // 18
console.log(parsed.name); // "Rudy"
console.log(c.sizeof(Dog)); // 19Quick start → · Install & setup →
What you can model
Scalars & layout — Fixed-width integers and floats, bigint u64/i64, explicit padding, and nested structs. Field order and size come from the class definition, not hand-maintained offsets.
Discriminated data — Validated enums, discriminated unions (@c.union, c.arm, c.when), and fixed-length arrays.
Advanced fields — Built-in c.Bool, c.String, c.WString, c.Time64, and c.bitfield for flag words, or subclass c.AdvancedType for your own wire format in a single field slot.
Get started
npm install @craftycodie/cstructImport { c } from @craftycodie/cstruct before any @c.struct() class so the Symbol.metadata polyfill is installed. Stage 3 decorators are required (experimentalDecorators: false, decoratorVersion: "2022-03" with SWC or Vitest). See Install & setup for compiler and test runner configuration.
Guide map
| Topic | Page |
|---|---|
| First read/write | Quick start |
| Types, padding, alignment | Primitives & padding |
| Structs inside structs | Nested structs |
| Variant layouts | Unions |
| Stored enum values | Enums |
| Repeated fields | Arrays |
| Flag words | Bitfield |
| Strings, time, custom types | Advanced fields |
| Real-world layouts | Example structures |
| Testing with decorators | Vitest & SWC |
read / write / sizeof | Struct I/O API |
| Release history | Changelog |