Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion yarn-project/foundation/src/bigint-buffer/bigint-buffer.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
import { fromHex, toHex } from './index.js';
import { fromHex, toBufferBE, toHex } from './index.js';

describe('bigint-buffer', () => {
describe('toBufferBE', () => {
it('serializes zero to a zeroed buffer of the requested width', () => {
expect(toBufferBE(0n, 32)).toEqual(Buffer.alloc(32));
});

it('big-endian pads small values on the left', () => {
expect(toBufferBE(1n, 4)).toEqual(Buffer.from([0, 0, 0, 1]));
expect(toBufferBE(0x0102n, 4)).toEqual(Buffer.from([0, 0, 1, 2]));
});

it('serializes a value that exactly fills the width', () => {
expect(toBufferBE(0xdeadbeefn, 4)).toEqual(Buffer.from('deadbeef', 'hex'));
});

it('throws on negative values', () => {
expect(() => toBufferBE(-1n, 32)).toThrow('negative');
});
});

describe('toHex', () => {
it('does not pad even length', () => {
expect(toHex(16n)).toEqual('0x10');
Expand Down
7 changes: 6 additions & 1 deletion yarn-project/foundation/src/bigint-buffer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,14 @@ export function toBufferLE(num: bigint, width: number): Buffer {
* @returns A big-endian buffer representation of num.
*/
export function toBufferBE(num: bigint, width: number): Buffer {
if (num < BigInt(0)) {
if (num < 0n) {
throw new Error(`Cannot convert negative bigint ${num.toString()} to buffer with toBufferBE.`);
}
// The values serialized in the hot paths are overwhelmingly zero (field elements are mostly
// zero-padding in protocol structs), and the hex round-trip is wasteful for them.
if (num === 0n) {
return Buffer.alloc(width);
}
const hex = num.toString(16);
const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
if (buffer.length > width) {
Expand Down
Loading