COBS (Consistent Overhead Byte Stuffing) codec in pure MoonBit
import {
"MuVirus/cobs" @cobs,
}let payload = b"\x01\x02\x00\x03hello\x00world"
let frame = @cobs.encode(payload)
// frame = 03 01 02 07 03 68 65 6c 6c 6f 06 77 6f 72 6c 64 00
// (内部无 0x00,末尾是分隔符)
match @cobs.decode(frame) {
Ok(data) => assert_eq(data, payload) // 还原成功
Err(TruncatedFrame) => ... // 帧在分隔符之前结束
Err(TrailingData) => ... // 分隔符之后还有多余字节
}let dec = @cobs.Decoder::new()
for byte in wire {
match dec.push(byte) {
Some(data) => handle(data) // 0x00 分隔符到达,一帧完成
None => ()
}
}///|
let frames : Array[Bytes] = @cobs.Decoder::new().feed(buffer)| 函数 | 说明 |
|---|---|
| max_encoded_len(n) -> Int | n 字节载荷的编码长度上界(含分隔符) |
| encode(Bytes) -> Bytes | 编码为完整帧(含末尾 0x00 分隔符) |
| decode(Bytes) -> Result[Bytes, DecodeError] | 严格解码一帧 |
| Decoder::new() / push / feed / finish | 流式增量解码 |
moon test # 运行测试
moon fmt # 格式化
moon info # 更新 .mbti 接口
moon run cmd/main # 运行演示impl Show for DecodeErrorpub(all) struct Decoder {
// private fields
}fn encode(payload : Bytes) -> Bytesfn max_encoded_len(n : Int) -> IntInstall
Download zipCOBS (Consistent Overhead Byte Stuffing) codec in pure MoonBit