Skip to content

Commit

Permalink
fix the discriminate case init position (#559)
Browse files Browse the repository at this point in the history
  • Loading branch information
barnjamin committed May 17, 2024
1 parent 382adbb commit f6bbc96
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 5 deletions.
71 changes: 67 additions & 4 deletions core/base/__tests__/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { describe, expect, it } from "@jest/globals";

import {
Layout,
serializeLayout,
deserializeLayout,
LayoutToType,
RoArray,
addFixedValues,
layoutDiscriminator,
bitsetItem,
} from './../src/index.js';
column,
deserializeLayout,
layoutDiscriminator,
serializeLayout,
} from "./../src/index.js";

// prettier-ignore
const testLayout = [
{ name: "uintFixedPrimitive", binary: "uint", size: 1, custom: 3 },
{
Expand Down Expand Up @@ -105,6 +109,7 @@ const testLayout = [
// type DynamicItems = DynamicItemsOfLayout<typeof testLayout>;
// type DynamicValues = LayoutToType<DynamicItems>;

// prettier-ignore
describe("Layout tests", function () {

const completeValues = {
Expand Down Expand Up @@ -337,3 +342,61 @@ describe("Layout tests", function () {

});
});

describe("Switch Layout Size Tests", () => {
it("Can discriminate a set of layouts", () => {
const layouta = [
{
name: "payload",
binary: "bytes",
lengthSize: 2,
layout: [
{
name: "payload",
binary: "switch",
idSize: 1,
layouts: [
[[0, "Direct"], []],
[[1, "Payload"], [{ name: "data", binary: "bytes", lengthSize: 4 }]],
],
},
],
},
] as const satisfies Layout;

const layoutb = [
{
name: "payload",
binary: "bytes",
lengthSize: 3,
layout: [
{
name: "payload",
binary: "switch",
idSize: 1,
layouts: [
[[0, "Nothing"], []],
[[1, "Data"], [{ name: "data", binary: "bytes", lengthSize: 4 }]],
],
},
],
},
] as const satisfies Layout;

const messageLayouts = [
["Layout", layouta],
["LayoutB", layoutb],
] as const satisfies RoArray<[string, Layout]>;
const messageDiscriminator = layoutDiscriminator(column(messageLayouts, 1));

const b: LayoutToType<typeof layoutb> = {
payload: {
payload: { id: "Data", data: new Uint8Array([0, 0, 0, 0]) },
},
};

const data = serializeLayout(layoutb, b);
const idx = messageDiscriminator(data);
expect(idx).toEqual(1);
});
});
2 changes: 1 addition & 1 deletion core/base/src/utils/layout/discriminate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,9 @@ function layoutItemMeta(
//keep track of the current index in each case's fixed bytes array
const itIndexes = caseFixedBytes.map(_ => 0);

let caseIndex = 0;
for (let bytePos = 0; bytePos < minLen;) {
let byteVal = null;
let caseIndex = 0;
while (caseIndex < caseFixedBytes.length) {
let curItIndex = itIndexes[caseIndex];
const curFixedBytes = caseFixedBytes[caseIndex];
Expand Down

0 comments on commit f6bbc96

Please sign in to comment.