Skip to content

Commit

Permalink
fix: sliceFrom api (#394)
Browse files Browse the repository at this point in the history
* chore: reproduce the bug in sliceFrom()

* fix: sliceFrom()

* chore: more comments
  • Loading branch information
twoeths authored Aug 19, 2024
1 parent 216241d commit 4ca1d6f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
2 changes: 2 additions & 0 deletions packages/ssz/src/viewDU/listComposite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ export class ListCompositeTreeViewDU<
sliceFrom(index: number): this {
// Commit before getting rootNode to ensure all pending data is in the rootNode
this.commit();
// populate to `this.nodes` to ensure all nodes are loaded
this.populateAllNodes();

// If negative index, try to make it positive long as |index| < length
if (index < 0) {
Expand Down
20 changes: 12 additions & 8 deletions packages/ssz/test/unit/byType/listComposite/tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {CompositeView, ContainerType, ListCompositeType, toHexString, UintNumber
import {ArrayCompositeTreeViewDU} from "../../../../src/viewDU/arrayComposite";
import {ssz} from "../../../lodestarTypes/primitive";
import {runViewTestMutation} from "../runViewTestMutation";
import {ListCompositeTreeViewDU} from "../../../../src/viewDU/listComposite";

const uint64NumInfType = new UintNumberType(8, {clipInfinity: true});
const containerUintsType = new ContainerType(
Expand Down Expand Up @@ -196,20 +197,23 @@ describe("ListCompositeType.sliceTo", () => {
});

describe("ListCompositeType.sliceFrom", () => {
it("Slice List from multiple length", () => {
const listType = new ListCompositeType(ssz.Root, 1024);
const listLength = 16;
const list = Array.from({length: listLength}, (_, i) => Buffer.alloc(32, i));
const listView = listType.toViewDU(list);
const listType = new ListCompositeType(ssz.Root, 1024);
const listLength = 16;
const list = Array.from({length: listLength}, (_, i) => Buffer.alloc(32, i));
let listView: ListCompositeTreeViewDU<typeof ssz.Root>;
beforeEach(() => {
listView = listType.toViewDU(list);
});

for (let i = -(listLength + 1); i < listLength + 1; i++) {
for (let i = -(listLength + 1); i < listLength + 1; i++) {
it(`Slice List from list length ${listLength}`, () => {
// compare list.slice(i) to listView.sliceFrom(i), they should be equivalent
const slicedList = list.slice(i);
const slicedListView = listView.sliceFrom(i);

expect(slicedListView.length).to.equal(slicedList.length);
expect(toHexString(slicedListView.serialize())).to.equal(toHexString(listType.serialize(slicedList)));
expect(toHexString(slicedListView.hashTreeRoot())).to.equal(toHexString(listType.hashTreeRoot(slicedList)));
}
});
});
}
});

0 comments on commit 4ca1d6f

Please sign in to comment.