codec

package module
v0.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 10 Imported by: 29 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-codec — Payload Encoding (CBOR / JSON / Raw)

CI Go Reference

Encoding/decoding for event-sourced payloads. Provides the Codec interface used by stores, snapshots, and event construction.

go get github.com/larsartmann/go-codec

Architecture

go-codec is the serialization contract at the center of an event-sourcing/CQRS stack. The Codec interface is consumed by storage, event construction, signing, and encryption modules:

flowchart LR
    subgraph go-codec
        C[Codec<br/>CBOR / JSON / Raw]
        BE[BufferEncoder]
        O[ObservableCodec]
        AD[AutoDetect / AutoDetectDebug]
        T[TranscodeToJSON]
        E[WrapEncode / UnwrapDecode]
        S[Size / SizeResult]
    end

    C -->|used by| ST[storage/pebble]
    C -->|payloads| EV[event]
    C -->|signs| SI[signing]
    C -->|encrypts| EN[encryption]
    C -->|read models| KV[kv]
    SI -->|requires| D[DeterministicCodec]
    C -.->|wraps| O
    C -.->|detects| AD
  • Codec / BufferEncoder — payload serialization and the zero-allocation hot path.
  • ObservableCodec — metrics, hooks, and monitoring without changing the codec.
  • AutoDetectDebug — best-effort encoding inference for mixed-format streams.
  • TranscodeToJSON / WrapEncode / Size — format conversion, self-describing envelopes, and payload-size diagnostics.
  • Sibling modules in go-cqrs-lite consume the contract; the signing module can assert DeterministicCodec to reject non-deterministic codecs at compile time.

Text-only summary of the diagram above:

┌───────────────────── go-codec ─────────────────────┐
│  Codec (CBOR / JSON / Raw) + BufferEncoder         │
│  ObservableCodec · AutoDetect · TranscodeToJSON    │
│  WrapEncode / UnwrapDecode · Size                  │
└──────┬──────────┬──────────┬──────────┬───────────┘
       │          │          │          │
    storage     event     signing   encryption
    (pebble)   payloads   (requires  (wraps any
                        DeterministicCodec)  Codec)

Codecs

Codec Description
CBORCodec Recommended. Canonical CBOR (RFC 7049) — deterministic, signing-safe
JSONCodec Standard encoding/json — universal interop, human-readable
CBORCompactCodec Stricter CBOR (RFC 8949 Core Deterministic) + unknown-field rejection
RawCodec Passthrough for pre-encoded []byte payloads

Interface

type Codec interface {
    Encoding() Encoding
    Encode(v any) ([]byte, error)
    Decode(data []byte, v any) error
}

// Optional zero-allocation interface:
type BufferEncoder interface {
    EncodeToBuffer(v any, buf *bytes.Buffer) error
}

Usage

codec := codec.CBORCodec{}
data, _ := codec.Encode(MyPayload{Name: "Alice"})
var decoded MyPayload
_ = codec.Decode(data, &decoded)

CBOR produces deterministic output (sorted map keys, shortest floats), making it safe for content-addressed storage and cryptographic signing. The pebble event store uses CBOR internally for its on-disk envelope format.

JSON
codec := codec.JSONCodec{}
data, _ := codec.Encode(MyPayload{Name: "Alice"})
var decoded MyPayload
_ = codec.Decode(data, &decoded)
CBOR Compact (Strict)
codec := codec.CBORCompactCodec{}
data, _ := codec.Encode(MyPayload{Name: "Alice"})

CBORCompactCodec uses stricter settings than CBORCodec:

  • Encoding: Core Deterministic (RFC 8949) — bytewise-lexically sorted map keys
  • Decoding: Rejects unknown struct fields as schema drift detection

Not compatible with data written by CBORCodec. Use only for new event stores.

CBOR with Event Signing

CBOR's deterministic encoding makes it ideal for signed event payloads — the same data always produces the same bytes, so signatures are reproducible:

// Use CBOR for deterministic event payloads
c := codec.CBORCodec{}
data, _ := c.Encode(payload)

// Sign the canonical CBOR bytes (same input → same signature every time)
signer, _ := signing.NewHMAC(secret)
sig, _ := signer.Sign(data)

// Verify on the consumer side
if !signer.Verify(data, sig) {
    return errors.New("signature mismatch")
}
var decoded MyPayload
_ = c.Decode(data, &decoded)

For compile-time safety, the signing module should accept codec.DeterministicCodec instead of a plain codec.Codec. Only CBORCodec, CBORCompactCodec, and (in the opt-in v2 JSON build) JSONCodec satisfy this interface, turning accidental use of non-deterministic v1 JSON into a build error.

When to Use CBOR vs JSON

CBOR is the recommended default for internal serialization — it produces smaller payloads and faster encode/decode times than JSON (run BenchmarkTagTradeoffs_Encode/BenchmarkTagTradeoffs_Decode and BenchmarkRealisticPayload_Encode for measured numbers on your hardware). CBOR is also deterministic: the same input always produces the same bytes, making it safe for signing. JSON is fully supported and remains the right choice for external interop, debugging, and human-readable payloads. Both codecs work everywhere in the library; pick one per use case.

Scenario Recommended Codec Why
Default for new projects CBORCodec Smaller, faster, signing-safe
Event payloads in PebbleDB CBORCodec Deterministic encoding for signing
Cryptographic signing of payloads CBORCodec Canonical byte representation
High-throughput event streams CBORCodec Smaller encoded size, faster decode
Read models / projections CBORCodec Smaller, faster, deterministic
New event store with schema drift guard CBORCompactCodec Unknown-field rejection on decode
External system interop / HTTP APIs JSONCodec Universal support
Debugging / human-readable payloads JSONCodec Readable in logs, curl, DB queries
Pre-encoded payloads RawCodec Zero-copy passthrough

CBOR Struct Tags for Smaller Payloads

fxamacker/cbor reads json struct tags by default, so CBOR works with existing struct definitions. For additional payload size reduction, use CBOR-specific tags:

toarray — Positional Array Encoding (~30-40% smaller)

Encodes structs as positional CBOR arrays instead of keyed maps, eliminating field-name string overhead entirely:

type UserCreated struct {
    _     struct{} `cbor:",toarray"`
    Name  string
    Email string
    Time  int64
}

Without toarray: {"Name":"Alice","Email":"[email protected]","Time":1700000000} With toarray: ["Alice","[email protected]",1700000000]

Once a struct uses toarray, field order is part of the wire format and cannot be reordered without breaking existing data. Add new fields only at the end.

keyasint — Integer Field Keys
type OrderPlaced struct {
    _      struct{} `cbor:",keyasint"`
    UserID uint64   `cbor:"1,keyasint"`
    ItemID uint64   `cbor:"2,keyasint"`
    Qty    int      `cbor:"3,keyasint"`
}
omitzero — Skip Zero-Valued Fields
type UserUpdated struct {
    Name  string `cbor:"name"`
    Email string `cbor:"email,omitempty"`
    Bio   string `cbor:"bio,omitzero"`
}

Both tags work with CBORCodec and CBORCompactCodec. Once adopted, the integer key mapping is part of the wire format — changing key numbers breaks existing data.

Zero-Allocation Encoding (BufferEncoder)

Codecs that implement the BufferEncoder interface can write directly into a caller-provided bytes.Buffer, avoiding the allocation returned by Encode:

buf := &bytes.Buffer{}
if be, ok := codec.(codec.BufferEncoder); ok {
    _ = be.EncodeToBuffer(payload, buf)
}

Both JSONCodec, CBORCodec, and CBORCompactCodec implement BufferEncoder.

Pooled Encoding (EncodePooled)

For hot paths that encode and immediately process the bytes (e.g., writing to a store or sending over the wire), EncodePooled manages the GetBuffer / EncodeToBuffer / PutBuffer lifecycle for you:

err := codec.EncodePooled(codec.CBORCodec{}, event, func(data []byte) error {
    // data is valid only inside this callback — copy it if you need to keep it.
    _, err := store.Write(data)
    return err
})

Compared to Encode, this eliminates the per-call []byte allocation. If the caller needs to retain the encoded bytes, use Encode instead (or append a copy inside the callback).

Streaming CBOR

For encoding/decoding large event batches without materializing the full byte slice in memory, use the streaming encoder/decoder:

// Encode a batch to a stream
f, _ := os.Create("events.cbor")
enc := codec.NewCBOREncoder(f)
for _, evt := range events {
    _ = enc.Encode(evt)
}

// Decode a batch from a stream
f, _ := os.Open("events.cbor")
dec := codec.NewCBORDecoder(f)
for {
    var evt MyEvent
    if err := dec.Decode(&evt); err == io.EOF { break }
}

The streaming encoder uses the same canonical encoding mode as CBORCodec.

Streaming JSON (NDJSON)

For JSON-based streams, NewJSONEncoder and NewJSONDecoder write and read newline-delimited JSON (NDJSON / JSON Lines). Each Encode call writes one JSON value followed by a newline, so readers can consume values incrementally without waiting for the whole stream:

// Encode a batch as NDJSON
var buf bytes.Buffer
enc := codec.NewJSONEncoder(&buf)
for _, evt := range events {
    _ = enc.Encode(evt)
}

// Decode values one at a time
dec := codec.NewJSONDecoder(&buf)
for {
    var evt MyEvent
    if err := dec.Decode(&evt); err != nil {
        break // io.EOF or end of stream
    }
}

The NDJSON format is convenient for logs, SSE, and HTTP line-streaming. The v2 JSON build uses json.MarshalWrite per value rather than a streaming encoder with separator tokens, keeping the output byte-identical to NDJSON.

CBOR Diagnostic Notation

Debug corrupt events or inspect raw CBOR payloads in human-readable form:

cborData, _ := codec.CBORCodec{}.Encode(event)
diag, _ := codec.Diagnose(cborData)
log.Printf("CBOR event: %s", diag)

Size Comparison (Size / SizeResult)

Use Size to compare the JSON and CBOR byte sizes of a value before committing to a format change. It returns a SizeResult with JSON and CBOR fields:

s := codec.Size(UserCreated{Name: "Alice", Email: "[email protected]"})
fmt.Printf("json=%d cbor=%d savings=%.0f%%\n",
    s.JSON, s.CBOR,
    float64(s.JSON-s.CBOR)/float64(s.JSON)*100)

If a codec cannot encode the value, that field is reported as -1. This is useful for payload-size budgets and for justifying a switch from JSON to CBOR on size-critical event types.

Telemetry (ObservableCodec)

Wrap any codec with ObserveCodec to record per-operation metrics — call counts, byte totals, error counts, and last errors — without touching the underlying codec. The wrapper is goroutine-safe and preserves the optional BufferEncoder fast path when the wrapped codec implements it.

obs := codec.ObserveCodec(codec.CBORCodec{},
    codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, bytes int, err error) {
        // Push-style telemetry: emit to Prometheus, OpenTelemetry, or logs.
    }),
)

data, _ := obs.Encode(payload)

m := obs.Metrics().Snapshot() // m.EncodeCalls, m.EncodeBytes, m.EncodeErrors, ...
  • WithMetrics(shared) — share one CodecMetrics sink across multiple codecs.
  • Snapshot() / Reset() — point-in-time copy vs. clear counters.
  • Panic policy: hook panics propagate (not recovered); metrics are recorded before the hook runs, so counters stay consistent.

See ExampleMetricsHook for a dependency-free counter implementation. In production, replace the map with Prometheus, OpenTelemetry, or structured log emission inside the hook.

Explainable Format Detection (AutoDetectDebug)

AutoDetect returns just the encoding; AutoDetectDebug also explains why:

result := codec.AutoDetectDebug(payload)
log.Printf("detected %s: %s", result.Encoding, result.Detail)

switch result.Reason { // branch on Reason — it is the stable contract
case codec.DetectionReasonCBORMajorType, codec.DetectionReasonCBORTrialDecode:
    // handle CBOR
case codec.DetectionReasonJSONStructure, codec.DetectionReasonJSONTrialDecode:
    // handle JSON
}

Reason is stable and machine-readable. Detail is human-readable prose for logs and triage — its wording may change between releases, so never parse it.

Shared CBOR Modes

Modules that need CBOR encoding identical to CBORCodec (e.g., custom storage backends) should use the exported modes instead of creating their own:

// Same canonical EncMode/DecMode used by CBORCodec internally
data, _ := codec.CBOREncMode().Marshal(payload)
_ = codec.CBORDecMode().Unmarshal(data, &payload)

Time Handling

CBOR codecs use TimeUnixDynamic — float64 epoch with sub-second precision (9 bytes). This preserves nanosecond values in time.Time payload fields (within ~165ns float drift).

Convention: All time.Time in event payloads MUST be .UTC() before encoding. Epoch values carry no timezone; decoded times reconstruct in time.Local, not the original location. Normalizing to UTC at encode time eliminates this ambiguity.

Wall-clock times (recurring schedules, business hours) must NOT use time.Time — store wall time components + IANA timezone name instead.

CBOR → JSON Transcoding (TranscodeToJSON)

Schema-free bridge for consumers that store events in CBOR but must serve JSON to browsers or REST clients (e.g. SSE delivery). Decodes the CBOR data model into a generic Go value and re-encodes as JSON, without needing the original struct type:

// payload is the stamped event payload; enc comes from evt.Encoding()
jsonBytes, err := codec.TranscodeToJSON(payload, enc)
  • EncodingJSON / EncodingRaw: returned unchanged (zero-cost passthrough).
  • EncodingCBOR: decoded generically and re-encoded as JSON.

Because it is schema-free, CBOR maps become JSON objects and CBOR arrays — including structs encoded with the cbor:",toarray" tag — stay arrays (field names cannot be reconstructed). For schema-aware JSON output, use event.DecodePayloadAuto[T] with the concrete payload type.

The transport/http package (from the sibling CQRS stack) provides CBORToJSONTransform, a ready-made adapter that wraps TranscodeToJSON for http.WithPayloadTransform — including graceful fallback to the raw payload on decode failure, so SSE clients always receive data.

Error Handling

Every error returned by this package carries a stable machine-readable code and a behavioral family (github.com/larsartmann/go-error-family):

Family Meaning Examples
Rejection Caller input fault unknown encoding, unencodable value
Corruption Undecodable stored / wire bytes malformed COSE structure, failing CBOR part
Infrastructure System-level plumbing that should not fail envelope marshal, buffer write
Orchestration Internal dependency-semantics bug CBOR mode-init panics

Errors render as [family:code] message: cause. Do not match on the string — match sentinels with errors.Is (ErrUnknownEncoding, ErrInvalidCOSESign1, ErrEncodeRawType, …) and extract code, family, and structured context via errors.AsType:

_, err := codec.ForEncoding(enc)
if e, ok := errors.AsType[*errorfamily.Error](err); ok {
    log.Printf("code=%s family=%v encoding=%s",
        e.Code(), e.ErrorFamily(), e.ErrorContext()["encoding"])
}

The full code table lives in docs/error-codes.md (registry, tripwired in CI), the design rationale in docs/adr/0001-error-taxonomy.md; the contract is locked by errors_contract_test.go. See doc.go (# Errors) for the contract and errors.go for the sentinel list.

Dual JSON Support (v1 and v2)

go-codec supports both encoding/json (v1, the default) and encoding/json/v2 (opt-in). The library uses the go-branded-id dual-build pattern: build-tagged compat files select the JSON implementation at compile time.

Default (v1): go build ./... — uses encoding/json, works on Go 1.27.2+ (see go.mod).

Opt-in (v2): GOEXPERIMENT=jsonv2 go build ./... — uses encoding/json/v2 (Go 1.25+ with the experiment flag, or Go 1.27+ natively).

Both modes are fully tested. Choose v2 if you need json.Deterministic, MarshalWrite, or other v2-specific features; otherwise v1 is the zero-config default.

This codec is part of an event-sourcing/CQRS stack. The sibling modules live in go-cqrs-lite:

  • event — DecodePayload[T] accepts a Codec to decode payloads
  • signing — CBOR's deterministic encoding makes signatures reproducible
  • encryption — encryption.NewCodec wraps a codec with encryption
  • storage/pebble — Uses CBOR internally for its on-disk envelope format
  • kv — WithTypedCodec lets read models use CBOR

Documentation

Overview

Package codec provides payload encoding and decoding for event sourcing.

The Codec interface abstracts serialization so that stores, snapshots, and event construction can work with any encoding format. Four implementations are provided:

  • CBORCodec: recommended default — canonical CBOR (deterministic, signing-safe)
  • JSONCodec: standard encoding/json — universal interop, human-readable
  • CBORCompactCodec: stricter CBOR with unknown-field rejection (schema drift guard)
  • RawCodec: passthrough for pre-encoded []byte payloads

CBORCodec and CBORCompactCodec are NOT interchangeable: they sort map keys differently (RFC 7049 length-first vs RFC 8949 bytewise-lexical) and the compact codec rejects unknown fields, so data written by one does not round-trip through the other. Choose one codec per store and keep it documented.

Choosing a Codec

Both JSON and CBOR are fully supported across the library. CBOR is recommended for internal serialization: smaller payloads (see BenchmarkTagTradeoffs for measured size reductions across payload shapes), faster to encode and decode, and deterministic (same input always produces the same output bytes — safe for cryptographic signing). JSON is the right choice for external interop, HTTP APIs, debugging, and any case where human-readability matters.

Payloads that will be signed or content-addressed require byte-deterministic encoding. The DeterministicCodec interface makes that a compile-time guarantee: CBORCodec and CBORCompactCodec always satisfy it, JSONCodec satisfies it only in the GOEXPERIMENT=jsonv2 build, and RawCodec never does. Signing modules should accept DeterministicCodec rather than Codec so that a non-deterministic codec choice fails to build instead of silently producing signatures that break on re-encoding.

Usage

codec := codec.JSONCodec{}
data, err := codec.Encode(MyPayload{Name: "Alice"})
var decoded MyPayload
err = codec.Decode(data, &decoded)

Integration

The Codec is used by event.New (auto-marshal payloads), event.DecodePayload[T] (typed decode), and snapshot stores (serialize stream state).

The encryption module provides a composable codec wrapper (encryption.NewCodec) that wraps any Codec with transparent encrypt-on-encode / decrypt-on-decode. It reports its own encoding ("encrypted") and is used with event.WithCodec to create events with encrypted payloads.

Cross-Codec Transcoding

TranscodeToJSON converts a payload from its stamped encoding into JSON bytes — the schema-free bridge for consumers that store events in CBOR but must serve JSON to browsers or REST clients. Non-CBOR payloads pass through unchanged; CBOR is decoded into a generic Go value and re-encoded as JSON.

out, err := codec.TranscodeToJSON(payload, evt.Encoding())

It is schema-free: CBOR maps become JSON objects, but structs encoded with the cbor:",toarray" tag become JSON arrays (field names are lost). For schema-aware JSON, decode with the concrete type first, then json.Marshal. The transport/http package provides CBORToJSONTransform, a ready-made adapter that wraps TranscodeToJSON for use with WithPayloadTransform.

TranscodeToJSON is a one-way operation: CBOR → JSON. There is intentionally no TranscodeToCBOR because the reverse direction cannot reconstruct CBOR type information (map key order, toarray positions, keyasint integers) from JSON without the original Go type. To produce CBOR, decode into the concrete type and encode with CBORCodec directly.

CBOR Compact Encoding (toarray)

For maximum payload size reduction (~30-40%), add the cbor:",toarray" struct tag to event payload types. This encodes structs as positional CBOR arrays instead of keyed maps, eliminating field-name string overhead entirely.

type UserCreated struct {
    _     struct{} `cbor:",toarray"`
    Name  string
    Email string
    Time  int64
}

Without toarray (map encoding): {"Name":"Alice","Email":"[email protected]","Time":1700000000} With toarray (array encoding): ["Alice","[email protected]",1700000000]

The toarray tag works with both CBORCodec and CBORCompactCodec. It is a per-type decision — mix array-encoded and map-encoded types freely. Once a struct uses toarray, field ORDER is part of the wire format and cannot be reordered without breaking existing data. Add new fields only at the end.

For additional compactness, use CBORCompactCodec (CoreDetEncOptions + ExtraReturnErrors for schema drift detection). See CBORCompactCodec docs.

Zero-Allocation Encoding

Codecs that implement the BufferEncoder interface can write directly into a caller-provided bytes.Buffer, avoiding the allocation returned by Encode. This is useful in hot paths where buffer reuse eliminates GC pressure.

buf := &bytes.Buffer{}
if be, ok := codec.(codec.BufferEncoder); ok {
    _ = be.EncodeToBuffer(payload, buf)
}

For even simpler pool-backed encoding, use EncodePooled, which manages a sync.Pool-backed buffer automatically via a callback:

err := codec.EncodePooled(cborCodec, event, func(data []byte) error {
    _, werr := store.Write(data)
    return werr
})

Streaming

For large event batches, streaming encoders/decoders avoid materializing the full byte slice in memory. Both CBOR and JSON are supported:

enc := codec.NewCBOREncoder(w)  // or codec.NewJSONEncoder(w)
_ = enc.Encode(event1)
_ = enc.Encode(event2)

dec := codec.NewCBORDecoder(r)  // or codec.NewJSONDecoder(r)
for {
    var evt Event
    if err := dec.Decode(&evt); err != nil { break }
    events = append(events, evt)
}

JSON streaming uses newline-delimited JSON (NDJSON / JSON Lines): each Encode call writes one JSON value followed by a newline, and Decode reads one value at a time, skipping whitespace between values.

Observability

ObserveCodec wraps any Codec with opt-in telemetry: per-operation call counts, byte totals, error counts, and last errors (CodecMetrics), plus a push-style MetricsHook for Prometheus/OpenTelemetry-style exporters. The wrapper is goroutine-safe and preserves the BufferEncoder fast path when present.

obs := codec.ObserveCodec(codec.CBORCodec{},
    codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, n int, err error) {
        // emit to your metrics backend
    }),
)

Errors

Every error returned by this package carries a stable machine-readable code and a behavioral family (github.com/larsartmann/go-error-family): Rejection for caller input faults, Corruption for undecodable stored or wire bytes, Infrastructure for system-level failures, and Orchestration for internal invariant violations. Sentinel identities (ErrUnknownEncoding, ErrEncodeRawType, ErrInvalidCOSESign1, …) match via errors.Is even when wrapped, and factual details (the offending encoding, the failing COSE part) live in the error's structured context:

_, err := codec.ForEncoding(enc)
if e, ok := errors.AsType[*errorfamily.Error](err); ok {
    log.Printf("code=%s family=%v encoding=%s",
        e.Code(), e.ErrorFamily(), e.ErrorContext()["encoding"])
}

The full code table lives in docs/error-codes.md (registry, tripwired in CI by scripts/check-error-codes.sh); the design rationale, including the WrapOnce rule and the classified-vs-passthrough split, is in docs/adr/0001-error-taxonomy.md.

Format Detection

AutoDetect infers the encoding (json/cbor/raw) of unknown payload bytes from the leading byte, with trial-decode fallback for ambiguous starts. It is a best-effort heuristic for diagnostics and tooling, NOT a security boundary. AutoDetectDebug additionally returns a stable DetectionReason to branch on and a human-readable Detail string for logs (unstable wording — never parse).

Performance

fxamacker/cbor caches type metadata in a process-wide sync.Map keyed by reflect.Type. The first encode/decode of each type pays a one-time reflection cost (~100µs); subsequent operations reuse the cached metadata (~300ns for a 7-field struct). Code generation is NOT needed for typical use cases — the cache handles it. Use EncodePooled or BufferEncoder to eliminate allocation overhead on hot paths.

The toarray and keyasint struct tags reduce payload size by eliminating field-name strings. Measured tradeoffs across payload shapes:

Payload      map (bytes)   toarray (bytes)   keyasint (bytes)
small (3)    56            43 (-23%)          46 (-18%)
medium (7)   218           156 (-28%)         168 (-23%)
large (12)   270           159 (-41%)         171 (-37%)

toarray produces the smallest payloads but encodes field order as positional (reordering fields breaks stored data). keyasint is slightly larger but preserves field identity via stable integer keys (safer for schema evolution). Run BenchmarkTagTradeoffs_Encode / BenchmarkTagTradeoffs_Decode for details.

CBOR Compact Struct Tags

fxamacker/cbor supports two struct tags for further payload optimization:

keyasint — encode struct fields as integer keys instead of string keys. This eliminates field-name strings entirely, ideal for high-frequency events with many fields.

type OrderPlaced struct {
    _      struct{} `cbor:",keyasint"`
    UserID uint64   `cbor:"1,keyasint"`
    ItemID uint64   `cbor:"2,keyasint"`
    Qty    int      `cbor:"3,keyasint"`
}

omitzero — omit fields that are zero-valued. Reduces payload size for events where many fields are optional.

type UserUpdated struct {
    Name  string `cbor:"name"`
    Email string `cbor:"email,omitempty"`
    Bio   string `cbor:"bio,omitzero"`
}

Both tags work with CBORCodec and CBORCompactCodec. Once adopted, the integer key mapping is part of the wire format — changing key numbers breaks existing data.

Index

Examples

Constants

View Source
const (
	COSEHeaderAlg         int64 = 1
	COSEHeaderCrit        int64 = 2
	COSEHeaderContentType int64 = 3
	COSEHeaderKid         int64 = 4
	COSEHeaderIV          int64 = 5
	COSEHeaderPartialIV   int64 = 6
)

COSE header parameter labels from the IANA "COSE Header Parameters" registry. See https://www.iana.org/assignments/cose/cose.xhtml

View Source
const (
	COSEAlgHMACSHA256_64    int64 = 4
	COSEAlgHMACSHA256       int64 = 5
	COSEAlgAES256GCM        int64 = 3
	COSEAlgChaCha20Poly1305 int64 = 24
	COSEAlgEdDSA            int64 = -8
	COSEAlgEd25519          int64 = -19
)

COSE algorithm identifiers from the IANA "COSE Algorithms" registry. These are the algorithms used by the signing and encryption modules.

Variables

View Source
var (
	ErrEncodeRawType error = errorfamily.NewRejection(
		"codec.raw_encode_type",
		"raw codec: expected []byte",
	)
	ErrDecodeRawType error = errorfamily.NewRejection(
		"codec.raw_decode_type",
		"raw codec: expected *[]byte target",
	)
	ErrInvalidCOSESign1 error = errorfamily.NewRejection(
		"codec.invalid_cose_sign1",
		"COSE_Sign1 structure has an invalid number of elements",
	)
	ErrInvalidCOSEEncrypt0 error = errorfamily.NewRejection(
		"codec.invalid_cose_encrypt0",
		"COSE_Encrypt0 structure has an invalid number of elements",
	)
	ErrCOSEAlgorithmOverflow error = errorfamily.NewRejection(
		"codec.cose_algorithm_overflow",
		"COSE algorithm value overflows int64",
	)
	ErrCOSEInvalidAlgorithm error = errorfamily.NewRejection(
		"codec.cose_invalid_algorithm",
		"COSE algorithm value is not an integer",
	)
	ErrNormalizeDepthExceeded error = errorfamily.NewRejection(
		"codec.normalize_depth_exceeded",
		"codec: normalizeForJSON recursion depth exceeded",
	)
)

Stable sentinel identities for the codec package. Declared as the `error` interface so errors.Is call sites match the sentinel guard; in-package wraps use errorfamily.Wrapf with the SAME code, so wrapped errors still match via code+family identity.

View Source
var ErrUnknownEncoding error = errorfamily.NewRejection(
	"codec.unknown_encoding",
	"codec: unknown encoding (no built-in codec)",
)

ErrUnknownEncoding is returned by ForEncoding when no built-in codec matches the requested encoding. Declared as the `error` interface so errors.Is call sites match the sentinel guard.

Functions

func AssignBase64JSON

func AssignBase64JSON(data []byte, module, noun string, target *[]byte) error

AssignBase64JSON unmarshals data and assigns the decoded bytes to *target. Convenience for types whose underlying type is []byte (encryption.Ciphertext, signing.Signature, etc.) — collapses the standard UnmarshalJSON body to one call so each []byte wrapper type does not repeat the decode+assign boilerplate.

func CBORDecMode

func CBORDecMode() cbor.DecMode

CBORDecMode returns the CBOR decoding mode with duplicate map key enforcement. External packages (e.g. storage/pebble) should use this instead of creating their own identical DecMode.

func CBOREncMode

func CBOREncMode() cbor.EncMode

CBOREncMode returns the canonical CBOR encoding mode (RFC 7049 sorted map keys). Used by storage/pebble and other modules that need deterministic CBOR encoding identical to what CBORCodec produces.

Example

ExampleCBOREncMode demonstrates using the exported canonical encoding mode directly. Storage backends should use this instead of creating their own CBOR mode, ensuring all modules share one deterministic encoding.

package main

import (
	"fmt"
	"log"

	"github.com/larsartmann/go-codec"
)

func main() {
	type Snapshot struct {
		State string
		N     int
	}

	snap := Snapshot{State: "active", N: 42}

	// Same canonical EncMode used by CBORCodec internally
	data, err := codec.CBOREncMode().Marshal(snap)
	if err != nil {
		log.Fatal(err)
	}

	var decoded Snapshot

	_ = codec.CBORDecMode().Unmarshal(data, &decoded)

	fmt.Printf("%s/%d (%d bytes)\n", decoded.State, decoded.N, len(data))

}
Output:
active/42 (18 bytes)

func COSEAlgHeader

func COSEAlgHeader(alg int64) ([]byte, error)

COSEAlgHeader returns the CBOR-encoded protected header for a COSE message that carries only the algorithm identifier (alg). This is the common case for COSE_Encrypt0 and COSE_Sign1 messages where the protected header contains no additional parameters.

The returned error is already wrapped as an Infrastructure error so callers (encryption, signing) don't need per-module error wrapping.

func COSEEncrypt0Diagnostic

func COSEEncrypt0Diagnostic(data []byte) string

COSEEncrypt0Diagnostic returns a human-readable diagnostic notation of a COSE_Encrypt0 message for debugging.

func COSESign1Diagnostic

func COSESign1Diagnostic(data []byte) string

COSESign1Diagnostic returns a human-readable diagnostic notation of a COSE_Sign1 message for debugging. It panics only if CBOR diagnosis itself fails, which cannot happen for valid CBOR data.

func DecodeBase64String

func DecodeBase64String(encoded string) ([]byte, error)

DecodeBase64String decodes a base64-encoded string, trying URL-safe encoding first, then falling back to standard base64 for backward compatibility with legacy consumers.

func DecodeEnvelopeOrLegacy added in v0.2.0

func DecodeEnvelopeOrLegacy[T any](data []byte, configured Codec) (T, error)

DecodeEnvelopeOrLegacy decodes data that may be envelope-wrapped or raw (pre-envelope) into T, keeping the permanent-readability guarantee of UnwrapDecode while honoring the caller's configured codec:

  • Envelope-wrapped data decodes via its stamped codec (first attempt).
  • Raw data decodes via the configured codec first.
  • If that fails and the codec is one of the two standard codecs, exactly one cross-retry with the other (JSON↔CBOR) rescues legacy rows written by a differently-configured store.
  • Custom codecs get the configured-codec attempt only — their data only decodes with themselves.

Truly undecodable data returns the primary decode error unwrapped, so callers can classify it (e.g. as Corruption) with their own context.

func Diagnose

func Diagnose(data []byte) (string, error)

Diagnose converts CBOR bytes to extended diagnostic notation (EDN) — a human-readable representation of CBOR data. Useful for debugging corrupt events or inspecting raw CBOR payloads without decoding into a Go struct.

cborData, _ := codec.CBORCodec{}.Encode(event)
diag, _ := codec.Diagnose(cborData)
log.Printf("CBOR event: %s", diag)
Example

ExampleDiagnose converts CBOR bytes to human-readable diagnostic notation. Useful for debugging corrupt events or inspecting raw CBOR payloads.

c := codec.CBORCodec{}

type User struct {
	Name  string
	Email string
}

data, _ := c.Encode(User{Name: testName, Email: testEmail})

diag, _ := codec.Diagnose(data)

// Diagnostic notation is a map-like representation
fmt.Println(strings.Contains(diag, testName))
Output:
true

func EncStructure0

func EncStructure0(bodyProtected, externalAAD []byte) ([]byte, error)

EncStructure0 builds the Enc_structure used for COSE_Encrypt0 encryption and decryption as defined in RFC 9052 Section 5.3.

func EncodePooled added in v0.2.0

func EncodePooled(enc BufferEncoder, v any, fn func([]byte) error) error

EncodePooled encodes v using a pooled *bytes.Buffer and passes the encoded bytes to fn. The buffer is returned to the pool after fn returns, so fn must not retain references to the byte slice after returning — if it needs to keep the bytes, it must copy them.

This eliminates the per-call []byte allocation of Codec.Encode in hot paths where the caller processes the encoded bytes immediately (e.g., writing to a store, sending over the wire). For callers that need to keep the bytes, use Codec.Encode instead.

cbor := codec.CBORCodec{}
err := codec.EncodePooled(cbor, event, func(data []byte) error {
    _, werr := store.Write(data)
    return werr
})
Example

ExampleEncodePooled demonstrates zero-allocation encoding using a pooled buffer. The callback receives the encoded bytes and must copy them if it needs to retain them after the callback returns — the buffer is returned to the pool immediately.

type Event struct {
	Type string
	Data string
}

c := codec.CBORCodec{}
evt := Event{Type: testEventCreated, Data: "hello"}

var encoded []byte

err := codec.EncodePooled(c, evt, func(data []byte) error {
	encoded = append([]byte(nil), data...) // copy: data is invalid after callback

	return nil
})
if err != nil {
	fmt.Println("error:", err)

	return
}

var decoded Event

_ = c.Decode(encoded, &decoded)
fmt.Println(decoded.Type, decoded.Data)
Output:
created hello

func GetBuffer added in v0.2.0

func GetBuffer() *bytes.Buffer

GetBuffer returns a zeroed *bytes.Buffer from the pool. The caller owns the buffer until PutBuffer is called.

func MarshalBase64JSON

func MarshalBase64JSON(raw []byte) ([]byte, error)

MarshalBase64JSON encodes raw bytes as a URL-safe base64 JSON string. Used by types that wrap []byte and need deterministic JSON marshalling (encryption.Ciphertext, signing.Signature, event.EventID, etc.).

func MarshalBase64JSONWithModule

func MarshalBase64JSONWithModule(raw []byte, module, noun string) ([]byte, error)

MarshalBase64JSONWithModule encodes raw bytes as base64 JSON and wraps any error with the given module and noun (e.g. "encryption", "ciphertext" → "encryption.marshal_ciphertext"). Symmetric with AssignBase64JSON — collapses the standard MarshalJSON body to one call.

func MarshalCOSEEncrypt0

func MarshalCOSEEncrypt0(msg COSEEncrypt0) ([]byte, error)

MarshalCOSEEncrypt0 encodes a COSE_Encrypt0 structure to CBOR bytes.

func MarshalCOSEProtectedHeader

func MarshalCOSEProtectedHeader(headers map[int64]any) ([]byte, error)

MarshalCOSEProtectedHeader serializes a COSE protected header map to the CBOR bytes that are wrapped in a byte string inside the COSE message. The encoding uses the canonical CBOR mode shared with CBORCodec.

func MarshalCOSESign1

func MarshalCOSESign1(msg COSESign1) ([]byte, error)

MarshalCOSESign1 encodes a COSE_Sign1 structure to CBOR bytes.

func NewCBORDecoder

func NewCBORDecoder(r io.Reader) *cbor.Decoder

NewCBORDecoder creates a streaming CBOR decoder that reads from r. Use for decoding large event batches from a stream without loading all bytes into memory at once. The decoder uses the same decoding mode as CBORCodec.

func NewCBOREncoder

func NewCBOREncoder(w io.Writer) *cbor.Encoder

NewCBOREncoder creates a streaming CBOR encoder that writes to w. Use for encoding large event batches without materializing the full byte slice in memory. The encoder uses the same canonical encoding mode as CBORCodec.

Example

ExampleNewCBOREncoder demonstrates streaming CBOR encoding for large event batches without materializing the full byte slice in memory.

type Event struct {
	Type string
	Data string
}

var buf bytes.Buffer

enc := codec.NewCBOREncoder(&buf)
_ = enc.Encode(Event{Type: testEventType, Data: testUserName})
_ = enc.Encode(Event{Type: testEventType, Data: "bob"})

// Decode the stream
dec := codec.NewCBORDecoder(&buf)

var events []Event

for {
	var evt Event
	if err := dec.Decode(&evt); err != nil {
		break
	}

	events = append(events, evt)
}

fmt.Printf("%d events decoded from stream\n", len(events))
Output:
2 events decoded from stream

func NormalizeCOSEAlgorithm

func NormalizeCOSEAlgorithm(v any) (int64, error)

NormalizeCOSEAlgorithm converts a CBOR-decoded algorithm value to int64. CBOR decodes integers as the narrowest Go type that fits, which means small positive values arrive as uint64. This helper normalizes all integer variants to int64 so callers can compare against the COSEAlg* constants. Returns ErrCOSEAlgorithmOverflow for values that exceed int64, and ErrCOSEInvalidAlgorithm for non-integer types.

func PrepareCOSESetup

func PrepareCOSESetup[Cfg any, O ~func(*Cfg)](cfg *Cfg, opts []O, alg int64) ([]byte, error)

PrepareCOSESetup applies COSE options to cfg and returns the protected header for the given algorithm. Shared by encryption.EncryptCOSE0 and signing.SignCOSE1 to eliminate the duplicated apply-opts + alg-extraction + header-build boilerplate that art-dupl flagged across those modules.

The caller passes a pointer to its module-local config (e.g. coseEncryptConfig or coseSignConfig); the options are applied in place. The O type parameter has a ~func(*Cfg) constraint so module-local defined option types (COSEEncryptOption, COSESignOption) satisfy it directly.

func PutBuffer added in v0.2.0

func PutBuffer(b *bytes.Buffer)

PutBuffer returns a buffer to the pool for reuse. Do not use the buffer after calling PutBuffer. Buffers larger than 1 MiB are discarded to avoid memory bloat from oversized payloads.

func SigStructure

func SigStructure(bodyProtected, externalAAD, payload []byte) ([]byte, error)

SigStructure builds the Sig_structure used for COSE_Sign1 signing and verification as defined in RFC 9052 Section 4.4.

func TranscodeToJSON

func TranscodeToJSON(payload []byte, enc Encoding) ([]byte, error)

TranscodeToJSON converts a payload from its stamped encoding into JSON bytes. It is the generic, schema-free bridge for consumers that must serve JSON to clients (browsers, REST APIs) while storing events in a compact encoding (CBOR). This deletes the per-consumer CBOR→JSON transcode logic that every compact-codec deployment otherwise duplicates.

Behaviour by encoding:

  • EncodingJSON: payload returned unchanged (already JSON).
  • EncodingRaw: payload returned unchanged (caller asserts it is valid JSON).
  • EncodingCBOR: payload is decoded into a generic Go value (map/slice/scalar) and re-encoded as JSON, preserving the CBOR data model.

TranscodeToJSON is schema-free: it does NOT know the original Go struct type. CBOR maps become JSON objects; CBOR arrays — including structs encoded with the cbor:",toarray" tag — become JSON arrays. For schema-aware decoding (field names, typed values), use event.DecodePayloadAuto[T] with the concrete type.

Map key order is NOT deterministic: the generic decode produces a map[string]any, and json.Marshal iterates Go maps in non-deterministic order. This is correct for browser SSE (JSON objects are unordered) but unsuitable for byte-deterministic use cases (content hashing, cache keys, byte-for-byte comparisons). Callers needing stable key order must use event.DecodePayloadAuto[T] with a concrete struct type, which produces field-order (declaration-order) JSON output.

An error is returned only when CBOR decoding or JSON encoding fails. Callers that want graceful degradation (fall back to the raw payload on failure) should ignore the error and use the original bytes — see transport/http.CBORToJSONTransform for a ready-made [WithPayloadTransform] adapter that does exactly this.

Example

ExampleTranscodeToJSON converts a stored CBOR payload into JSON bytes for serving to browsers or REST clients without knowing the original Go type.

c := codec.CBORCodec{}

type User struct {
	Name string
}

cborBytes, err := c.Encode(User{Name: testName})
if err != nil {
	fmt.Println("error:", err)

	return
}

jsonBytes, err := codec.TranscodeToJSON(cborBytes, codec.EncodingCBOR)
if err != nil {
	fmt.Println("error:", err)

	return
}

fmt.Println(string(jsonBytes))
Output:
{"Name":"Alice"}

func UnmarshalBase64JSON

func UnmarshalBase64JSON(data []byte, module, noun string) ([]byte, error)

UnmarshalBase64JSON unmarshals a JSON string field and decodes it from URL-safe (or standard) base64. The module and noun parameters produce meaningful error locations: e.g. module="signing", noun="signature" yields "signing.unmarshal_signature" and "signing.decode_signature".

func UnmarshalCOSEProtectedHeader

func UnmarshalCOSEProtectedHeader(data []byte) (map[int64]any, error)

UnmarshalCOSEProtectedHeader deserializes a COSE protected header map from its CBOR-encoded form.

func WrapCOSEMarshal

func WrapCOSEMarshal(data []byte, err error, module, noun string) ([]byte, error)

WrapCOSEMarshal wraps a COSE marshal result with infrastructure error handling. Used by encryption (COSE_Encrypt0) and signing (COSE_Sign1) to centralise the if-err-wrap pattern with a consistent error code format ("<module>.cose_marshal") and message ("marshal <noun>").

func WrapEncode

func WrapEncode(v any, c Codec) ([]byte, error)

WrapEncode serializes v with codec c and wraps the result in a JSON envelope. The envelope itself is always JSON-encoded so it can be read without knowing the inner codec. Callers should use UnwrapDecode on the read path to extract the codec and inner data, or fall back to raw decode for old data.

Types

type AutoDetectResult added in v0.2.0

type AutoDetectResult struct {
	Encoding Encoding
	Reason   DetectionReason
	Detail   string
}

AutoDetectResult carries the encoding chosen by AutoDetect plus the reason.

Reason is the STABLE, machine-readable contract: branch on it in code. Detail is human-readable, intended for logs and triage output only. Its exact wording and format are NOT part of the API contract and may change in any release — never parse it.

func AutoDetectDebug added in v0.2.0

func AutoDetectDebug(data []byte) AutoDetectResult

AutoDetectDebug is the verbose form of AutoDetect: it returns not only the inferred encoding but also the reason and a human-readable detail string. Use it when triaging mixed-encoding streams or when logging the decision path. Branch on Reason (stable); treat Detail as diagnostic prose (unstable).

Example

ExampleAutoDetectDebug demonstrates explainable format detection: beyond the inferred encoding, it returns a stable DetectionReason to branch on and a human-readable Detail for logs. Detail is NOT a stable contract — never parse it.

package main

import (
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	for _, data := range [][]byte{
		[]byte(`{"name":"Alice"}`),
		{0xa1, 0x64, 'n', 'a', 'm', 'e', 0x65, 'A', 'l', 'i', 'c', 'e'}, // CBOR map
		{0x1f}, // unrecognized
	} {
		result := codec.AutoDetectDebug(data)

		switch result.Reason {
		case codec.DetectionReasonJSONStructure, codec.DetectionReasonJSONTrialDecode:
			fmt.Println("json")
		case codec.DetectionReasonCBORMajorType, codec.DetectionReasonCBORTrialDecode:
			fmt.Println("cbor")
		case codec.DetectionReasonEmpty,
			codec.DetectionReasonOversized,
			codec.DetectionReasonUnknown:
			fmt.Printf("other (%s): %s\n", result.Reason, result.Detail)
		}
	}

}
Output:
json
cbor
other (unknown): first byte 0x1f does not match any known format

type BufferEncoder

type BufferEncoder interface {
	EncodeToBuffer(v any, buf *bytes.Buffer) error
}

BufferEncoder is an optional interface that Codecs can implement for zero-allocation encoding. Instead of allocating a new []byte on every Encode call, EncodeToBuffer writes directly into a caller-provided buffer. Callers can reuse the buffer across calls to eliminate GC pressure in hot paths (batch event publishing, bulk snapshot saving).

Example

ExampleBufferEncoder demonstrates zero-allocation encoding by writing directly into a caller-provided buffer. Useful in hot paths where buffer reuse eliminates GC pressure.

package main

import (
	"bytes"
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	type Metric struct {
		Name  string
		Value float64
	}

	c := codec.CBORCodec{}
	buf := &bytes.Buffer{}

	// Reuse the same buffer across multiple encode calls
	for _, m := range []Metric{
		{Name: "cpu", Value: 0.42},
		{Name: "mem", Value: 0.87},
	} {
		buf.Reset()

		if be, ok := any(c).(codec.BufferEncoder); ok {
			_ = be.EncodeToBuffer(m, buf)
		}

		fmt.Printf("%d bytes ", buf.Len())
	}

	fmt.Println("done")

}
Output:
25 bytes 25 bytes done

type CBORCodec

type CBORCodec struct{}

CBORCodec implements Codec using fxamacker/cbor with canonical encoding (RFC 7049: sorted map keys, shortest floats). Canonical mode is deterministic, making CBORCodec safe for content-addressed storage and cryptographic signing.

Encoding mode: CanonicalEncOptions (RFC 7049 §3.9 "Canonical CBOR"). Evaluated CoreDetEncOptions (RFC 7049bis "Core Deterministic") — not adopted because it uses SortBytewiseLexical vs SortLengthFirst, changing all output bytes and breaking existing stored CBOR data + signatures.

Example
c := codec.CBORCodec{}

type User struct {
	Name string
}

data, err := c.Encode(User{Name: testName})
if err != nil {
	fmt.Println("error:", err)

	return
}

var user User

err = c.Decode(data, &user)
if err != nil {
	fmt.Println("error:", err)

	return
}

fmt.Println(user.Name)
Output:
Alice
Example (Keyasint)

ExampleCBORCodec_keyasint demonstrates the keyasint struct tag that encodes field names as compact integer keys instead of strings. This is the COSE/CWT (CBOR Web Token) pattern used by JWT-like claims: each field gets a small integer key, shrinking payloads without losing the self-describing map structure (unlike toarray, field order doesn't matter).

package main

import (
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	c := codec.CBORCodec{}

	// Integer keys follow the CWT claim registry (RFC 8392).
	type Claims struct {
		Iss string `cbor:"1,keyasint"`
		Sub string `cbor:"2,keyasint"`
		Aud string `cbor:"3,keyasint"`
		Exp int64  `cbor:"4,keyasint"`
	}

	// String-keyed equivalent for size comparison
	type ClaimsString struct {
		Iss string
		Sub string
		Aud string
		Exp int64
	}

	claims := Claims{Iss: "s6BhdRkqt3", Sub: "24400320", Aud: "s6BhdRkqt3", Exp: 1735689600}

	data, _ := c.Encode(claims)
	stringData, _ := c.Encode(ClaimsString(claims))

	fmt.Printf("keyasint: %d bytes, string keys: %d bytes\n", len(data), len(stringData))

	var decoded Claims

	_ = c.Decode(data, &decoded)
	fmt.Println(decoded.Iss)

}
Output:
keyasint: 41 bytes, string keys: 53 bytes
s6BhdRkqt3
Example (Time)

ExampleCBORCodec_time shows time.Time round-tripping through CBOR. Times are encoded as epoch values (TimeUnixDynamic), so the instant survives but the original time zone does not: normalize with .UTC() before encoding and re-normalize after decoding.

package main

import (
	"fmt"
	"time"

	"github.com/larsartmann/go-codec"
)

func main() {
	c := codec.CBORCodec{}

	created := time.Date(2026, 8, 14, 12, 0, 0, 0, time.UTC)

	data, err := c.Encode(created)
	if err != nil {
		fmt.Println("error:", err)

		return
	}

	var decoded time.Time

	if err := c.Decode(data, &decoded); err != nil {
		fmt.Println("error:", err)

		return
	}

	fmt.Println(decoded.UTC())

}
Output:
2026-08-14 12:00:00 +0000 UTC
Example (Toarray)

ExampleCBORCodec_toarray demonstrates the toarray struct tag that encodes structs as positional CBOR arrays instead of keyed maps, reducing payload size by 30-40% by eliminating field-name string overhead.

package main

import (
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	c := codec.CBORCodec{}

	// The _ field with `cbor:",toarray"` tag enables positional encoding.
	// Field ORDER becomes part of the wire format — add new fields only at end.
	type PaymentProcessed struct {
		_           struct{} `cbor:",toarray"`
		PaymentID   string
		AmountCents int64
		Currency    string
		OccurredAt  int64
	}

	payload := PaymentProcessed{
		PaymentID:   "pay_abc123",
		AmountCents: 4999,
		Currency:    "USD",
		OccurredAt:  1700000000,
	}

	mapCodec := codec.JSONCodec{}
	mapData, _ := mapCodec.Encode(payload)

	arrayData, _ := c.Encode(payload)

	fmt.Printf("JSON: %d bytes, CBOR+toarray: %d bytes (%.0f%% smaller)\n",
		len(mapData), len(arrayData),
		float64(len(mapData)-len(arrayData))/float64(len(mapData))*100)

	var decoded PaymentProcessed

	_ = c.Decode(arrayData, &decoded)
	fmt.Println(decoded.PaymentID, decoded.AmountCents)

}
Output:
JSON: 86 bytes, CBOR+toarray: 24 bytes (72% smaller)
pay_abc123 4999

func (CBORCodec) Decode

func (CBORCodec) Decode(data []byte, v any) error

Decode unmarshals CBOR bytes into a value.

func (CBORCodec) Encode

func (CBORCodec) Encode(v any) ([]byte, error)

Encode marshals a value to canonical CBOR bytes with deterministic map ordering.

func (CBORCodec) EncodeToBuffer

func (CBORCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error

EncodeToBuffer writes canonical CBOR encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.

func (CBORCodec) Encoding

func (CBORCodec) Encoding() Encoding

type CBORCompactCodec

type CBORCompactCodec struct{}

CBORCompactCodec is an opt-in Codec that uses stricter decoding than CBORCodec. It uses CoreDetEncOptions (RFC 8949 "Core Deterministic") for encoding and ExtraReturnErrors(UnknownField) for decoding — rejecting unknown fields on decode as a schema drift detection mechanism.

This codec is NOT compatible with data written by CBORCodec (which uses CanonicalEncOptions with length-first sort). Use it only for new event stores.

For even smaller payloads, consumers should add `cbor:",toarray"` struct tags to their event payload types. This encodes structs as positional CBOR arrays instead of maps, eliminating field-name string keys (~30-40% reduction). The toarray tag is separate from this codec — the codec enables the strict encoding/decoding modes, and the consumer opts into per-type compactness.

type MyEvent struct {
    _           struct{} `cbor:",toarray"`
    ID          string
    Payload     []byte
    OccurredAt  int64
}
Example

ExampleCBORCompactCodec demonstrates the strict CBOR codec that rejects unknown fields on decode — a schema drift detection mechanism.

c := codec.CBORCompactCodec{}

type UserCreated struct {
	Name  string
	Email string
}

data, _ := c.Encode(UserCreated{Name: testName, Email: testEmail})

var result UserCreated

_ = c.Decode(data, &result)

fmt.Println(result.Name, result.Email)
Output:
Alice [email protected]

func (CBORCompactCodec) Decode

func (CBORCompactCodec) Decode(data []byte, v any) error

Decode unmarshals compact CBOR bytes into a value. Returns an error if the data contains unknown fields (schema drift detection).

func (CBORCompactCodec) Encode

func (CBORCompactCodec) Encode(v any) ([]byte, error)

Encode marshals a value to compact CBOR bytes with deterministic ordering.

func (CBORCompactCodec) EncodeToBuffer

func (CBORCompactCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error

EncodeToBuffer writes compact CBOR encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.

func (CBORCompactCodec) Encoding

func (CBORCompactCodec) Encoding() Encoding

type COSEEncrypt0

type COSEEncrypt0 struct {
	// Protected contains the serialized protected header map (a CBOR-encoded map
	// wrapped in a byte string). It is authenticated as additional data (AAD).
	Protected []byte

	// Unprotected contains header parameters that are not cryptographically
	// protected, such as the initialization vector (IV).
	Unprotected map[int64]any

	// Ciphertext is the encrypted payload. It may be nil for detached content.
	Ciphertext []byte
}

COSEEncrypt0 represents a COSE_Encrypt0 structure as defined in RFC 9052. It is a single-recipient encrypted message with protected headers, unprotected headers, and ciphertext.

func UnmarshalCOSEEncrypt0

func UnmarshalCOSEEncrypt0(data []byte) (COSEEncrypt0, error)

UnmarshalCOSEEncrypt0 decodes a COSE_Encrypt0 structure from CBOR bytes.

type COSESign1

type COSESign1 struct {
	// Protected contains the serialized protected header map (a CBOR-encoded map
	// wrapped in a byte string). It is stored as raw bytes so that signature
	// verification can use the exact byte representation that was signed.
	Protected []byte

	// Unprotected contains header parameters that are not cryptographically
	// protected, such as the key identifier (kid).
	Unprotected map[int64]any

	// Payload is the signed payload. It may be nil for detached content.
	Payload []byte

	// Signature is the raw cryptographic signature value.
	Signature []byte
}

COSESign1 represents a COSE_Sign1 structure as defined in RFC 9052. It is a single-signer signed message with protected headers, unprotected headers, payload, and signature.

func UnmarshalCOSESign1

func UnmarshalCOSESign1(data []byte) (COSESign1, error)

UnmarshalCOSESign1 decodes a COSE_Sign1 structure from CBOR bytes.

type Codec

type Codec interface {
	Encoding() Encoding
	Encode(v any) ([]byte, error)
	Decode(data []byte, v any) error
}

Codec serializes and deserializes values with a declared encoding.

func ForEncoding

func ForEncoding(enc Encoding) (Codec, error)

ForEncoding returns the built-in Codec for the given Encoding. It resolves EncodingJSON → JSONCodec, EncodingCBOR → CBORCodec, and EncodingRaw → RawCodec.

For unknown encodings (including custom values like "encrypted"), it returns ErrUnknownEncoding. Callers that need custom encoding support should build their own dispatch table.

ForEncoding is the codec-level counterpart to AutoDetect: AutoDetect infers the encoding from raw bytes, ForEncoding resolves a known encoding stamp to its codec. Together they enable mixed-stream decoding — see [event.DecodePayloadAuto].

Example (Classified)

ExampleForEncoding_classified shows how to extract the stable code, behavioral family, and structured context from a codec error with errors.AsType. Every wrapping helper in this package returns classified errors — see the # Errors section of the package documentation and docs/error-codes.md.

package main

import (
	"errors"
	"fmt"

	"github.com/larsartmann/go-codec"
	errorfamily "github.com/larsartmann/go-error-family"
)

func main() {
	_, err := codec.ForEncoding("encrypted") // no built-in codec matches

	if e, ok := errors.AsType[*errorfamily.Error](err); ok {
		fmt.Println("code:", e.Code())
		fmt.Println("family:", e.ErrorFamily())
		fmt.Println("encoding:", e.ErrorContext()["encoding"])
	}

}
Output:
code: codec.unknown_encoding
family: rejection
encoding: encrypted

func UnwrapDecode

func UnwrapDecode(data []byte, fallback Codec) (Codec, []byte)

UnwrapDecode inspects data for an envelope wrapper. If found, it returns the stamped codec and inner data bytes. If not found (old unenveloped data), it returns the fallback codec and the original data unchanged.

This enables backward-compatible migration: old data decodes via the fallback, new data decodes via the stamped codec. Stores can gradually transition without a full clear-and-rebuild.

type CodecMetrics added in v0.2.0

type CodecMetrics struct {
	// contains filtered or unexported fields
}

CodecMetrics records per-instance codec operation counters and last results. It is safe for concurrent use by multiple goroutines.

func (*CodecMetrics) Reset added in v0.2.0

func (m *CodecMetrics) Reset()

Reset clears all recorded metrics.

func (*CodecMetrics) Snapshot added in v0.2.0

func (m *CodecMetrics) Snapshot() MetricsSnapshot

Snapshot returns a point-in-time copy of the metrics.

type DetectionReason added in v0.2.0

type DetectionReason string

DetectionReason explains why AutoDetect chose an encoding.

const (
	// DetectionReasonEmpty means the input was empty and defaulted to raw.
	DetectionReasonEmpty DetectionReason = "empty"
	// DetectionReasonCBORMajorType means the first byte identified a CBOR major type.
	DetectionReasonCBORMajorType DetectionReason = "cbor_major_type"
	// DetectionReasonJSONStructure means the first byte was an unambiguous JSON structural start.
	DetectionReasonJSONStructure DetectionReason = "json_structure"
	// DetectionReasonJSONTrialDecode means the first byte was ambiguous, but JSON trial decode succeeded.
	DetectionReasonJSONTrialDecode DetectionReason = "json_trial_decode"
	// DetectionReasonCBORTrialDecode means the first byte was ambiguous, JSON
	// trial decode failed, but CBOR trial decode succeeded.
	DetectionReasonCBORTrialDecode DetectionReason = "cbor_trial_decode"
	// DetectionReasonOversized means the payload exceeded maxAutoDetectSize and was treated as raw.
	DetectionReasonOversized DetectionReason = "oversized"
	// DetectionReasonUnknown means the payload did not match any known format.
	DetectionReasonUnknown DetectionReason = "unknown"
)

type DeterministicCodec added in v0.2.0

type DeterministicCodec interface {
	Codec
	// contains filtered or unexported methods
}

DeterministicCodec is a marker interface implemented by codecs whose Encode produces byte-identical output for equal inputs on every call. Codecs that satisfy this interface are safe for cryptographic signing: the signing module can assert this at compile time, turning silent signature corruption (e.g. using JSONCodec in v1 mode, whose map key order is non-deterministic) into a build error.

The unexported method prevents external packages from implementing the interface — only the built-in codecs in this package can be signing-safe.

CBORCodec and CBORCompactCodec always implement DeterministicCodec. JSONCodec implements it only in the v2 build (encoding/json/v2 with Deterministic mode); the v1 default does not because map key ordering is non-deterministic. RawCodec never implements it because it performs no encoding at all.

Example

ExampleDeterministicCodec shows how a signing helper can require a byte-deterministic codec at compile time. CBORCodec and CBORCompactCodec always satisfy the interface; JSONCodec satisfies it only in the GOEXPERIMENT=jsonv2 build; RawCodec never does.

sign := func(c codec.DeterministicCodec, v any) ([]byte, error) {
	// Signing safety is guaranteed by the type: only codecs whose Encode
	// is byte-deterministic can reach this body.
	return c.Encode(v)
}

type User struct {
	Name string
}

first, err := sign(codec.CBORCodec{}, User{Name: testName})
if err != nil {
	fmt.Println("error:", err)

	return
}

second, err := sign(codec.CBORCodec{}, User{Name: testName})
if err != nil {
	fmt.Println("error:", err)

	return
}

fmt.Println(bytes.Equal(first, second))

// The following would NOT compile in the default (v1) build, because
// encoding/json v1 map key order is non-deterministic:
//
//	_ = sign(codec.JSONCodec{}, User{Name: testName})
Output:
true

type Encoding

type Encoding string

Encoding identifies the serialization format used for a payload.

const (
	EncodingJSON Encoding = "json"
	EncodingCBOR Encoding = "cbor"
	EncodingRaw  Encoding = "raw"
)

func AutoDetect

func AutoDetect(data []byte) Encoding

AutoDetect inspects raw payload bytes and returns the most likely Encoding. It distinguishes JSON from CBOR by examining the structural first byte:

  • JSON objects/arrays/strings start with '{', '[', or '"' (ASCII).
  • CBOR maps (major type 5) start with 0xa0–0xbf; arrays (major type 4) with 0x80–0x9f. These ranges never overlap with valid JSON leading bytes.

For ambiguous leading bytes (e.g. bare numbers, booleans) the function falls back to a trial decode: JSON first, then CBOR.

Empty input returns EncodingRaw. Unknown data returns EncodingRaw.

AutoDetect is a best-effort heuristic for diagnostics and tooling — it is NOT a security boundary. Never use it to skip encoding validation; always pair detected data with the matching codec's Decode for authoritative parsing.

Example

ExampleAutoDetect infers the encoding of unknown payload bytes from the leading byte. It is a best-effort heuristic for diagnostics and tooling — always pair the result with the matched codec's Decode for real work.

package main

import (
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	for _, data := range [][]byte{
		[]byte(`{"name":"Alice"}`),                                      // JSON object
		{0xa1, 0x64, 'n', 'a', 'm', 'e', 0x65, 'A', 'l', 'i', 'c', 'e'}, // CBOR map
		{0x1f}, // unrecognized
	} {
		fmt.Println(codec.AutoDetect(data))
	}

}
Output:
json
cbor
raw

type JSONCodec

type JSONCodec struct{}

JSONCodec implements Codec using encoding/json.

Example
c := codec.JSONCodec{}

type User struct {
	Name string `json:"name"`
}

data, err := c.Encode(User{Name: testName})
if err != nil {
	fmt.Println("error:", err)

	return
}

var user User

err = c.Decode(data, &user)
if err != nil {
	fmt.Println("error:", err)

	return
}

fmt.Println(user.Name)
Output:
Alice

func (JSONCodec) Decode

func (JSONCodec) Decode(data []byte, v any) error

Decode unmarshals JSON bytes into a value.

func (JSONCodec) Encode

func (JSONCodec) Encode(v any) ([]byte, error)

Encode marshals a value to JSON bytes.

func (JSONCodec) EncodeToBuffer

func (JSONCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error

EncodeToBuffer writes JSON encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.

func (JSONCodec) Encoding

func (JSONCodec) Encoding() Encoding

type JSONDecoder added in v0.2.0

type JSONDecoder struct {
	// contains filtered or unexported fields
}

JSONDecoder reads JSON values from an io.Reader. Each call to JSONDecoder.Decode reads one JSON value from the stream, skipping whitespace and newlines between values.

In the v2 build (GOEXPERIMENT=jsonv2), this wraps jsontext.Decoder with json.UnmarshalDecode for stateful streaming. json.UnmarshalRead is NOT used because it creates a new internal buffer per call, losing over-read bytes between values.

func NewJSONDecoder added in v0.2.0

func NewJSONDecoder(r io.Reader) *JSONDecoder

NewJSONDecoder creates a streaming JSON decoder that reads from r. Each call to JSONDecoder.Decode reads the next JSON value from the stream, skipping whitespace and newlines between values. Use for decoding large event batches from a stream without loading all bytes into memory.

Parity with NewCBORDecoder for consumers that standardize on JSON.

func (*JSONDecoder) Decode added in v0.2.0

func (d *JSONDecoder) Decode(v any) error

Decode reads the next JSON value from the stream into v.

type JSONEncoder added in v0.2.0

type JSONEncoder struct {
	// contains filtered or unexported fields
}

JSONEncoder streams JSON values to an io.Writer. Each call to JSONEncoder.Encode writes one JSON value followed by a newline (NDJSON / JSON Lines convention), enabling a reader to consume values incrementally from the stream.

In the v2 build (GOEXPERIMENT=jsonv2), this uses json.MarshalWrite per value. jsontext.Encoder is intentionally NOT used because it inserts separator tokens between top-level values, corrupting NDJSON output.

func NewJSONEncoder added in v0.2.0

func NewJSONEncoder(w io.Writer) *JSONEncoder

NewJSONEncoder creates a streaming JSON encoder that writes to w. Each call to JSONEncoder.Encode writes one JSON value followed by a newline (NDJSON / JSON Lines convention), enabling incremental consumption on the reader side. Use for encoding large event batches without materializing the full byte slice in memory.

Parity with NewCBOREncoder for consumers that standardize on JSON.

Example

ExampleNewJSONEncoder demonstrates streaming JSON encoding for large event batches using newline-delimited JSON (NDJSON). Each Encode call writes one JSON value followed by a newline, enabling incremental consumption on the reader side.

type Event struct {
	Type string
	Data string
}

var buf bytes.Buffer

enc := codec.NewJSONEncoder(&buf)
_ = enc.Encode(Event{Type: testEventType, Data: testUserName})
_ = enc.Encode(Event{Type: testEventType, Data: "bob"})

// Decode the NDJSON stream
dec := codec.NewJSONDecoder(&buf)

var events []Event

for {
	var evt Event
	if err := dec.Decode(&evt); err != nil {
		break
	}

	events = append(events, evt)
}

fmt.Printf("%d events decoded from JSON stream\n", len(events))
Output:
2 events decoded from JSON stream

func (*JSONEncoder) Encode added in v0.2.0

func (e *JSONEncoder) Encode(v any) error

Encode writes the JSON encoding of v followed by a newline to the stream.

type MetricsHook added in v0.2.0

type MetricsHook func(op Operation, enc Encoding, bytesProcessed int, err error)

MetricsHook receives a notification after each observed operation. bytesProcessed is the length of the encoded payload for encodes or the input length for decodes. err is the result of the operation (nil on success).

Panic policy: hooks are caller-supplied callbacks and their panics PROPAGATE to the caller of Encode/Decode — they are not recovered. This is the idiomatic Go contract (a library must not swallow panics, which hides bugs). Metrics are always recorded BEFORE the hook runs, so a panicking hook leaves counters consistent. Keep hooks fast and panic-free: they execute inline on the codec's hot path.

Example

ExampleMetricsHook demonstrates a dependency-free push-style metrics hook. The callback updates simple counters; in production, this is where you would emit to Prometheus, OpenTelemetry, or structured logs.

type event struct {
	Type string
}

counters := map[codec.Operation]int64{}

obs := codec.ObserveCodec(codec.CBORCodec{},
	codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, bytes int, err error) {
		counters[op]++
	}),
)

data, _ := obs.Encode(event{Type: testEventCreated})

var decoded event

_ = obs.Decode(data, &decoded)

fmt.Printf("encodes=%d decodes=%d type=%s\n",
	counters[codec.OpEncode], counters[codec.OpDecode], decoded.Type)
Output:
encodes=1 decodes=1 type=created

type MetricsSnapshot added in v0.2.0

type MetricsSnapshot struct {
	EncodeCalls     int64
	EncodeBytes     int64
	EncodeErrors    int64
	LastEncodeError error
	DecodeCalls     int64
	DecodeBytes     int64
	DecodeErrors    int64
	LastDecodeError error
}

MetricsSnapshot is a point-in-time copy of CodecMetrics.

Example

ExampleMetricsSnapshot takes a point-in-time copy of ObservableCodec counters for operational dashboards. The snapshot is immutable — later codec operations do not change it.

type User struct {
	Name string
}

obs := codec.ObserveCodec(codec.CBORCodec{})

for range 2 {
	_, _ = obs.Encode(User{Name: testName})
}

snap := obs.Metrics().Snapshot()

fmt.Printf("encode calls: %d, encode errors: %d\n", snap.EncodeCalls, snap.EncodeErrors)
Output:
encode calls: 2, encode errors: 0

type ObservableCodec added in v0.2.0

type ObservableCodec struct {
	// contains filtered or unexported fields
}

ObservableCodec wraps a Codec and records metrics for every operation. It implements Codec and, when the wrapped codec implements BufferEncoder, BufferEncoder as well.

func ObserveCodec added in v0.2.0

func ObserveCodec(c Codec, opts ...ObserveOption) *ObservableCodec

ObserveCodec returns an observable wrapper around c.

Example

ExampleObserveCodec demonstrates wrapping a codec with telemetry. The ObservableCodec decorator records per-operation metrics and invokes a MetricsHook after every encode/decode — useful for Prometheus or OpenTelemetry-style push telemetry without polling.

obs := codec.ObserveCodec(codec.CBORCodec{},
	codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, bytes int, err error) {
		fmt.Printf("op=%d enc=%s err=%v\n", op, enc, err)
	}))

data, _ := obs.Encode(map[string]string{testFieldName: testName})

var decoded map[string]string

_ = obs.Decode(data, &decoded)

m := obs.Metrics().Snapshot()
fmt.Printf("encode calls: %d, decode calls: %d\n", m.EncodeCalls, m.DecodeCalls)
Output:
op=0 enc=cbor err=<nil>
op=1 enc=cbor err=<nil>
encode calls: 1, decode calls: 1

func (*ObservableCodec) Decode added in v0.2.0

func (obs *ObservableCodec) Decode(data []byte, v any) error

Decode unmarshals data and records metrics.

func (*ObservableCodec) Encode added in v0.2.0

func (obs *ObservableCodec) Encode(v any) ([]byte, error)

Encode marshals v and records metrics.

func (*ObservableCodec) EncodeToBuffer added in v0.2.0

func (obs *ObservableCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error

EncodeToBuffer writes v into buf using the wrapped codec if it implements BufferEncoder; otherwise it encodes and writes the bytes.

func (*ObservableCodec) Encoding added in v0.2.0

func (obs *ObservableCodec) Encoding() Encoding

Encoding returns the wrapped codec's encoding.

func (*ObservableCodec) Metrics added in v0.2.0

func (obs *ObservableCodec) Metrics() *CodecMetrics

Metrics returns the live metrics sink for this wrapper.

type ObserveOption added in v0.2.0

type ObserveOption func(*ObservableCodec)

ObserveOption configures an ObservableCodec.

func WithMetrics added in v0.2.0

func WithMetrics(metrics *CodecMetrics) ObserveOption

WithMetrics stores metrics in the supplied CodecMetrics instead of creating a private one. This lets multiple ObservableCodecs share a metrics sink or lets callers inspect metrics directly.

func WithMetricsHook added in v0.2.0

func WithMetricsHook(hook MetricsHook) ObserveOption

WithMetricsHook registers a hook that is called after every Encode/Decode.

type Operation added in v0.2.0

type Operation int

Operation identifies the kind of observed codec operation.

const (
	// OpEncode is an encoding operation.
	OpEncode Operation = iota

	// OpDecode is a decoding operation.
	OpDecode
)

type RawCodec

type RawCodec struct{}

RawCodec implements Codec as a passthrough for []byte. Encode accepts only []byte (or json.RawMessage). Decode copies data into a *[]byte target.

Example
package main

import (
	"fmt"

	"github.com/larsartmann/go-codec"
)

func main() {
	c := codec.RawCodec{}

	raw := []byte(`{"name":"Bob"}`)

	data, err := c.Encode(raw)
	if err != nil {
		fmt.Println("error:", err)

		return
	}

	var decoded []byte

	err = c.Decode(data, &decoded)
	if err != nil {
		fmt.Println("error:", err)

		return
	}

	fmt.Println(string(decoded))

}
Output:
{"name":"Bob"}

func (RawCodec) Decode

func (RawCodec) Decode(data []byte, v any) error

Decode copies data into target, which must be *[]byte.

func (RawCodec) Encode

func (RawCodec) Encode(v any) ([]byte, error)

Encode returns v as-is if it is []byte or json.RawMessage.

func (RawCodec) Encoding

func (RawCodec) Encoding() Encoding

type SizeResult added in v0.2.0

type SizeResult struct {
	JSON int `json:"json"`
	CBOR int `json:"cbor"`
}

SizeResult reports the serialized byte sizes of a value under each codec.

func Size

func Size(v any) SizeResult

Size encodes v with both JSON and CBOR and returns the byte sizes. This is useful for deciding whether switching a payload type from JSON to CBOR is worthwhile before committing to a format change.

If a codec fails to encode v, that size is reported as -1.

s := codec.Size(UserCreated{Name: "Alice", Email: "[email protected]"})
savings := float64(s.JSON-s.CBOR) / float64(s.JSON) * 100 // e.g. 19
Example

ExampleSize compares the serialized byte sizes of a value under JSON and CBOR, helping decide whether a format switch is worthwhile before committing.

type UserCreated struct {
	Name  string
	Email string
}

s := codec.Size(UserCreated{Name: testName, Email: testEmail})

if s.CBOR < s.JSON {
	fmt.Printf("CBOR saves %d bytes (%.0f%% smaller)\n",
		s.JSON-s.CBOR,
		float64(s.JSON-s.CBOR)/float64(s.JSON)*100)
} else {
	fmt.Println("CBOR is not smaller for this payload")
}
Output:
CBOR saves 8 bytes (18% smaller)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL