Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add coercion utils #38

Merged
merged 4 commits into from Oct 5, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/__fixtures__/coercions.ts
@@ -0,0 +1,22 @@
import type { Hex } from '../hex';

export const POSITIVE_INTEGERS = [0, 1, 10, 100, 1000, 123456789, 2147483647];
export const NEGATIVE_INTEGERS = [
-1, -10, -100, -1000, -123456789, -2147483647,
];
export const DECIMAL_NUMBERS = [
1.1, 1.123456789, 1.123456789123456789, -1.1, -1.123456789,
-1.123456789123456789,
];

export const HEX_STRINGS: Hex[] = [
'0x',
'0x00',
'0x1a',
'0x2b',
'0x3c',
'0xff',
'0xff00ff',
'0x1234567890abcdef',
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
];
2 changes: 2 additions & 0 deletions src/__fixtures__/index.ts
@@ -1 +1,3 @@
export * from './bytes';
export * from './coercions';
export * from './json';
10 changes: 9 additions & 1 deletion src/bytes.test.ts
Expand Up @@ -70,6 +70,10 @@ describe('bytesToHex', () => {
expect(bytesToHex(new Uint8Array([0, 1, 2])).startsWith('0x')).toBe(true);
});

it('returns 0x for an empty byte array', () => {
expect(bytesToHex(new Uint8Array())).toBe('0x');
});

it.each(INVALID_BYTES_FIXTURES)(
'throws an error for invalid byte arrays',
(value) => {
Expand Down Expand Up @@ -191,7 +195,11 @@ describe('hexToBytes', () => {
expect(hexToBytes('abc')).toStrictEqual(new Uint8Array([10, 188]));
});

it.each([true, false, null, undefined, 0, 1, '', '0x', [], {}])(
it('returns an empty byte array for 0x', () => {
expect(hexToBytes('0x')).toStrictEqual(new Uint8Array());
});

it.each([true, false, null, undefined, 0, 1, '', [], {}])(
'throws an error for invalid hex strings',
(value) => {
// @ts-expect-error Invalid type.
Expand Down
21 changes: 18 additions & 3 deletions src/bytes.ts
@@ -1,5 +1,5 @@
import { assert } from './assert';
import { add0x, assertIsHexString, remove0x } from './hex';
import { add0x, assertIsHexString, Hex, remove0x } from './hex';

// '0'.charCodeAt(0) === 48
const HEX_MINIMUM_NUMBER_CHARACTER = 48;
Expand Down Expand Up @@ -74,9 +74,13 @@ export function assertIsBytes(value: unknown): asserts value is Uint8Array {
* @param bytes - The bytes to convert to a hexadecimal string.
* @returns The hexadecimal string.
*/
export function bytesToHex(bytes: Uint8Array): string {
export function bytesToHex(bytes: Uint8Array): Hex {
assertIsBytes(bytes);

if (bytes.length === 0) {
return '0x';
}

const lookupTable = getPrecomputedHexValues();
const hex = new Array(bytes.length);

Expand Down Expand Up @@ -159,17 +163,24 @@ export function bytesToNumber(bytes: Uint8Array): number {
export function bytesToString(bytes: Uint8Array): string {
assertIsBytes(bytes);

return new TextDecoder(undefined).decode(bytes);
return new TextDecoder().decode(bytes);
}

/**
* Convert a hexadecimal string to a `Uint8Array`. The string can optionally be
* prefixed with `0x`. It accepts even and odd length strings.
*
* If the value is "0x", an empty `Uint8Array` is returned.
*
* @param value - The hexadecimal string to convert to bytes.
* @returns The bytes as `Uint8Array`.
*/
export function hexToBytes(value: string): Uint8Array {
// "0x" is often used as empty byte array.
if (value?.toLowerCase?.() === '0x') {
return new Uint8Array();
}

assertIsHexString(value);

// Remove the `0x` prefix if it exists, and pad the string to have an even
Expand Down Expand Up @@ -310,6 +321,10 @@ export function stringToBytes(value: string): Uint8Array {
* Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,
* a `bigint`, a `number`, or a `string`.
*
* This will attempt to guess the type of the value based on its type and
* contents. For more control over the conversion, use the more specific
* conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.
*
* If the value is a `string`, and it is prefixed with `0x`, it will be
* interpreted as a hexadecimal string. Otherwise, it will be interpreted as a
* UTF-8 string. To convert a hexadecimal string to bytes without interpreting
Expand Down
151 changes: 151 additions & 0 deletions src/coercers.test.ts
@@ -0,0 +1,151 @@
import {
DECIMAL_NUMBERS,
HEX_STRINGS,
NEGATIVE_INTEGERS,
POSITIVE_INTEGERS,
} from './__fixtures__';
import { createBigInt, createBytes, createHex, createNumber } from './coercers';
import { add0x } from './hex';
import { bytesToHex, hexToBytes } from './bytes';

describe('createNumber', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we test that this accepts 0x-prefixed hex strings? And also treats strings that look like numbers as decimals?

Copy link
Member Author

@Mrtenz Mrtenz Oct 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expect(createNumber(add0x(value.toString(16)))).toBe(value);
expect(createNumber(value.toString(10))).toBe(value);

it.each(POSITIVE_INTEGERS)(
'creates a number from a positive number-like value',
(value) => {
expect(createNumber(value)).toBe(value);
expect(createNumber(BigInt(value))).toBe(value);
expect(createNumber(add0x(value.toString(16)))).toBe(value);
expect(createNumber(value.toString(10))).toBe(value);
},
);

it.each(NEGATIVE_INTEGERS)(
'creates a number from a negative number-like value',
(value) => {
expect(createNumber(value)).toBe(value);
expect(createNumber(BigInt(value))).toBe(value);
expect(createNumber(value.toString(10))).toBe(value);
},
);

it.each(DECIMAL_NUMBERS)(
'creates a number from a positive number-like value with decimals',
(value) => {
expect(createNumber(value)).toBe(value);
expect(createNumber(value.toString(10))).toBe(value);
},
);

it('handles -0', () => {
expect(createNumber('-0')).toBe(-0);
expect(createNumber(BigInt('-0'))).toBe(0);
});

it('throws if the result is not finite', () => {
expect(() => createNumber(Infinity)).toThrow(
'Expected a number-like value, got "Infinity".',
);

expect(() => createNumber(-Infinity)).toThrow(
'Expected a number-like value, got "-Infinity".',
);
});

it.each([true, false, null, undefined, NaN, {}, []])(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens with negative zero?

Copy link
Member Author

@Mrtenz Mrtenz Oct 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

console.log(createNumber(-0)); // -0
console.log(createNumber('-0')); // -0
console.log(createNumber(BigInt(-0))); // 0

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think it is worth adding tests for these cases?

Copy link
Member

@ritave ritave Oct 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's literally 1 line change, why not.

But not that important if you want to just merge

'throws if the value is not a number-like value',
(value) => {
// @ts-expect-error Invalid type.
expect(() => createNumber(value)).toThrow(
/Expected a number-like value, got "(.*)"\./u,
);
},
);
});

describe('createBigInt', () => {
Mrtenz marked this conversation as resolved.
Show resolved Hide resolved
it.each(POSITIVE_INTEGERS)(
'creates a bigint from a positive number-like value',
(value) => {
expect(createBigInt(value)).toBe(BigInt(value));
expect(createBigInt(add0x(value.toString(16)))).toBe(BigInt(value));
expect(createBigInt(value.toString(10))).toBe(BigInt(value));
},
);

it.each(NEGATIVE_INTEGERS)(
'creates a bigint from a negative number-like value',
(value) => {
expect(createBigInt(value)).toBe(BigInt(value));
expect(createBigInt(value.toString(10))).toBe(BigInt(value));
},
);

it.each([true, false, null, undefined, NaN, {}, []])(
'throws if the value is not a number-like value',
(value) => {
// @ts-expect-error Invalid type.
expect(() => createBigInt(value)).toThrow(
/Expected a number-like value, got "(.*)"\./u,
);
},
);

it('handles -0', () => {
expect(createBigInt('-0')).toBe(BigInt(0));
expect(createBigInt(-0)).toBe(BigInt(0));
});
});

describe('createHex', () => {
it.each(HEX_STRINGS)(
'creates a hex string from a byte-like value',
(value) => {
const bytes = hexToBytes(value);

expect(createHex(value)).toBe(value);
expect(createHex(bytesToHex(bytes))).toBe(value);
},
);

it.each([true, false, null, undefined, NaN, {}, [], '', '11ff'])(
'throws if the value is not a bytes-like value',
(value) => {
// @ts-expect-error Invalid type.
expect(() => createHex(value)).toThrow(
/Expected a bytes-like value, got "(.*)"\./u,
);
},
);

it('handles empty byte arrays', () => {
expect(createHex('0x')).toBe('0x');
expect(createHex(new Uint8Array())).toBe('0x');
});
});

describe('createBytes', () => {
it.each(HEX_STRINGS)(
'creates a byte array from a byte-like value',
(value) => {
const bytes = hexToBytes(value);

expect(createBytes(value)).toStrictEqual(bytes);
expect(createBytes(bytesToHex(bytes))).toStrictEqual(bytes);
},
);

it.each([true, false, null, undefined, NaN, {}, [], '', '11ff'])(
'throws if the value is not a bytes-like value',
(value) => {
// @ts-expect-error Invalid type.
expect(() => createBytes(value)).toThrow(
/Expected a bytes-like value, got "(.*)"\./u,
);
},
);

it('handles empty byte arrays', () => {
expect(createBytes('0x')).toStrictEqual(new Uint8Array());
expect(createBytes(new Uint8Array())).toStrictEqual(new Uint8Array());
});
});