diff --git a/assets/js/serializer.mjs b/assets/js/serializer.mjs index e09ef45d5..ce17d2416 100644 --- a/assets/js/serializer.mjs +++ b/assets/js/serializer.mjs @@ -1,5 +1,8 @@ "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) => { @@ -7,6 +10,14 @@ export default class Serializer { 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()}`; } diff --git a/test/javascript/serializer_test.mjs b/test/javascript/serializer_test.mjs index 0ca3af272..9421ffe78 100644 --- a/test/javascript/serializer_test.mjs +++ b/test/javascript/serializer_test.mjs @@ -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"]';