Skip to content

Commit

Permalink
fix: don't use spread operator when encoding vec (#561)
Browse files Browse the repository at this point in the history
* fix: don't use spread operator when encoding vec

* use pipe to avoid quadratic concat
  • Loading branch information
chenyan-dfinity committed Apr 20, 2022
1 parent 2d15437 commit 4dae0c9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/candid/src/idl.test.ts
Expand Up @@ -160,6 +160,7 @@ test('IDL encoding (array)', () => {
'4449444c016d7c01000400010203',
'Array of Ints',
);
IDL.encode([IDL.Vec(IDL.Nat16)], [new Array(200000).fill(42)]);
expect(() => IDL.encode([IDL.Vec(IDL.Int)], [BigInt(0)])).toThrow(/Invalid vec int argument/);
expect(() => IDL.encode([IDL.Vec(IDL.Int)], [['fail']])).toThrow(/Invalid vec int argument/);
});
Expand Down
9 changes: 7 additions & 2 deletions packages/candid/src/idl.ts
Expand Up @@ -750,8 +750,13 @@ export class VecClass<T> extends ConstructType<T[]> {
if (this._blobOptimization) {
return concat(len, new Uint8Array(x as unknown as number[]));
}

return concat(len, ...x.map(d => this._type.encodeValue(d)));
const buf = new Pipe(new ArrayBuffer(len.byteLength + x.length), 0);
buf.write(len);
for (const d of x) {
const encoded = this._type.encodeValue(d);
buf.write(new Uint8Array(encoded));
}
return buf.buffer;
}

public _buildTypeTableImpl(typeTable: TypeTable) {
Expand Down

0 comments on commit 4dae0c9

Please sign in to comment.