Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff883d6f8e
|
||
|
|
63ebaa0232
|
||
|
|
f4665a46cb
|
||
|
|
92021a2608
|
||
|
|
adb0db7ee5
|
||
|
|
3d674989ab
|
No files matched your search
@@ -0,0 +1,49 @@
|
||||
# Changelog
|
||||
|
||||
## 0.3.0 — 2026-03-31
|
||||
|
||||
### Performance
|
||||
|
||||
- **Encode nonzero/mixed: ~2x faster** — uses const `copy_from_slice` (memcpy at
|
||||
runtime) via Rust 1.93's stabilization of const slice methods. Sub-slice scan
|
||||
pattern helps LLVM eliminate bounds checks.
|
||||
- **Encode zeros: ~50% faster** — fast path skips scan loop overhead for leading
|
||||
zero bytes.
|
||||
- **Decode zeros: ~4x faster** — batch consecutive `0x01` codes and fill zeros
|
||||
via `fill(0)` (memset) instead of per-byte iteration.
|
||||
- Encode now wins or ties corncobs on nonzero/mixed workloads.
|
||||
- Decode zeros now leads all competitors by 3x.
|
||||
|
||||
### Added
|
||||
|
||||
- `legacy-msrv` feature flag — enables compilation on Rust 1.83+ (e.g. Xtensa
|
||||
toolchain) by replacing const `copy_from_slice` with a manual byte loop.
|
||||
All other optimizations (sub-slice scan, zero fast path, decode batch fill)
|
||||
work without this feature on any supported Rust version.
|
||||
|
||||
### Changed
|
||||
|
||||
- **MSRV bumped from 1.83 to 1.93** — required for const `copy_from_slice`.
|
||||
Use the `legacy-msrv` feature for older toolchains.
|
||||
- Dev-dependencies updated: `cobs` 0.3 to 0.5, `criterion` 0.5 to 0.8,
|
||||
`rand` 0.8 to 0.10.
|
||||
|
||||
## 0.2.0 — 2026-03-30
|
||||
|
||||
### Added
|
||||
|
||||
- `const fn` encode — encode data at compile time with zero runtime cost.
|
||||
- Comprehensive documentation with 7 usage examples (basic, buffer sizing,
|
||||
framing, stream parsing, compile-time encoding, error handling).
|
||||
- Initial encode/decode throughput optimizations.
|
||||
|
||||
### Changed
|
||||
|
||||
- MSRV set to 1.83.
|
||||
|
||||
## 0.1.0 — 2026-03-29
|
||||
|
||||
- Initial release.
|
||||
- `no_std`, zero-alloc, `unsafe`-free COBS encoder and decoder.
|
||||
- 106 tests: canonical vectors, property-based (proptest), fuzz targets,
|
||||
cross-crate interop with `corncobs` and `cobs`.
|
||||
+6
-5
@@ -1,8 +1,8 @@
|
||||
[package]
|
||||
name = "ucobs"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.56"
|
||||
rust-version = "1.93"
|
||||
license = "MIT"
|
||||
description = "μCOBS — Consistent Overhead Byte Stuffing. no_std, zero-alloc, fastest, most-tested COBS implementation."
|
||||
authors = ["Stephen Waits <steve@waits.net>"]
|
||||
@@ -15,6 +15,7 @@ categories = ["encoding", "no-std::no-alloc", "embedded"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
legacy-msrv = []
|
||||
|
||||
[lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -23,11 +24,11 @@ unsafe_code = "forbid"
|
||||
all-features = true
|
||||
|
||||
[dev-dependencies]
|
||||
cobs = "0.3"
|
||||
cobs = "0.5"
|
||||
corncobs = "0.1"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
proptest = "1"
|
||||
rand = "0.8"
|
||||
rand = "0.10"
|
||||
|
||||
[[bench]]
|
||||
name = "bench"
|
||||
|
||||
@@ -26,94 +26,273 @@ Benchmarked against the two other `no_std` COBS crates using
|
||||
[Criterion](https://github.com/bheisler/criterion.rs) across three payload
|
||||
patterns: **all zeros** (worst case — every byte triggers a code emit),
|
||||
**no zeros**, and **mixed** (0x00–0xFF cycling). Throughput in MB/s, higher
|
||||
is better.
|
||||
is better. Legend: 🥇 winner, 🥉 last, 🤝 statistical tie (<5%).
|
||||
|
||||
### Encode
|
||||
|
||||
| Payload | Pattern | μCOBS | `cobs` 0.3 | `corncobs` 0.1 |
|
||||
| Payload | Pattern | μCOBS | `cobs` 0.5 | `corncobs` 0.1 |
|
||||
|---------|---------|------:|-----------:|---------------:|
|
||||
| 64 B | zeros | 595 | 748 | 180 |
|
||||
| 64 B | mixed | 1,853 | 1,011 | 1,734 |
|
||||
| 64 B | nonzero | 1,884 | 1,012 | 2,110 |
|
||||
| 256 B | zeros | 654 | 817 | 184 |
|
||||
| 256 B | mixed | 1,888 | 1,002 | 1,887 |
|
||||
| 256 B | nonzero | 1,964 | 1,004 | 1,968 |
|
||||
| 4096 B | zeros | 675 | 845 | 188 |
|
||||
| 4096 B | mixed | 1,734 | 1,016 | 1,746 |
|
||||
| 4096 B | nonzero | 1,775 | 1,020 | 2,245 |
|
||||
| 64 B | zeros | 1,485 | 🥇 1,572 | 🥉 274 |
|
||||
| 64 B | nonzero | 🤝 3,721 | 🥉 2,177 | 🤝 3,616 |
|
||||
| 64 B | mixed | 🥇 3,596 | 🥉 2,019 | 3,137 |
|
||||
| 256 B | zeros | 1,494 | 🥇 1,962 | 🥉 341 |
|
||||
| 256 B | nonzero | 🥇 4,267 | 🥉 2,218 | 3,951 |
|
||||
| 256 B | mixed | 🤝 3,891 | 🥉 2,114 | 🤝 3,867 |
|
||||
| 4096 B | zeros | 1,376 | 🥇 2,052 | 🥉 334 |
|
||||
| 4096 B | nonzero | 🤝 4,538 | 🥉 2,227 | 🤝 4,501 |
|
||||
| 4096 B | mixed | 🤝 3,993 | 🥉 1,549 | 🤝 3,888 |
|
||||
|
||||
### Decode
|
||||
|
||||
| Payload | Pattern | μCOBS | `cobs` 0.3 | `corncobs` 0.1 |
|
||||
| Payload | Pattern | μCOBS | `cobs` 0.5 | `corncobs` 0.1 |
|
||||
|---------|---------|------:|-----------:|---------------:|
|
||||
| 64 B | zeros | 595 | 440 | 732 |
|
||||
| 64 B | mixed | 7,041 | 504 | 7,991 |
|
||||
| 64 B | nonzero | 9,900 | 502 | 9,807 |
|
||||
| 256 B | zeros | 656 | 472 | 742 |
|
||||
| 256 B | mixed |17,024 | 645 | 16,207 |
|
||||
| 256 B | nonzero |18,456 | 647 | 19,549 |
|
||||
| 4096 B | zeros | 675 | 483 | 768 |
|
||||
| 4096 B | mixed |17,522 | 656 | 22,959 |
|
||||
| 4096 B | nonzero |37,987 | 623 | 40,005 |
|
||||
| 64 B | zeros | 🥇 2,896 | 🥉 924 | 1,520 |
|
||||
| 64 B | nonzero | 🤝 16,000 | 🥉 1,168 | 🤝 15,238 |
|
||||
| 64 B | mixed | 9,275 | 🥉 1,133 | 🥇 15,610 |
|
||||
| 256 B | zeros | 🥇 3,088 | 🥉 914 | 1,496 |
|
||||
| 256 B | nonzero | 40,000 | 🥉 1,179 | 🥇 42,667 |
|
||||
| 256 B | mixed | 28,444 | 🥉 1,140 | 🥇 37,647 |
|
||||
| 4096 B | zeros | 🥇 4,620 | 🥉 942 | 1,549 |
|
||||
| 4096 B | nonzero | 🥇 68,040 | 🥉 1,203 | 58,851 |
|
||||
| 4096 B | mixed | 40,236 | 🥉 1,154 | 🥇 49,769 |
|
||||
|
||||
### Code size
|
||||
|
||||
Measured from `.text` section of release-optimized symbols (`encode` + `decode`
|
||||
combined):
|
||||
|
||||
| Crate | Code size |
|
||||
|----------------|----------:|
|
||||
| μCOBS | 541 B |
|
||||
| `cobs` 0.3 | 537 B |
|
||||
| `corncobs` 0.1 | 637 B |
|
||||
| Crate | `encode` | `decode` | Total |
|
||||
|----------------|--------:|---------:|------:|
|
||||
| μCOBS | 434 B | 435 B | 869 B |
|
||||
| `cobs` 0.5 | 245 B | 292 B | 537 B |
|
||||
| `corncobs` 0.1 | 375 B | 262 B | 637 B |
|
||||
|
||||
All three crates are tiny. The difference is negligible for any target.
|
||||
All three crates are under 1 KB. μCOBS is the largest due to its
|
||||
optimized encode (sub-slice scan, zero fast path, `copy_from_slice`)
|
||||
and decode (batch zero fill) paths.
|
||||
|
||||
### Crate properties
|
||||
|
||||
| Property | μCOBS | `cobs` 0.3 | `corncobs` 0.1 |
|
||||
| Property | μCOBS | `cobs` 0.5 | `corncobs` 0.1 |
|
||||
|----------------|:------:|:-----------------:|:--------------:|
|
||||
| `no_std` | always | opt-in[^1] | always |
|
||||
| Zero-alloc | yes | opt-in[^2] | yes |
|
||||
| `unsafe`-free | yes | yes | yes |
|
||||
| Implementation | ~120 LOC | ~790 LOC | ~645 LOC |
|
||||
| `const fn` encode | yes | no | no |
|
||||
| Implementation | ~140 LOC | ~790 LOC | ~645 LOC |
|
||||
|
||||
[^1]: Requires disabling the default `std` feature.
|
||||
[^2]: `alloc` is enabled by default via the `std` feature.
|
||||
|
||||
> Measured on Intel N100, Rust 1.93.1, Linux 6.12. Run `just bench` to
|
||||
> reproduce. Full Criterion reports are generated in `target/criterion/report/`.
|
||||
> Measured on AMD Ryzen 7 7840U, Rust 1.93.1, Linux 6.18. Run `just bench`
|
||||
> to reproduce. Full Criterion reports are generated in `target/criterion/report/`.
|
||||
|
||||
## Usage
|
||||
## When to use μCOBS
|
||||
|
||||
| You need… | μCOBS | `cobs` 0.5 | `corncobs` 0.1 |
|
||||
|---|:---:|:---:|:---:|
|
||||
| Minimal code to audit | **~140 LOC** | ~790 LOC | ~645 LOC |
|
||||
| Compile-time (`const fn`) encode | **yes** | no | no |
|
||||
| Fastest encode (nonzero/mixed) | **yes** | no | ties μCOBS |
|
||||
| Fastest encode (zero-heavy) | 2nd | **yes** | no |
|
||||
| Fastest decode (zero-heavy) | **yes (3×)** | no | 2nd |
|
||||
| Fastest decode (nonzero) | **ties corncobs** | no | **ties μCOBS** |
|
||||
| Fastest decode (mixed) | 2nd | no | **yes** |
|
||||
| Dead-simple API (3 functions) | **yes** | yes | more surface area |
|
||||
| In-place / streaming encode | no | no | **yes** |
|
||||
| `no_std` + zero-alloc by default | **yes** | opt-in | **yes** |
|
||||
| Thorough test suite | **106 tests, fuzz, proptest** | basic | basic |
|
||||
|
||||
**Choose μCOBS** if you want the smallest, most auditable COBS implementation
|
||||
with a `const fn` encoder, a dead-simple 3-function API, and leading or
|
||||
competitive throughput across most workloads — especially on embedded targets.
|
||||
|
||||
**Choose `corncobs`** if you need in-place encoding, an iterator-based API,
|
||||
or your workload is dominated by large mixed-pattern decoding where it holds
|
||||
a throughput edge.
|
||||
|
||||
**Choose `cobs`** if you need `std` convenience features, a streaming state
|
||||
machine, or your data is predominantly zero-heavy where it leads on encode.
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic encode and decode
|
||||
|
||||
```rust
|
||||
// Encode
|
||||
// Encode: [0x11, 0x00, 0x33] → [0x02, 0x11, 0x02, 0x33]
|
||||
let mut buf = [0u8; 16];
|
||||
let n = ucobs::encode(&[0x11, 0x00, 0x33], &mut buf).unwrap();
|
||||
assert_eq!(&buf[..n], &[0x02, 0x11, 0x02, 0x33]);
|
||||
|
||||
// Decode
|
||||
// Decode reverses it
|
||||
let mut out = [0u8; 16];
|
||||
let n = ucobs::decode(&[0x02, 0x11, 0x02, 0x33], &mut out).unwrap();
|
||||
let m = ucobs::decode(&buf[..n], &mut out).unwrap();
|
||||
assert_eq!(&out[..m], &[0x11, 0x00, 0x33]);
|
||||
```
|
||||
|
||||
### Buffer sizing
|
||||
|
||||
Use `max_encoded_len` to determine the required destination buffer size:
|
||||
|
||||
```rust
|
||||
let data = [0x01, 0x02, 0x03];
|
||||
let max = ucobs::max_encoded_len(data.len()); // 4 bytes
|
||||
|
||||
let mut buf = [0u8; 4];
|
||||
let n = ucobs::encode(&data, &mut buf).unwrap();
|
||||
assert_eq!(n, 4); // fits exactly
|
||||
```
|
||||
|
||||
If the destination is too small, `encode` returns `None` rather than panicking:
|
||||
|
||||
```rust
|
||||
let mut tiny = [0u8; 1];
|
||||
assert_eq!(ucobs::encode(&[0x01, 0x02], &mut tiny), None);
|
||||
```
|
||||
|
||||
### Framing for transport
|
||||
|
||||
Append a `0x00` sentinel after encoding to delimit frames on a wire. Strip
|
||||
it before decoding:
|
||||
|
||||
```rust
|
||||
let data = [0x11, 0x00, 0x33];
|
||||
|
||||
// Encode and append sentinel
|
||||
let mut frame = [0u8; 16];
|
||||
let n = ucobs::encode(&data, &mut frame).unwrap();
|
||||
frame[n] = 0x00;
|
||||
let wire = &frame[..n + 1];
|
||||
|
||||
// Receive: strip sentinel, then decode
|
||||
let cobs_data = &wire[..wire.len() - 1];
|
||||
let mut out = [0u8; 16];
|
||||
let m = ucobs::decode(cobs_data, &mut out).unwrap();
|
||||
assert_eq!(&out[..m], &data);
|
||||
```
|
||||
|
||||
### Parsing a stream of frames
|
||||
|
||||
Split a byte stream on `0x00` to extract individual COBS frames:
|
||||
|
||||
```rust
|
||||
// Two frames separated by 0x00 sentinels
|
||||
let stream = [
|
||||
0x02, 0x11, 0x02, 0x33, 0x00, // frame 1: [0x11, 0x00, 0x33]
|
||||
0x03, 0xAA, 0xBB, 0x00, // frame 2: [0xAA, 0xBB]
|
||||
];
|
||||
|
||||
let mut out = [0u8; 16];
|
||||
let frames: Vec<&[u8]> = stream.split(|&b| b == 0x00)
|
||||
.filter(|f| !f.is_empty())
|
||||
.collect();
|
||||
|
||||
let n = ucobs::decode(frames[0], &mut out).unwrap();
|
||||
assert_eq!(&out[..n], &[0x11, 0x00, 0x33]);
|
||||
|
||||
// Buffer sizing
|
||||
let max = ucobs::max_encoded_len(256); // 258
|
||||
let n = ucobs::decode(frames[1], &mut out).unwrap();
|
||||
assert_eq!(&out[..n], &[0xAA, 0xBB]);
|
||||
```
|
||||
|
||||
### Compile-time encoding
|
||||
|
||||
`encode` is `const fn`, so you can build COBS-encoded tables at compile
|
||||
time with zero runtime cost:
|
||||
|
||||
```rust
|
||||
const PING: [u8; 2] = {
|
||||
let mut buf = [0u8; 2];
|
||||
match ucobs::encode(&[0x01], &mut buf) {
|
||||
Some(_) => buf,
|
||||
None => panic!("buffer too small"),
|
||||
}
|
||||
};
|
||||
|
||||
const ACK: [u8; 3] = {
|
||||
let mut buf = [0u8; 3];
|
||||
match ucobs::encode(&[0x06, 0x00], &mut buf) {
|
||||
Some(_) => buf,
|
||||
None => panic!("buffer too small"),
|
||||
}
|
||||
};
|
||||
|
||||
// Baked into the binary — no runtime encoding needed
|
||||
assert_eq!(PING, [0x02, 0x01]);
|
||||
assert_eq!(ACK, [0x02, 0x06, 0x01]);
|
||||
```
|
||||
|
||||
### Error handling
|
||||
|
||||
Both `encode` and `decode` return `Option<usize>` — `None` on failure,
|
||||
never panic:
|
||||
|
||||
```rust
|
||||
let mut buf = [0u8; 8];
|
||||
|
||||
// Destination too small
|
||||
assert_eq!(ucobs::encode(&[1, 2, 3], &mut buf[..1]), None);
|
||||
|
||||
// Malformed input (zero byte in encoded stream)
|
||||
assert_eq!(ucobs::decode(&[0x00], &mut buf), None);
|
||||
|
||||
// Truncated frame (code byte promises more data than exists)
|
||||
assert_eq!(ucobs::decode(&[0x05, 0x11], &mut buf), None);
|
||||
|
||||
// Empty input is valid
|
||||
assert_eq!(ucobs::encode(&[], &mut buf), Some(1)); // encodes to [0x01]
|
||||
assert_eq!(ucobs::decode(&[], &mut buf), Some(0)); // decodes to []
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
| Function | Signature | Description |
|
||||
|---|---|---|
|
||||
| `encode` | `(src: &[u8], dest: &mut [u8]) -> Option<usize>` | COBS-encode `src` into `dest`. Returns byte count or `None` if buffer too small. |
|
||||
| `encode` | `const fn(src: &[u8], dest: &mut [u8]) -> Option<usize>` | COBS-encode `src` into `dest`. Returns byte count or `None` if buffer too small. |
|
||||
| `decode` | `(src: &[u8], dest: &mut [u8]) -> Option<usize>` | Decode COBS data. Returns byte count or `None` if input is malformed. |
|
||||
| `max_encoded_len` | `const fn(src_len: usize) -> usize` | Maximum encoded size for a given input length. |
|
||||
|
||||
**Note:** The encoder does *not* append a trailing `0x00` sentinel. Append it
|
||||
yourself when framing for transport.
|
||||
|
||||
## Minimum Supported Rust Version
|
||||
|
||||
The default build requires **Rust 1.93+** (for const `copy_from_slice`).
|
||||
|
||||
### `legacy-msrv` feature
|
||||
|
||||
If you're targeting a toolchain older than 1.93 (e.g. Xtensa), enable the
|
||||
`legacy-msrv` feature to fall back to a manual byte copy in the encoder:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ucobs = { version = "0.3", features = ["legacy-msrv"] }
|
||||
```
|
||||
|
||||
All other optimizations (sub-slice scan, zero fast path, decode batch fill)
|
||||
are available regardless of this feature. Only the encode copy phase is
|
||||
affected — it uses a byte loop instead of `copy_from_slice`/memcpy.
|
||||
|
||||
## Testing
|
||||
|
||||
μCOBS has one of the most thorough test suites of any COBS implementation —
|
||||
106 tests across 7 categories:
|
||||
|
||||
- **Canonical vectors** — every example from Cheshire & Baker 1999 (the original
|
||||
COBS paper), plus the full Wikipedia vector set
|
||||
- **External corpora** — vectors drawn from `cobs-c`, `nanocobs`, `cobs2-rs`,
|
||||
Jacques Fortier's C implementation, and the Python `cobs` package
|
||||
- **Cross-crate interop** — byte-for-byte validation against both `corncobs` and
|
||||
`cobs` crates on randomized payloads up to 4 KB
|
||||
- **Property-based tests** — 6 proptest suites covering round-trip correctness,
|
||||
no-zero-in-output invariants, encoding properties, decoding properties,
|
||||
structural/algebraic properties, and boundary-region behavior
|
||||
- **Fuzz targets** — 3 `cargo-fuzz` harnesses (decode, round-trip, small-dest)
|
||||
for continuous coverage of edge cases
|
||||
- **Boundary tests** — exhaustive coverage of 254/255-byte block boundaries,
|
||||
multi-block splits, buffer-exact fits, and off-by-one dest sizes
|
||||
- **Compile-time verification** — `const` assertions that validate encode
|
||||
correctness at compile time
|
||||
|
||||
```sh
|
||||
# Unit + property + interop tests
|
||||
just test-unit
|
||||
|
||||
+8
-4
@@ -1,4 +1,6 @@
|
||||
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
|
||||
|
||||
// ── Test payloads ───────────────────────────────────────────────────
|
||||
|
||||
@@ -51,9 +53,11 @@ fn cobs_encode(data: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn cobs_decode(encoded: &[u8], out: &mut [u8]) -> usize {
|
||||
// unwrap_or(0): the cobs crate returns Err(EmptyFrame) for empty input,
|
||||
// which is valid COBS. We treat it as 0 decoded bytes for benchmarking.
|
||||
cobs::decode(encoded, out).unwrap_or(0)
|
||||
// The cobs crate returns DecodeReport on success or Err(EmptyFrame)
|
||||
// for empty input. We extract parsed_size, treating errors as 0.
|
||||
cobs::decode(encoded, out)
|
||||
.map(|report| report.parsed_size())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
// ── Benchmarks ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 00411472de4d6cdb296c04bc52fd533354bc25ba1765807da8b7994868fcb987 # shrinks to len = 1
|
||||
cc 81ebf688f1dd5ea2a735756a7fb703b92c2a2033057ae91886577c6a63763cf5 # shrinks to data = [0]
|
||||
cc 32d0d2d26e2be6ec66b432f1e9baee378777b1a00b959922cff7a5784292ec4b # shrinks to data = [0]
|
||||
cc fe447e0e58f4c0b21f6e1b38a90bd33578c968967c956964a06013a4df977d68 # shrinks to data = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
|
||||
+281
-42
@@ -9,54 +9,234 @@
|
||||
//! Overhead is at most 1 byte per 254 input bytes plus 1; see
|
||||
//! [`max_encoded_len`] for the exact formula.
|
||||
//!
|
||||
//! This crate is `no_std` and zero-alloc — suitable for embedded firmware.
|
||||
//! This crate is `no_std`, zero-alloc, and `unsafe`-free — it runs
|
||||
//! everywhere from 8-bit MCUs to servers.
|
||||
//!
|
||||
//! # Sentinel convention
|
||||
//! # Feature flags
|
||||
//!
|
||||
//! - **`legacy-msrv`** — Enables compilation on Rust 1.83+ by replacing
|
||||
//! the const `copy_from_slice` (requires Rust 1.93) with a manual byte
|
||||
//! loop in the encoder. All other optimizations are unaffected.
|
||||
//!
|
||||
//! # Quick start
|
||||
//!
|
||||
//! ```
|
||||
//! // Encode
|
||||
//! let mut buf = [0u8; 16];
|
||||
//! let n = ucobs::encode(&[0x11, 0x00, 0x33], &mut buf).unwrap();
|
||||
//! assert_eq!(&buf[..n], &[0x02, 0x11, 0x02, 0x33]);
|
||||
//!
|
||||
//! // Decode
|
||||
//! let mut out = [0u8; 16];
|
||||
//! let m = ucobs::decode(&buf[..n], &mut out).unwrap();
|
||||
//! assert_eq!(&out[..m], &[0x11, 0x00, 0x33]);
|
||||
//! ```
|
||||
//!
|
||||
//! # Buffer sizing
|
||||
//!
|
||||
//! Use [`max_encoded_len`] to determine the required destination buffer
|
||||
//! size before encoding:
|
||||
//!
|
||||
//! ```
|
||||
//! let data = [0x01, 0x02, 0x03];
|
||||
//! let max = ucobs::max_encoded_len(data.len()); // 4
|
||||
//!
|
||||
//! let mut buf = [0u8; 4];
|
||||
//! let n = ucobs::encode(&data, &mut buf).unwrap();
|
||||
//! assert_eq!(n, 4); // fits exactly
|
||||
//! ```
|
||||
//!
|
||||
//! If the destination is too small, `encode` returns `None` rather than
|
||||
//! panicking:
|
||||
//!
|
||||
//! ```
|
||||
//! let mut tiny = [0u8; 1];
|
||||
//! assert_eq!(ucobs::encode(&[0x01, 0x02], &mut tiny), None);
|
||||
//! ```
|
||||
//!
|
||||
//! # Framing for transport
|
||||
//!
|
||||
//! The encoder does **not** append a trailing `0x00` sentinel. The decoder
|
||||
//! expects input **without** a trailing sentinel. Callers should append /
|
||||
//! strip the sentinel themselves when framing for transport:
|
||||
//! expects input **without** a trailing sentinel. Append and strip the
|
||||
//! sentinel yourself when framing for transport:
|
||||
//!
|
||||
//! ```
|
||||
//! let data = [0x11, 0x00, 0x33];
|
||||
//!
|
||||
//! // Encode — leave room for the sentinel byte
|
||||
//! // Encode into a wire frame: [COBS bytes...] [0x00 sentinel]
|
||||
//! let mut frame = [0u8; 16];
|
||||
//! let n = ucobs::encode(&data, &mut frame).unwrap();
|
||||
//! frame[n] = 0x00; // append sentinel for framing
|
||||
//! frame[n] = 0x00; // append sentinel
|
||||
//! let wire = &frame[..n + 1];
|
||||
//!
|
||||
//! // Decode — strip sentinel before decoding
|
||||
//! // On the receiving end, strip the sentinel before decoding
|
||||
//! let cobs_data = &wire[..wire.len() - 1];
|
||||
//! let mut out = [0u8; 16];
|
||||
//! let m = ucobs::decode(&frame[..n], &mut out).unwrap();
|
||||
//! let m = ucobs::decode(cobs_data, &mut out).unwrap();
|
||||
//! assert_eq!(&out[..m], &data);
|
||||
//! ```
|
||||
//!
|
||||
//! # Parsing a stream of frames
|
||||
//!
|
||||
//! In a byte stream, split on `0x00` to extract individual COBS frames,
|
||||
//! then decode each one:
|
||||
//!
|
||||
//! ```
|
||||
//! // Simulate a stream containing two frames separated by 0x00 sentinels
|
||||
//! let stream = [
|
||||
//! 0x02, 0x11, 0x02, 0x33, 0x00, // frame 1: encodes [0x11, 0x00, 0x33]
|
||||
//! 0x03, 0xAA, 0xBB, 0x00, // frame 2: encodes [0xAA, 0xBB]
|
||||
//! ];
|
||||
//!
|
||||
//! let mut out = [0u8; 16];
|
||||
//! let frames: Vec<&[u8]> = stream.split(|&b| b == 0x00)
|
||||
//! .filter(|f| !f.is_empty())
|
||||
//! .collect();
|
||||
//!
|
||||
//! let n = ucobs::decode(frames[0], &mut out).unwrap();
|
||||
//! assert_eq!(&out[..n], &[0x11, 0x00, 0x33]);
|
||||
//!
|
||||
//! let n = ucobs::decode(frames[1], &mut out).unwrap();
|
||||
//! assert_eq!(&out[..n], &[0xAA, 0xBB]);
|
||||
//! ```
|
||||
//!
|
||||
//! # Compile-time encoding
|
||||
//!
|
||||
//! [`encode`] is `const fn`, so you can build COBS-encoded lookup tables
|
||||
//! or protocol headers at compile time with zero runtime cost:
|
||||
//!
|
||||
//! ```
|
||||
//! // Pre-encode a command table at compile time
|
||||
//! const PING: [u8; 2] = {
|
||||
//! let mut buf = [0u8; 2];
|
||||
//! match ucobs::encode(&[0x01], &mut buf) {
|
||||
//! Some(_) => buf,
|
||||
//! None => panic!("buffer too small"),
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! const ACK: [u8; 3] = {
|
||||
//! let mut buf = [0u8; 3];
|
||||
//! match ucobs::encode(&[0x06, 0x00], &mut buf) {
|
||||
//! Some(_) => buf,
|
||||
//! None => panic!("buffer too small"),
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! // No runtime encoding needed — these are baked into the binary
|
||||
//! assert_eq!(PING, [0x02, 0x01]);
|
||||
//! assert_eq!(ACK, [0x02, 0x06, 0x01]);
|
||||
//! ```
|
||||
//!
|
||||
//! # Error handling
|
||||
//!
|
||||
//! Both [`encode`] and [`decode`] return `Option<usize>` — `None` on
|
||||
//! failure, never panic.
|
||||
//!
|
||||
//! ```
|
||||
//! let mut buf = [0u8; 8];
|
||||
//!
|
||||
//! // Destination too small for encode
|
||||
//! assert_eq!(ucobs::encode(&[1, 2, 3], &mut buf[..1]), None);
|
||||
//!
|
||||
//! // Malformed COBS data (zero byte in encoded stream)
|
||||
//! assert_eq!(ucobs::decode(&[0x00], &mut buf), None);
|
||||
//!
|
||||
//! // Truncated frame (code byte promises more data than exists)
|
||||
//! assert_eq!(ucobs::decode(&[0x05, 0x11], &mut buf), None);
|
||||
//!
|
||||
//! // Empty input is valid for both
|
||||
//! assert_eq!(ucobs::encode(&[], &mut buf), Some(1)); // encodes to [0x01]
|
||||
//! assert_eq!(ucobs::decode(&[], &mut buf), Some(0)); // decodes to []
|
||||
//! ```
|
||||
|
||||
#![no_std]
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
/// Encode `src` into `dest` using COBS. Returns the number of bytes written,
|
||||
/// or `None` if `dest` is too small.
|
||||
/// Copy `src` into `dest[offset..]` in a const-compatible way.
|
||||
/// Default path uses `copy_from_slice` (Rust 1.93+, compiles to memcpy).
|
||||
/// With `legacy-msrv` feature, falls back to a manual loop for Rust 1.83+.
|
||||
#[inline(always)]
|
||||
#[cfg(not(feature = "legacy-msrv"))]
|
||||
const fn const_copy(dest: &mut [u8], offset: usize, src: &[u8]) {
|
||||
let (_, tail) = dest.split_at_mut(offset);
|
||||
let (chunk, _) = tail.split_at_mut(src.len());
|
||||
chunk.copy_from_slice(src);
|
||||
}
|
||||
|
||||
/// Fallback const copy for toolchains older than Rust 1.93.
|
||||
#[inline(always)]
|
||||
#[cfg(feature = "legacy-msrv")]
|
||||
const fn const_copy(dest: &mut [u8], offset: usize, src: &[u8]) {
|
||||
let mut i = 0;
|
||||
while i < src.len() {
|
||||
dest[offset + i] = src[i];
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// COBS-encode `src` into `dest`.
|
||||
///
|
||||
/// The output does **not** include a trailing `0x00` sentinel — the caller
|
||||
/// should append it as a frame delimiter.
|
||||
/// Returns the number of bytes written, or `None` if `dest` is too small.
|
||||
/// Use [`max_encoded_len`] to size the destination buffer.
|
||||
///
|
||||
/// The output does **not** include a trailing `0x00` sentinel — append it
|
||||
/// yourself when framing for transport.
|
||||
///
|
||||
/// This function is `const fn`, so it can encode data at compile time.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let mut buf = [0u8; 8];
|
||||
/// let n = ucobs::encode(&[0x00], &mut buf).unwrap();
|
||||
/// assert_eq!(&buf[..n], &[0x01, 0x01]);
|
||||
/// ```
|
||||
///
|
||||
/// Compile-time encoding:
|
||||
///
|
||||
/// ```
|
||||
/// const ENCODED: [u8; 4] = {
|
||||
/// let mut buf = [0u8; 4];
|
||||
/// match ucobs::encode(&[0x11, 0x00, 0x33], &mut buf) {
|
||||
/// Some(_) => buf,
|
||||
/// None => panic!("buffer too small"),
|
||||
/// }
|
||||
/// };
|
||||
/// assert_eq!(ENCODED, [0x02, 0x11, 0x02, 0x33]);
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn encode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
pub const fn encode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
let mut si = 0;
|
||||
let mut di = 0;
|
||||
|
||||
loop {
|
||||
// Scan for next zero (or 254-byte cap).
|
||||
let remaining = src.len() - si;
|
||||
let max_run = if remaining < 254 { remaining } else { 254 };
|
||||
let run = if max_run > 0 && src[si] == 0x00 {
|
||||
0
|
||||
} else {
|
||||
src[si..si + max_run]
|
||||
.iter()
|
||||
.position(|&b| b == 0x00)
|
||||
.unwrap_or(max_run)
|
||||
};
|
||||
|
||||
// Create bounded source window (split_at is const since Rust 1.71).
|
||||
let (_, src_tail) = src.split_at(si);
|
||||
let (src_window, _) = src_tail.split_at(max_run);
|
||||
|
||||
// Fast path: leading zero byte avoids scan loop overhead.
|
||||
// Always continue — the next iteration emits the trailing group code byte.
|
||||
if max_run > 0 && src_window[0] == 0x00 {
|
||||
if di >= dest.len() {
|
||||
return None;
|
||||
}
|
||||
dest[di] = 0x01;
|
||||
di += 1;
|
||||
si += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Phase 1: Scan for next zero byte.
|
||||
// LLVM sees `run < src_window.len()` → eliminates bounds check.
|
||||
let mut run = 0;
|
||||
while run < src_window.len() && src_window[run] != 0x00 {
|
||||
run += 1;
|
||||
}
|
||||
let full_block = run == 254;
|
||||
|
||||
// Write code byte.
|
||||
@@ -66,24 +246,22 @@ pub fn encode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
dest[di] = if full_block { 0xFF } else { (run + 1) as u8 };
|
||||
di += 1;
|
||||
|
||||
// Bulk-copy the run.
|
||||
// Phase 2: Copy via const copy_from_slice (Rust 1.93+) → memcpy.
|
||||
if run > 0 {
|
||||
if di + run > dest.len() {
|
||||
return None;
|
||||
}
|
||||
dest[di..di + run].copy_from_slice(&src[si..si + run]);
|
||||
let (src_chunk, _) = src_window.split_at(run);
|
||||
const_copy(dest, di, src_chunk);
|
||||
di += run;
|
||||
}
|
||||
si += run;
|
||||
|
||||
if full_block {
|
||||
// 254 non-zero bytes emitted; no implicit zero.
|
||||
// If input is exhausted exactly here, we're done.
|
||||
if si >= src.len() {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Run ended at a zero or end-of-input.
|
||||
if si >= src.len() {
|
||||
break;
|
||||
}
|
||||
@@ -94,12 +272,29 @@ pub fn encode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
Some(di)
|
||||
}
|
||||
|
||||
/// Decode a COBS-encoded buffer. Returns the number of decoded bytes
|
||||
/// written to `dest`, or `None` if the input is malformed or `dest` is
|
||||
/// too small.
|
||||
/// Decode a COBS-encoded buffer.
|
||||
///
|
||||
/// Returns the number of decoded bytes written to `dest`, or `None` if the
|
||||
/// input is malformed or `dest` is too small.
|
||||
///
|
||||
/// `src` should **not** include the trailing `0x00` frame sentinel — strip
|
||||
/// it before calling this function.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let mut out = [0u8; 8];
|
||||
/// let n = ucobs::decode(&[0x02, 0x11, 0x02, 0x33], &mut out).unwrap();
|
||||
/// assert_eq!(&out[..n], &[0x11, 0x00, 0x33]);
|
||||
/// ```
|
||||
///
|
||||
/// Malformed input returns `None`:
|
||||
///
|
||||
/// ```
|
||||
/// let mut out = [0u8; 8];
|
||||
/// assert_eq!(ucobs::decode(&[0x00], &mut out), None); // unexpected zero
|
||||
/// assert_eq!(ucobs::decode(&[0x05, 0x11], &mut out), None); // truncated
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn decode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
let mut si = 0;
|
||||
@@ -110,18 +305,36 @@ pub fn decode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
if code == 0 {
|
||||
return None; // unexpected zero in COBS data
|
||||
}
|
||||
|
||||
if code == 1 {
|
||||
// Batch path: count consecutive 0x01 codes, fill zeros in bulk.
|
||||
let mut count = 1usize;
|
||||
while si < src.len() && src[si] == 0x01 {
|
||||
si += 1;
|
||||
count += 1;
|
||||
}
|
||||
// Each 0x01 inserts an implicit zero, except the last at end-of-input.
|
||||
let zeros = if si < src.len() { count } else { count - 1 };
|
||||
if zeros > 0 {
|
||||
if di + zeros > dest.len() {
|
||||
return None;
|
||||
}
|
||||
dest[di..di + zeros].fill(0);
|
||||
di += zeros;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Bulk-copy `code - 1` data bytes.
|
||||
let n = code - 1;
|
||||
if n > 0 {
|
||||
if si + n > src.len() || di + n > dest.len() {
|
||||
return None;
|
||||
}
|
||||
dest[di..di + n].copy_from_slice(&src[si..si + n]);
|
||||
di += n;
|
||||
si += n;
|
||||
if si + n > src.len() || di + n > dest.len() {
|
||||
return None;
|
||||
}
|
||||
dest[di..di + n].copy_from_slice(&src[si..si + n]);
|
||||
di += n;
|
||||
si += n;
|
||||
// If code < 0xFF, an implicit zero follows (unless we're at the end).
|
||||
if code < 0xFF && si < src.len() {
|
||||
if code != 0xFF && si < src.len() {
|
||||
if di >= dest.len() {
|
||||
return None;
|
||||
}
|
||||
@@ -133,6 +346,17 @@ pub fn decode(src: &[u8], dest: &mut [u8]) -> Option<usize> {
|
||||
}
|
||||
|
||||
/// Maximum encoded size for a given source length (excluding sentinel).
|
||||
///
|
||||
/// Use this to allocate a destination buffer for [`encode`]. The formula
|
||||
/// is `src_len + (src_len / 254) + 1`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// assert_eq!(ucobs::max_encoded_len(0), 1);
|
||||
/// assert_eq!(ucobs::max_encoded_len(1), 2);
|
||||
/// assert_eq!(ucobs::max_encoded_len(254), 256);
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub const fn max_encoded_len(src_len: usize) -> usize {
|
||||
src_len + (src_len / 254) + 1
|
||||
@@ -155,6 +379,21 @@ mod tests {
|
||||
encode(input, &mut buf).map(|n| buf[..n].to_vec())
|
||||
}
|
||||
|
||||
// ── Compile-time (const fn) encode ────────────────────────────
|
||||
|
||||
const _: () = {
|
||||
let input = [0x11, 0x00, 0x33];
|
||||
let mut buf = [0u8; 8];
|
||||
let Some(n) = encode(&input, &mut buf) else {
|
||||
panic!("const encode failed");
|
||||
};
|
||||
assert!(n == 4);
|
||||
assert!(buf[0] == 0x02);
|
||||
assert!(buf[1] == 0x11);
|
||||
assert!(buf[2] == 0x02);
|
||||
assert!(buf[3] == 0x33);
|
||||
};
|
||||
|
||||
// ── Wikipedia canonical decode vectors (Cheshire & Baker 1999) ──
|
||||
|
||||
#[test]
|
||||
@@ -729,11 +968,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn interop_random_payloads() {
|
||||
use rand::Rng;
|
||||
let mut rng = rand::thread_rng();
|
||||
use rand::RngExt;
|
||||
let mut rng = rand::rng();
|
||||
for _ in 0..500 {
|
||||
let len = rng.gen_range(0..=512);
|
||||
let data: Vec<u8> = (0..len).map(|_| rng.gen()).collect();
|
||||
let len = rng.random_range(0..=512);
|
||||
let data: Vec<u8> = (0..len).map(|_| rng.random()).collect();
|
||||
cross_encode(&data);
|
||||
cross_decode(&data);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user