@serialpilot/cobs
v0.1.0
Published
Pure-function Consistent Overhead Byte Stuffing (COBS) encode/decode. Browser-clean — no node:* imports.
Maintainers
Readme
@serialpilot/cobs
Pure-function Consistent Overhead Byte Stuffing encode/decode. Zero deps, no node:* imports — runs unchanged in browsers and Web Serial.
COBS turns an arbitrary byte stream into a self-delimiting stream where 0x00 only ever appears as the frame terminator. Output is at most ⌈n/254⌉ + 1 bytes longer than the input, plus one delimiter byte.
Install
npm install @serialpilot/cobsUse
import { encode, decode } from '@serialpilot/cobs'
const data = new Uint8Array([0x11, 0x22, 0x00, 0x33])
const encoded = encode(data)
// → Uint8Array(6) [3, 0x11, 0x22, 2, 0x33, 0] (terminating 0x00 included)
const decoded = decode(encoded)
// → Uint8Array(4) [0x11, 0x22, 0x00, 0x33]encode always appends a single 0x00 delimiter. decode accepts a frame with or without the trailing 0x00.
Allocation-free hot-path variants
import { encodeInto, decodeInto, maxEncodedLength } from '@serialpilot/cobs'
const dst = new Uint8Array(maxEncodedLength(data.length))
const written = encodeInto(data, dst)
// dst.subarray(0, written) is the encoded frame.maxEncodedLength(n) = n + Math.ceil(n / 254) + 2. The +2 covers the leading code byte and the trailing delimiter.
Errors
decode throws CobsError for malformed input:
| code | meaning |
| --------------- | ------------------------------------------------------ |
| INVALID_FRAME | code byte is 0x00, or a 0x00 appears mid-run. |
| TRUNCATED | code byte points past the end of the buffer. |
Use @serialpilot/parser-cobs if you want a Transform stream that emits one decoded payload per 0x00 delimiter.
License
MIT.
