Skip to content

Commit

Permalink
cbor js testing
Browse files Browse the repository at this point in the history
  • Loading branch information
kuhe committed May 16, 2024
1 parent f1673f0 commit adb9158
Showing 1 changed file with 68 additions and 25 deletions.
93 changes: 68 additions & 25 deletions packages/core/src/submodules/cbor/cbor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,74 @@
import { cbor } from "./cbor";

const toBytes = (str: string) => {
const bytes = [] as number[];
str.split(/../g).forEach((pair: string) => {
bytes.push(parseInt(pair, 16));
});
return new Uint8Array(bytes);
};

describe("cbor", () => {
it("should", async () => {
const encoded = toBytes(
"A663696E74FB41DFFFFFFFC66666666E6567696E742065666C6F6174F9FC00636D6170A2666E6567696E742065666C6F6174C2F93E006474727565F56566616C73659F01F4FF"
);
console.log("encoded", encoded);

const decoded = cbor.deserialize(encoded);
console.log("decoded", decoded);

const reencoded = cbor.serialize(decoded);
console.log("reencoded", reencoded);
const examples = [
{
name: "false",
data: false,
// special major 7 = 0b111 plus false(20) = 0b10100
cbor: new Uint8Array([0b111_10100]),
},
{
name: "true",
data: true,
// increment from false
cbor: new Uint8Array([0b111_10101]),
},
{
name: "null",
data: null,
// increment from true
cbor: new Uint8Array([0b111_10110]),
},
{
name: "undefined",
data: undefined,
// increment from null
cbor: new Uint8Array([0b111_10111]),
},
{
name: "an unsigned zero integer",
data: 0,
// unsigned int major (0) plus 00's.
cbor: new Uint8Array([0b000_00000]),
},
{
name: "negative 1",
data: -1,
// negative major (1) plus 00's, since -1 is the first negative number.
cbor: new Uint8Array([0b001_00000]),
},
{
name: "an empty string",
data: "",
// string major plus 00's
cbor: new Uint8Array([0b011_00000]),
},
{
name: "a short string",
data: "hello, world",
cbor: new Uint8Array([108, 104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]),
},
{
name: "simple object",
data: {
message: "hello, world",
},
cbor: new Uint8Array([
161, 103, 109, 101, 115, 115, 97, 103, 101, 108, 104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100,
]),
},
];

const redecoded = cbor.deserialize(reencoded);
console.log("redecoded", redecoded);
for (const { name, data, cbor: cbor_representation } of examples) {
it(`should encode for ${name}`, async () => {
const serialized = cbor.serialize(data);
expect(serialized).toEqual(cbor_representation);
});

const badobj = {} as any;
badobj.a = badobj;
cbor.serialize(badobj);
});
it(`should decode for ${name}`, async () => {
const deserialized = cbor.deserialize(cbor_representation);
expect(deserialized).toEqual(data);
});
}
});

0 comments on commit adb9158

Please sign in to comment.