Consistent overhead byte stuffing: Difference between revisions

Added Wren
(Initial draft task with →‎C: and →‎Insitux)
 
(Added Wren)
Line 124:
(assert (= (COBS a) b)))
</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
Just the basic task for now.
<syntaxhighlight lang="ecmascript">import "./fmt" for Fmt
 
class COBS {
static encode(data) {
if (!((data is List) && data.count > 0 && data.all { |i| i.isInteger && i >= 0 && i < 256 })) {
Fiber.abort("data must be a non-empty list of bytes.")
}
var enc = [-1]
var ins = 0
var code = 1
var addLastCode = true
for (byte in data) {
if (byte != 0) {
enc.add(byte)
code = code + 1
}
addLastCode = true
if (byte == 0|| code == 255) {
if (code == 255) addLastCode = false
enc[ins] = code
code = 1
ins = enc.count
enc.add(-1)
}
}
if (addLastCode) {
enc[ins] = code
enc.add(0)
} else {
enc[ins] = 0
}
return enc
}
}
 
var examples = [
[0x00],
[0x00, 0x00],
[0x00, 0x11, 0x00],
[0x11, 0x22, 0x00, 0x33],
[0x11, 0x22, 0x33, 0x44],
[0x11, 0x00, 0x00, 0x00],
(0x01..0xfe).toList,
(0x00..0xfe).toList,
(0x01..0xff).toList,
(0x02..0xff).toList + [0x00],
(0x03..0xff).toList + [0x00, 0x01]
]
 
for (example in examples) {
var res = COBS.encode(example)
if (example.count < 5) {
Fmt.print("$-33s -> $02x", Fmt.swrite("$02x", example), res)
} else {
var e = Fmt.va("xz", 2, example, 0, " ", "", "", 5, "...")
var r = Fmt.va("xz", 2, res, 0, " ", "", "", 5, "...")
Fmt.print("$s -> $s", e, r)
}
}</syntaxhighlight>
 
{{out}}
<pre>
00 -> 01 01 00
00 00 -> 01 01 01 00
00 11 00 -> 01 02 11 01 00
11 22 00 33 -> 03 11 22 02 33 00
11 22 33 44 -> 05 11 22 33 44 00
11 00 00 00 -> 02 11 01 01 01 00
01 02 03 04 05 ... fa fb fc fd fe -> ff 01 02 03 04 ... fb fc fd fe 00
00 01 02 03 04 ... fa fb fc fd fe -> 01 ff 01 02 03 ... fb fc fd fe 00
01 02 03 04 05 ... fb fc fd fe ff -> ff 01 02 03 04 ... fd fe 02 ff 00
02 03 04 05 06 ... fc fd fe ff 00 -> ff 02 03 04 05 ... fe ff 01 01 00
03 04 05 06 07 ... fd fe ff 00 01 -> fe 03 04 05 06 ... fe ff 02 01 00
</pre>
9,476

edits