agentleFS
mixcodemixcode/binarystruct/llms-full.txt

binarystruct

llms.txt5 starsChanged 6 months agoBSD-3-ClauseView on GitHub

This document contains rules, syntax constraints, and patterns to help LLM agents and code assistants successfully integrate and use the binarystruct library. binarystruct uses the binary struct tag to map Go struct fields to binary layouts. * Where the encoding comes from (most specific first): a field's own encoding= tag → the struct's sentinel encoding= (Rule E) → the Marshaler's DefaultTextEncoding. The encoding must be registered either way. Example struct-wide default: _ struct{} \binary:"endian=big,encoding=shift-jis"\. (Codegen supports struct-level endian= and encoding=;…

  • Installs packages

The file

We split this llms-full.txt into the rules it gives an agent

8 rules. About 0 are common, 1 is distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When unmarshalling into an interface field, you must choose one of two patterns:

    line 57
  2. Very specific:

    safe_binarystruct (portability): If the code is compiled for platforms that restrict Go's unsafe package (e.g., Google App Engine), …

    line 73
  3. Very specific:

    If you encounter layout or padding issues, use the Inspect API to print out the struct's byte offsets, sizes, and values.

    line 161
  4. Very specific:

    Critical: If your struct uses custom codecs or custom text encodings, you MUST call Inspect on your configured Marshaler instance.

    line 163
  5. Very specific:

    When debugging failures (premature EOFs, array sizing mismatches, etc.), inspect the returned error's properties.

    line 189
  6. Very specific:

    Always check for DecodeError to diagnose data stream mismatches:

    line 194
  7. Very specific:

    Error Types: If a validation constraint is violated, the unmarshalling function returns a DecodeError wrapping …

    line 213
  8. Very specific:

    Add a //go:generate comment directive referencing the binarystruct-codegen CLI tool.

    line 231

≈ “Common” is an estimate: at least 1 in 5 of the 1,484 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
llms-full.txt
# AI and LLM Agent Instructions for binarystruct

This document contains rules, syntax constraints, and patterns to help LLM agents and code assistants successfully integrate and use the `binarystruct` library.

---

## 1. Syntax Cheat Sheet

`binarystruct` uses the `binary` struct tag to map Go struct fields to binary layouts.

```go
`binary:"[array_len]TYPE(buf_len),option1=val1,option2"`
```

### Supported Types
* **Fixed Scalars**: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`
* **Bitmaps (type-agnostic)**: `byte` (1 byte), `word` (2 bytes), `dword` (4 bytes), `qword` (8 bytes)
* **Floats**: `float32`, `float64`
* **Strings**:
  * `string`: Raw byte string (padded with `0` up to `buf_len` if specified)
  * `bstring`, `wstring`, `dwstring`: Length-prefixed string (1, 2, or 4-byte length prefix)
  * `zstring`, `z16string`: Null-terminated string (C-style or UTF-16 style)
* **Padding**: `pad(size)` (inserts zero bytes on marshal; skips bytes on unmarshal)
* **Other**: `ignore` or `-` (skips field), `any` (default primitive layout), `custom` (custom codec)

### Key Options
* `encoding=NAME`: String character conversion (e.g., `shift-jis`, `utf-16le`).
* `endian=big|little|inverse`: per-field byte order **override** (Rule G). The struct's overall order is declared on a blank `_ struct{}` sentinel field — see Rule E. `inverse` flips the inherited byte order recursively.
* `codec=NAME`: Reference to a custom registered codec.
* `omittable[=Expression]`: Marks a trailing field as optional (suppresses `io.EOF` errors at start of field or skips based on struct byte-offset check).
* `range=min..max`: Enforces range check validation on integers and float values (e.g. `range=1..100`, open ranges `range=0..` or `range=..100`).
* `match=pattern`: Enforces regex match validation on string values (e.g. `match=^[A-Z0-9]+$`).
* `valueof=Expr`: Auto-computes an integer field's serialized value from other fields, using arithmetic plus the built-ins `bytelen(F)` (encoded byte length of any field F) and `count(F)` (element count of an array/slice field F) — encode-only, emit-only. Custom multi-arg evaluators registered with `Marshaler.AddValueOf` (e.g. `valueof=CRC32(Type, Data)`) also validate on decode. See Section 7.
* `const=Value`: (encode + decode) Emits a fixed value on encode (ignoring the Go field) and validates it on decode (`ErrValidationError` on mismatch) — ideal for magic numbers/signatures. Integer target: `const=0x04034b50` (an integer expression; **endian-sensitive** — see §8). Byte-sequence target `[N]byte`/`string(N)`: `const=0x89504e470d0a1a0a` (hex blob, natural byte order, endian-independent). See Section 8.

---

## 2. Crucial Coding Rules & Constraints

### A. String Encodings Must Be Registered
* **Rule**: There are no default text encodings (other than raw UTF-8 bytes). Using `encoding=shift-jis` or similar in a tag will fail unless you first register the encoding on the `Marshaler` instance.
* **Code pattern**:
  ```go
  // order-free if the struct declares its order; else NewMarshalerOrder(order)
  ms := binarystruct.NewMarshalerOrder(binarystruct.LittleEndian)
  ms.AddTextEncoding("shift-jis", htmlindex.Get("shift-jis"))
  blob, err := ms.Marshal(&v) // methods take NO order argument
  ```
* **Where the encoding comes from** (most specific first): a field's own
  `encoding=` tag → the struct's sentinel `encoding=` (Rule E) → the Marshaler's
  `DefaultTextEncoding`. The encoding must be registered either way. Example
  struct-wide default: `_ struct{} \`binary:"endian=big,encoding=shift-jis"\``.
  (Codegen supports struct-level `endian=` and `encoding=`; only inheritance via
  embedding is codegen-unsupported.)

### B. Interface & Polymorphic Payload Unmarshalling
When unmarshalling into an interface field, you must choose one of two patterns:
1. **Strategy 1 (Pre-assigned)**: Pre-initialize the interface field with a pointer to a concrete structure before calling `Unmarshal`.
   ```go
   var data MessageA
   pkt := Packet{Payload: &data}
   binarystruct.Unmarshal(blob, &pkt) // Packet declares its order via the `_` sentinel
   ```
2. **Strategy 2 (Custom Codec)**: Implement a custom `Codec` that reads a preceding type field and dynamically allocates the concrete type.
   ```go
   func (s *DynamicPayloadCodec) Decode(r io.Reader, parent reflect.Value, fieldIndex int, order binarystruct.ByteOrder) (interface{}, int, error) {
       msgType := parent.FieldByName("MsgType").Uint()
       // Allocate dynamically and decode...
   }
   ```

### C. Build Tags
* **`safe_binarystruct` (portability)**: If the code is compiled for platforms that restrict Go's `unsafe` package (e.g., Google App Engine), compile and test with the `safe_binarystruct` build tag — it swaps the unsafe pointer interpreter for the reflection-only path (byte-identical, slower):
  ```bash
  go test -tags safe_binarystruct ./...
  ```
* **`experiment_simd` (performance, opt-in)**: On amd64 with Go 1.26+, building with `-tags experiment_simd` **and** `GOEXPERIMENT=simd` vectorizes endian byte-swaps (AVX2) in the unsafe runtime path and in codegen generated with `-unsafe-bulk`. It is purely a speed knob — output bytes are identical, and any other platform/build silently uses the scalar fallback:
  ```bash
  GOEXPERIMENT=simd go build -tags experiment_simd ./...
  ```
  Mutually exclusive in effect with `safe_binarystruct` (the safe path has no SIMD). Leave it off unless you are byte-swap bound on amd64; it depends on an experimental Go package (`simd/archsimd`) with no compatibility promise.

### D. Expressions (sizes and computed values)
Wherever a tag takes a size or computed value — `[len]`, `(buf_len)`, `omittable=`, and `valueof=` — it accepts an expression, not just a literal:
* **Operands**: integer literals (decimal, hex `0x1F`, octal `0o17`, binary `0b1010`; `_` digit separators allowed) and references to other struct fields.
* **Operators**: `+`, `-`, `*`, `/`, and parentheses.
* **Reference scope**: decode-side expressions (`[len]`, `(buf_len)`, `omittable`) may reference only fields defined **before** the target. The encode-only `valueof` (Section 7) may reference any field, because the whole Go value is available when encoding.
* **Functions** `bytelen(F)` / `count(F)` are available **only** inside `valueof` (Section 7), never in decode-side expressions.
* **Multidimensional arrays**: stack length prefixes — `[2][3]int16`, `[2][2][2]int8` — to encode/decode nested Go arrays/slices in row-major order; each dimension is its own expression (`[Rows][Cols]uint8`). `binarystruct-codegen` supports a **scalar leaf** (fixed arrays, or slices with all dimensions specified); non-scalar leaves (strings, nested structs, pointers) or mixed fixed/slice nesting fall back to the runtime interpreter.

### E. Byte order is declared on the struct; the API is order-free
A struct states its byte order with a blank `_ struct{}` **sentinel** field, so the format's endianness lives with the type that describes it. The package functions and the `Marshaler` methods (`Marshal`, `Unmarshal`, `Write`, `Read`, `Append`, `Inspect`) take **no** `order` argument:
```go
type Header struct {
	_     struct{} `binary:"endian=big"` // this format is big-endian
	Magic uint32   `binary:"uint32"`
	Size  uint32   `binary:"uint32"`
}
blob, _ := binarystruct.Marshal(&h)        // no order argument
_, _    = binarystruct.Unmarshal(blob, &h) // no order argument
```

**Order resolution, most specific first:** a per-field `endian=` tag → the struct's `_` declaration → the `Marshaler`'s `Order` fallback → otherwise encoding/decoding a multi-byte value **fails loud** (`"no byte order: declare endian= on the struct or use NewMarshalerOrder(order)"`).

**Values that can't declare an order** (a bare scalar, a third-party struct) take a fallback from the Marshaler — this is the only place an order is passed:
```go
ms := binarystruct.NewMarshalerOrder(binarystruct.BigEndian)
b, _ := ms.Marshal(&someScalar) // uses the fallback order
```
`NewMarshaler()` makes one with **no** fallback (every value must declare its own). A struct's declaration **wins** over the fallback — `NewMarshalerOrder(LittleEndian).Marshal(&aBigEndianStruct)` still emits big-endian, because the format's order is intrinsic.

**Embedding** a struct that declares an order propagates it, giving a reusable base:
```go
type bigEndian struct{ _ struct{} `binary:"endian=big"` } // 0 bytes; declares the order
type PNG struct {
	bigEndian
	Width uint32 `binary:"uint32"`
}
```

### F. Concurrency
The package-level `Marshal`/`Unmarshal`/`Write`/`Read` are safe for concurrent use (each call allocates its own `Marshaler`), and independent `Marshaler` instances may run concurrently (the only shared global is a `sync.Map` metadata cache). Do **not** share a single `*Marshaler` across goroutines: it lazily populates an internal encoder cache (and `AddTextEncoding` mutates it), and it reuses an internal scalar scratch buffer during encode/decode — neither is locked, so a shared instance races even when no text encoding is registered. Use one instance per goroutine, or the package-level functions.

### G. The struct order propagates; per-field `endian=` is only an override (common trap)
The struct's declared order (the `_` sentinel, Rule E) applies to the **entire** value and **propagates automatically into every field and nested struct**. The per-field `endian=big|little|inverse` tag is purely an **override** for the rare field that differs (a mixed-endian format); `inverse` flips relative to the inherited order.

* **Do not tag every field with `endian=`.** Declare the order once on the struct and tag *only* the exceptions. A struct whose fields all share its declared order needs **no** per-field `endian=` tags.
* Per-field `endian=` is for heterogeneity, not for choosing the format's overall endianness — that is the struct-level declaration's job.

```go
// Right: order declared once on the struct; no per-field endian tags needed.
type Header struct {
	_     struct{} `binary:"endian=little"` // whole struct is little-endian
	Magic uint32   `binary:"uint32"`
	Size  uint32   `binary:"uint32"`
}

// per-field endian= belongs only on the field that breaks from the struct order:
type Mixed struct {
	_  struct{} `binary:"endian=little"`
	LE uint32   `binary:"uint32"`            // little (the struct order)
	BE uint32   `binary:"uint32,endian=big"` // this one field overrides
}
```

### H. Migrating from pre-0.3.0 (breaking renames)
**Full upgrade path with before/after code and a checklist: [MIGRATION.md](MIGRATION.md).** In short, v0.3.0 aligned the API with Go standard-library conventions; when reading or updating older code, translate:
* **`Marshaller` → `Marshaler`** (type), including `…WithMarshaller` → `…WithMarshaler`.
* **Order removed from the API:** `Marshal(v, order)` / `Unmarshal(data, order, v)` / `Write` / `Read` / `Inspect` (package funcs *and* methods) → declare the order on the struct (`_ struct{}` `binary:"endian=…"`) and call order-free; for a value that declares none, use `NewMarshalerOrder(order)`. The old `NewMarshaler(order)` → `NewMarshalerOrder(order)`.
* **Custom codecs:** `Serializer`/`Serialize`/`Deserialize` → `Codec`/`Encode`/`Decode`; `AddSerializer` → `AddCodec`; and the tag `serializer=NAME` → `codec=NAME`.

For the **type-spelling change only**, a one-line alias in your own code keeps old `Marshaller` *type references* compiling during a gradual migration:
```go
type Marshaller = binarystruct.Marshaler // shim: fixes the spelling only
```
The alias does **not** address the method-signature (dropped `order`), the `Codec` rename, or the `codec=` tag — those call sites still need updating. The package itself ships no deprecated alias.

---

## 3. Debugging Layout Issues
If you encounter layout or padding issues, use the `Inspect` API to print out the struct's byte offsets, sizes, and values.

* **Critical**: If your struct uses custom codecs or custom text encodings, you **MUST** call `Inspect` on your configured `Marshaler` instance. Using the package-level `binarystruct.Inspect(...)` will use a default Marshaler and show custom fields with size `0`.

```go
// Standard layout (myStruct declares its order via the `_` sentinel):
layout, _ := binarystruct.Inspect(&myStruct)

// For a custom-configured Marshaler (custom codecs/encodings):
ms := binarystruct.NewMarshalerOrder(binarystruct.BigEndian) // fallback order for undeclared structs
// ms.AddTextEncoding(...) / ms.AddCodec(...)
layout, _ := ms.Inspect(&myStruct) // no order argument

fmt.Println(layout.Format(binarystruct.DefaultLayoutFormat))
```

### JSON Layout Export
To export structural schema metadata to other languages (for codegen or external clients), export the layout to JSON:

```go
js, _ := layout.ToJSON()
// js contains JSON string with "type_name", "total_size", and "fields"
```

---

## 4. Accurate Error Diagnosis (Failure Byte-Offset)

When debugging failures (premature EOFs, array sizing mismatches, etc.), inspect the returned error's properties. All unmarshal/read failures are wrapped in a custom `DecodeError` that exposes:
* `Offset`: The exact byte offset where decoding failed.
* `Field`: The struct field name that was being decoded when the failure occurred.
* `Err`: The underlying error.

Always check for `DecodeError` to diagnose data stream mismatches:

```go
_, err := binarystruct.Unmarshal(data, &pkt) // pkt declares its order via the `_` sentinel
if err != nil {
	var decodeErr *binarystruct.DecodeError
	if errors.As(err, &decodeErr) {
		// Log the precise byte offset and corrupt field path
		log.Printf("corrupted packet at offset %d, field %s: %v", 
			decodeErr.Offset, decodeErr.Field, decodeErr.Err)
	}
}
```

---

## 5. Declarative Validation
`binarystruct` performs runtime validation checks during deserialization (Unmarshalling) when `range` or `match` options are present in the struct tags.

* **Error Types**: If a validation constraint is violated, the unmarshalling function returns a `DecodeError` wrapping `binarystruct.ErrValidationError`.
* **Zero Overhead for Unused Fields**: Fields without validation options incur no runtime validation overhead.
* **Precompiled Regex**: Regex patterns (`match=pattern`) are compiled once when the struct metadata is cached, avoiding expensive recompilation in the hot loop.

### Example struct with validation:
```go
type UserRegistration struct {
	Age uint8  `binary:"uint8,range=18..120"`
	Code string `binary:"string(6),match=^[A-Z]{2}\\d{4}$"` // e.g., US1234
}
```

---

## 6. Static Code Generation & JSON Export
To achieve peak performance in production, compile struct layouts into static Go code using the standalone `binarystruct-codegen` tool located in the `/binarystruct-codegen` nested module.

* **Workflow**:
  1. Add a `//go:generate` comment directive referencing the `binarystruct-codegen` CLI tool.
  2. Install the tool locally: `go install github.com/mixcode/binarystruct/binarystruct-codegen@latest`.
  3. Compile the static methods by running: `go generate ./...`.
* **JSON Layout Export**: Export structural layout metadata to a JSON file (for external schemas or clients in other languages) using the `-json` flag:
  ```bash
  binarystruct-codegen -type Packet -json -output layout.json
  ```
* **Parsing Test Files**: By default, the parser ignores `*_test.go` files. Pass `-tests` to include structs defined in test files:
  ```bash
  binarystruct-codegen -type TestStruct -tests
  ```
* **Byte order / `-endian` flag**: a struct's own `_` sentinel declaration supplies (and overrides) the order baked into the generated no-arg `MarshalBinary()`/`UnmarshalBinary()`/`AppendBinary()`. `-endian big|little` is only the **fallback** for a struct that declares none. Generation **errors** if neither the struct nor the flag gives an order (the stdlib `encoding` interfaces carry none, so there is no default). Codegen does **not** support struct-level `endian=inverse` or order-via-embedding — use the runtime interpreter for those.
* **Generated methods**: for each type, `MarshalBinary`/`UnmarshalBinary` (stdlib `encoding.BinaryMarshaler`/`Unmarshaler`), `AppendBinary` (stdlib `encoding.BinaryAppender`, Go 1.24), and `WriteBinary`/`ReadBinary` (+ `…WithMarshaler` when the struct uses encodings/codecs).
* **Runtime Fast-Paths**: The main library automatically detects generated static methods via type assertion (interfaces `BinaryReader`, `BinaryWriter`, `MarshalerContextReader`, `MarshalerContextWriter`) and fast-paths directly to them during `Marshal` / `Unmarshal` calls.
* **`-unsafe-bulk` flag (optional, default off)**: for fixed-width scalar arrays/slices whose Go element width equals the wire width, emit a raw-memory bulk path (one `Write`/`ReadFull` over the element backing store via `unsafe`, plus one in-place `binarystruct.SwapBytes` when the order differs from the host) instead of the portable per-element loop. The output is **byte-identical** — it only trades portability (the generated file gains an `unsafe` import) for speed, and the swap is **SIMD-accelerated** when the consumer builds with `-tags experiment_simd` (`GOEXPERIMENT=simd`) on amd64. Without the flag, generated code is pure/portable as before. (The runtime *unsafe* interpreter path already uses this raw-memory bulk swap unconditionally; the flag brings the same to generated code. SIMD never affects little-endian-on-amd64 or any host-order slice — no swap happens.)
* **Codegen limitations — design your struct to stay inside these** (each fails generation with a clear message; the **runtime interpreter handles them all**, so fall back to it for that struct):
  - a custom `valueof` evaluator whose argument is a **nested struct** (other arg shapes are fine — see §7);
  - a **multidimensional array with a non-scalar leaf** (string/nested-struct/pointer), or mixed fixed-array/slice nesting (scalar-leaf multidim like `[2][3]int16` / `[Rows][Cols]uint16` **is** supported);
  - `bytelen()` of a **pointer-element struct array** or a **pointer scalar field**;
  - struct-level **`endian=inverse`** or byte-order/encoding **inheritance via embedding**.
  Also: a struct that uses `encoding=`/`codec=`/custom `valueof` **must** be driven via `WriteBinaryWithMarshaler`/`ReadBinaryWithMarshaler` (a registered Marshaler) — the no-arg `MarshalBinary`/`UnmarshalBinary` pass a nil Marshaler and error for those fields.

### Example:
```go
//go:generate binarystruct-codegen -type Packet -endian big
type Packet struct {
	Magic uint32 `binary:"uint32"`
	Data  []byte `binary:"[16]byte"`
}
```

---

## 7. Computed Field Values (`valueof`)

The `valueof` option auto-computes an integer field's serialized value from other fields at **encode time only**, removing manual length/count bookkeeping. Pair it with a decode-side size expression so the two directions stay in sync:

```go
type Record struct {
	NameLen uint16 `binary:"uint16,valueof=bytelen(Name)"` // encode: written as len(Name)
	Name    []byte `binary:"[NameLen]byte"`                 // decode: sized from NameLen
}
```

### Functions (single field-name argument each)
A `valueof` value is a full expression (operators, constants, field references; see Section 2.D) **extended** with two functions, available only inside `valueof`:
* **`bytelen(F)`**: total encoded byte length of field `F` (honors text encodings such as Shift-JIS, length prefixes, arrays, and nested structs — not just `len()`). Valid for any field.
* **`count(F)`**: element count (`len(F)`) of an array or slice field `F`. NOT valid for strings — use `bytelen` for a string's byte length.

Combine with `+ - * /`, parentheses, and field references: `valueof=bytelen(Payload)+2`, `valueof=count(Items)`, `valueof=bytelen(A)+bytelen(B)`.

### Recipe: variable-length records (the most common pattern)
A header field holding the length/count of variable data that follows it = a `valueof=` length field paired with a `[len]` size expression on its target. `valueof` fills the length on encode; the size expression consumes it on decode. Set only the data fields — never the length fields:

```go
type Record struct {
	Magic      uint32 `binary:"uint32"`                         // you set this
	NameLen    uint16 `binary:"uint16,valueof=bytelen(Name)"`   // auto = encoded length of Name
	PayloadLen uint32 `binary:"uint32,valueof=bytelen(Payload)"`
	ItemCount  uint16 `binary:"uint16,valueof=count(Items)"`    // auto = number of Items
	Name    []byte   `binary:"[NameLen]byte"`     // decode: sized from NameLen
	Payload []byte   `binary:"[PayloadLen]byte"`
	Items   []uint32 `binary:"[ItemCount]uint32"`
}
// Encode: populate Name/Payload/Items only; the length+count fields are computed.
// (Emit-only: rec.NameLen is still 0 in memory after Marshal — round-trip via Unmarshal to populate.)
```

**Scope of the built-ins:** `bytelen`/`count` derive only field lengths/counts. Other derived values — CRC checksums, compressed sizes, offsets — are computed by **custom evaluators** you register (next).

### Recipe: checksums / CRCs (custom valueof evaluators)
The other common derived field is a checksum over preceding bytes, which `bytelen` cannot express. Register a named evaluator on the Marshaler and reference it from `valueof=NAME(field, …)`. **You must use a configured Marshaler** (`ms.Marshal`/`ms.Unmarshal`), not the package-level functions, exactly like custom codecs:

```go
ms := binarystruct.NewMarshaler()
ms.AddValueOf("CRC32", func(c binarystruct.ValueOfContext) (uint64, error) {
	h := crc32.NewIEEE()
	for _, a := range c.Args { h.Write(a.Bytes) } // hash the ENCODED bytes, not the Go values
	return uint64(h.Sum32()), nil
})

type Chunk struct {
	_      struct{} `binary:"endian=big"`
	Length uint32   `binary:"uint32,valueof=bytelen(Data)"`
	Type   string   `binary:"string(4)"`
	Data   []byte   `binary:"[Length]byte"`
	CRC    uint32   `binary:"uint32,valueof=CRC32(Type, Data)"` // computed on encode; validated on decode
}
blob, _ := ms.Marshal(&Chunk{Type: "IHDR", Data: payload})
```
* **Hash `Args[i].Bytes`, not `Args[i].Value`** — `Bytes` is what actually hits the stream (byte order / text encoding / width applied); the Go value can differ. The context also gives `Target` (field name) and `Struct` (pointer to the struct).
* **Validated on decode** (unlike encode-only `bytelen`): the same evaluator re-runs over the decoded fields and the result is compared to the value read; a mismatch is a `DecodeError` wrapping `ErrValidationError`. It's a post-decode pass, so a checksum may reference fields declared after it.
* **Must be the whole expression** — `valueof=CRC32(Type, Data)`; cannot be mixed with arithmetic in this version. An unregistered name fails loud.

### Recipe: a full chunked container (header + count-prefixed records + per-record CRC)
The library's sweet spot (PNG/TLV/packet-log shapes) combines four features in one type — struct-declared order (Rule E), a `const` magic (Section 8), `valueof` count/length, and a custom CRC. Set **only** the real data fields; every magic / count / length / CRC is written or validated for you:

```go
type Record struct {
	NameLen uint8  `binary:"uint8,valueof=bytelen(Name)"`
	Name    []byte `binary:"[NameLen]byte"`
	DataLen uint32 `binary:"uint32,valueof=bytelen(Payload)"`
	Payload []byte `binary:"[DataLen]byte"`
	CRC     uint32 `binary:"uint32,valueof=CRC32(Name, Payload)"` // per-record; validated on decode
}
type Container struct {
	_       struct{}  `binary:"endian=big"`              // order declared once; propagates into Record
	Magic   uint32    `binary:"uint32,const=0x504B544C"` // "PKTL": written on encode, checked on decode
	Version uint16    `binary:"uint16"`                  // a real field — you set this
	Count   uint16    `binary:"uint16,valueof=count(Records)"`
	Records []*Record `binary:"[Count]"`                 // slice-of-struct: BARE [Count], no element type
}

ms := binarystruct.NewMarshaler()                        // custom CRC ⇒ a configured Marshaler, not pkg funcs
ms.AddValueOf("CRC32", func(c binarystruct.ValueOfContext) (uint64, error) {
	h := crc32.NewIEEE()
	for _, a := range c.Args { h.Write(a.Bytes) }
	return uint64(h.Sum32()), nil
})
blob, _ := ms.Marshal(&Container{Version: 1, Records: recs}) // set only Version + Records (+ each Name/Payload)
var out Container
_, _ = ms.Unmarshal(blob, &out)                              // Magic + every CRC validated; lengths/Count consumed
```
* A **slice of structs** whose element count is a field uses the **bare `[Count]`** tag (no element type) — `[]*Record \`binary:"[Count]"\``.
* Because the custom CRC needs the registered evaluator, drive **both** directions through the same `ms` (the no-arg `binarystruct.Marshal`/the generated `MarshalBinary` would fail loud on the unknown name).

### Rules
* **Encode-only (built-ins).** On decode the field is read normally; size the target with a decode-side `[len]` expression. (Custom evaluators additionally validate on decode — above.)
* **Emit-only (no write-back), by design.** The computed value is written to the stream but your Go struct field is left unchanged — this keeps encoding a pure, side-effect-free read (safe for concurrent marshalling). **To obtain the computed values in Go, do a `Marshal`/`Unmarshal` (or `Write`/`Read`) round trip.** A write-back mode will not be added.
* **Integer/bitmap fields only**; other field types are a compile-time error. `bytelen`/`count` are valid only inside `valueof`.
* **Round-trip test gotcha (Go nil-vs-empty):** a zero-length `[]byte{}` (or `[]T{}`) decodes back as `nil`, so `reflect.DeepEqual(in, out)` can fail on otherwise-correct data — the *bytes* round-trip fine. Compare byte fields with `bytes.Equal` (treats nil and empty as equal), or normalize before `DeepEqual`. This is standard Go behavior, not a binarystruct quirk.
* **Codegen support**: the static code generator resolves `count(F)` and `bytelen(F)` for nearly every field shape — fixed-width scalars and scalar arrays, byte slices/arrays, fixed `string(N)` and all length-prefixed/null-terminated string variants (including text-encoded, via an `ms`-guarded `EncodeText` measurement), nested structs, tag-counted arrays of structs, and pointer-to-struct. It also supports **custom valueof evaluators**: byte-region args (`[]byte`/`[N]byte`, raw `string`, constant-size `string(N)` without text encoding) and fixed-width integer scalars (`order.PutUintN`) are emitted inline; every other arg shape (text-encoded/prefixed strings, floats, multibyte-scalar arrays, padded byte slices, variable string buffers) is re-encoded with its own tag via `ms.MarshalAs`, byte-matching the runtime. Only a **nested-struct arg** is unsupported (fails generation → use the runtime). Generated code needs a non-nil Marshaler (call `WriteBinaryWithMarshaler`, not the no-arg `MarshalBinary`); decode-time validation is **on by default** (generated decode recomputes and verifies the value, matching the runtime interpreter), and the `-no-validate` flag strips all decode validation — this custom check plus the built-in `const`/`range`/`match` checks. It rejects (generation-time error → use the runtime interpreter for that struct) `bytelen` of a **pointer-element struct array** or a **pointer scalar field**.

---

## 8. Fixed / Magic Values (`const`)

The `const` option pins a field to a fixed value: it is **emitted on encode** (the Go field's value is ignored) and **validated on decode** (a mismatch returns a `DecodeError` wrapping `ErrValidationError`). It is the right tool for format signatures, version bytes, and reserved fields.

```go
type ZIPLocalHeader struct {
	Signature uint32  `binary:"uint32,const=0x04034b50,endian=little"` // integer magic
	Version   uint16  `binary:"uint16,const=20,endian=little"`
}

type PNGHeader struct {
	Magic [8]byte `binary:"[8]byte,const=0x89504e470d0a1a0a"` // byte-sequence magic
}
```

### Two target shapes
* **Integer / bitmap** (`const=0x04034b50`): the value is a constant integer **expression** (decimal, hex `0x`, octal `0o`, binary `0b`, `+ - * /`, parens). Written as an integer, so its on-wire bytes follow the byte order. Limited to values that fit a signed 64-bit int (`< 2^63`); for larger or multi-byte magics use the byte-sequence form.
* **Byte sequence** `[N]byte` / `[]byte` / `string(N)` (`const=0x89504e470d0a1a0a`): a **hex blob** — the bytes in natural order (each pair of hex digits is one byte; `_` separators allowed). Written verbatim, so it is **endian-independent**. The field must have a fixed size equal to the constant's byte length.

### Endianness tip (important for integer magics)
An **integer** `const` is serialized through the active byte order, so the same `const=0x04034b50` emits `50 4b 03 04` under little-endian but `04 03 4b 50` under big-endian. Pin it with an explicit `endian=little|big` on the field so the signature's bytes are deterministic regardless of the marshaller's order. A **byte-sequence** `const` is written in natural order and is unaffected by byte order — no `endian=` needed (in fact `PK\x03\x04` is simply `const=0x504b0304`, which is clearer than the byte-swapped integer `0x04034b50`).

### Rules
* **Emit-only on encode** (like `valueof`): the Go field is not modified; set it or leave it zero, the const is written either way. On decode the field is populated from the stream and then checked.
* **Targets**: integer/bitmap or a raw byte sequence only; other types are a compile-time error. Cannot be combined with `valueof`. The byte form cannot be combined with `encoding=` (raw bytes only) and requires a fixed size (`[N]byte` or `string(N)`).
* **Codegen**: both shapes are supported by the static code generator.

---

## 9. Implementing the stdlib `encoding` interfaces (and `Append`)

`binarystruct.Append(buf, v)` encodes `v` and appends it to `buf`, returning the extended slice — the analog of `encoding/binary.Append`.

To make a tagged type usable by code that speaks the standard `encoding` interfaces (`gob`, your own framing, etc.), give it `MarshalBinary` / `UnmarshalBinary` / `AppendBinary` (Go 1.24) that delegate to binarystruct. **Codegen emits these for you** (`binarystruct-codegen` — `-endian` optional when the struct declares its order); to hand-write them, mind this trap:

> **Trap — infinite recursion.** binarystruct's `Marshal`/`Write` **honor `encoding.BinaryMarshaler`**. If your type's `MarshalBinary` calls `binarystruct.Marshal(self)`, that re-enters `MarshalBinary` forever (stack overflow). Break the cycle by marshalling a **method-less twin type** (the same idiom `encoding/json` uses):

```go
type Pixel struct {
	_ struct{} `binary:"endian=big"` // declares the order; the twin inherits it
	X uint16   `binary:"uint16"`
	Y uint16   `binary:"uint16"`
}

type pixelLayout Pixel // same layout & tags, NONE of Pixel's methods → no recursion

func (p *Pixel) MarshalBinary() ([]byte, error) {
	return binarystruct.Marshal((*pixelLayout)(p)) // order-free: the struct declares it
}
func (p *Pixel) AppendBinary(b []byte) ([]byte, error) {
	return binarystruct.Append(b, (*pixelLayout)(p))
}
func (p *Pixel) UnmarshalBinary(data []byte) error {
	_, err := binarystruct.Unmarshal(data, (*pixelLayout)(p))
	return err
}
```

Because the order is declared on the struct (the twin inherits it), no order is passed. If the type does *not* declare one, use `binarystruct.NewMarshalerOrder(order)` instead. (Codegen-generated methods write fields directly via `WriteBinary`, so they don't need the twin-type trick.)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.