function packet(s) {
const b = typeof s === "string" ? bits(s) : s;
const version = takeInt(b, 3);
const type = takeInt(b, 3);
if (type === 4) {
let value = 0n;
let prefix;
do {
prefix = takeInt(b, 1);
value = (value << 4n) | BigInt(takeInt(b, 4));
} while (prefix);
return { version, type, value };
} else {
const packets = [];
const lengthType = takeInt(b, 1);
if (lengthType === 0) {
const size = takeInt(b, 15);
const sub = take(b, size);
for (let p; (p = packet(sub)); ) packets.push(p);
return { version, type, packets, lengthType, size };
} else if (lengthType === 1) {
const n = takeInt(b, 11);
for (let i = 0; i < n; i++) packets.push(packet(b));
return { version, type, packets, lengthType, n };
}
}
}