Skip to content

Commit

Permalink
Serialize boxed bitstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
bartblast committed Oct 17, 2024
1 parent 646eb03 commit 93ec588
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions assets/js/serializer.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
"use strict";

import Bitstring from "./bitstring.mjs";
import Type from "./type.mjs";

export default class Serializer {
static serialize(term) {
const serialized = JSON.stringify(term, (_key, value) => {
if (value?.type === "atom") {
return `__atom__:${value.value}`;
}

if (value?.type === "bitstring") {
if (Type.isBinary(value)) {
return `__binary__:${Bitstring.toText(value)}`;
}

return {...value, bits: Array.from(value.bits)};
}

if (value?.type === "float") {
return `__float__:${value.value.toString()}`;
}
Expand Down
31 changes: 31 additions & 0 deletions test/javascript/serializer_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,37 @@ describe("Serializer", () => {
assert.equal(serialize(term), expected);
});

describe("bitstring", () => {
it("binary", () => {
const term = Type.bitstring('a"bc');
const expected = '[1,"__binary__:a\\"bc"]';

assert.equal(serialize(term), expected);
});

it("nested binary", () => {
const term = {a: Type.bitstring('a"bc'), b: 2};
const expected = '[1,{"a":"__binary__:a\\"bc","b":2}]';

assert.equal(serialize(term), expected);
});

it("non-binary", () => {
const term = Type.bitstring([1, 0, 1, 0]);
const expected = '[1,{"type":"bitstring","bits":[1,0,1,0]}]';

assert.equal(serialize(term), expected);
});

it("nested non-binary", () => {
const term = {a: Type.bitstring([1, 0, 1, 0]), b: 2};
const expected =
'[1,{"a":{"type":"bitstring","bits":[1,0,1,0]},"b":2}]';

assert.equal(serialize(term), expected);
});
});

it("float", () => {
const term = Type.float(1.23);
const expected = '[1,"__float__:1.23"]';
Expand Down

0 comments on commit 93ec588

Please sign in to comment.