Skip to content

Commit

Permalink
chore: support index -1
Browse files Browse the repository at this point in the history
  • Loading branch information
twoeths committed Sep 18, 2023
1 parent 9752eb9 commit b8243dc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
16 changes: 15 additions & 1 deletion packages/ssz/src/viewDU/listBasic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,26 @@ export class ListBasicTreeViewDU<ElementType extends BasicType<unknown>> extends
this.set(index, value);
}

/**
* Returns a new ListBasicTreeViewDU instance with the values from 0 to `index`.
* To achieve it, rebinds the underlying tree zero-ing all nodes right of `chunkIindex`.
* Also set all value right of `index` in the same chunk to 0.
*
* Note: Using index = -1, returns an empty list of length 0.
*/
sliceTo(index: number): this {
if (index < -1) {
throw new Error("Does not support sliceTo() with index less than -1");
}

if (index === -1) {
return this.type.defaultViewDU() as this;
}

// Commit before getting rootNode to ensure all pending data is in the rootNode
this.commit();

// All nodes beyond length are already zero
// Array of length 2: [X,X,0,0], for index >= 1 no action needed
if (index >= this._length - 1) {
return this;
}
Expand Down
10 changes: 7 additions & 3 deletions packages/ssz/test/unit/byType/listBasic/tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,17 @@ describe("ListBasicType.sliceTo", () => {
const listRoots: string[] = [];
const listSerialized: string[] = [];

for (let i = 0; i < 16; i++) {
listView.push(i);
for (let i = -1; i < 16; i++) {
if (i >= 0) {
listView.push(i);
}
// Javascript arrays can handle negative indexes (ok for tests)
listSerialized[i] = toHexString(listView.serialize());
listRoots[i] = toHexString(listView.hashTreeRoot());
}

for (let i = 0; i < 16; i++) {
// Start at -1 to test the empty case.
for (let i = -1; i < 16; i++) {
const listSlice = listView.sliceTo(i);
expect(listSlice.length).to.equal(i + 1, `Wrong length at .sliceTo(${i})`);
expect(toHexString(listSlice.serialize())).equals(listSerialized[i], `Wrong serialize at .sliceTo(${i})`);
Expand Down

0 comments on commit b8243dc

Please sign in to comment.