# `src/codec`

Wire-level CAN and CAN-FD encoding utilities for
`fuyun-2026/moonbit-canbus`.

This package converts the project's validated `@frame.Frame` values to and
from a deterministic bit representation. It includes DLC conversion, CRC-15,
CRC-17, and CRC-21 calculation, CAN bit stuffing, trailer validation, and
wire-size inspection. It is a protocol codec, not a hardware driver or a
socket interface.

## Install

```bash
moon add fuyun-2026/moonbit-canbus/src/codec@0.2.4
```

The codec depends on the sibling `src/frame` package. In a module checkout,
declare both packages in the package imports:

```text
import {
  "fuyun-2026/moonbit-canbus/src/codec"
  "fuyun-2026/moonbit-canbus/src/frame"
}
```

## Core round trip

`encode` returns the complete wire bit sequence. `decode` validates the
trailer, removes stuffed bits, checks the frame shape and verifies the
appropriate CRC. The byte helpers preserve the bit length in the first two
bytes, so they can carry a final partial byte without ambiguity.

```moonbit
let frame = @frame.Frame::data(
  id=@frame.Id::standard(0x123),
  bytes=[0x10, 0x20, 0x30],
)
let wire = @codec.encode_bytes(frame)
let restored = @codec.decode_bytes(wire)
assert(@codec.round_trip_equal(frame))
assert(restored.payload() == frame.payload())
```

## Useful APIs

- `encode` / `decode` — checked bit-level wire conversion.
- `encode_bytes` / `decode_bytes` — length-prefixed byte transport.
- `inspect` — report logical bits, stuffing, trailer, payload bytes, and wire
  length.
- `frame_statistics` / `stuffing_ratio` — measure bit density and stuffing
  overhead for a frame.
- `BitStatistics::summary` / `zero_density` — expose concise population and
  transition metrics for logs and diagnostics.
- `WireReport::payload_efficiency` / `has_stuffing` — quantify payload use and
  bit-stuffing overhead on the encoded wire.
- `BitCursor` — bounds-checked sequential reads for adapters and diagnostics.
- `BitStream` — mutable bit collection with slicing, prefix checks, and byte
  conversion.
- `crc15`, `crc17`, `crc21` — the CRC widths selected by classic CAN and CAN-FD
  payload size.

## Error handling

Operations that parse or encode frames raise `CodecError`. Callers should
handle `Truncated`, `MalformedFrame`, `MalformedStuffing`, `InvalidTrailer`,
`InvalidDlc`, `InvalidLength`, and `CrcMismatch` when accepting untrusted wire
data.

The package is deterministic and allocation-conscious at the API boundary,
but it does not open devices, schedule traffic, or provide a native CAN
controller backend. Use `src/sim` for a deterministic virtual bus and
`src/replay` for scheduled event playback.

## Verification

From the repository root:

```bash
moon check --target all
moon test src/codec
```
