Skip to content

cstruct

Packed binary layouts for TypeScript — describe structs with Stage 3 decorators, then read and write Uint8Array data with explicit endianness. Inspired by binrw.

npm·GitHub·MIT

At a glance

StepDescription
Define@c.struct() classes with @c.field(...) on each member
Serializec.write(ctor, instance, endian?)Uint8Array
Parsec.read(ctor, bytes, endian?) → instance
Measurec.sizeof(ctor) — packed size in bytes

Endianness is "little" (default) or "big". Slice buffers when a struct does not start at offset zero.

Example

ts
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)); // 19

Quick 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

bash
npm install @craftycodie/cstruct

Import { 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

TopicPage
First read/writeQuick start
Types, padding, alignmentPrimitives & padding
Structs inside structsNested structs
Variant layoutsUnions
Stored enum valuesEnums
Repeated fieldsArrays
Flag wordsBitfield
Strings, time, custom typesAdvanced fields
Real-world layoutsExample structures
Testing with decoratorsVitest & SWC
read / write / sizeofStruct I/O API
Release historyChangelog