forked from MetaMask/utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoercers.ts
195 lines (178 loc) · 5.42 KB
/
coercers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import type { Infer } from 'superstruct';
import {
bigint,
coerce,
create,
instance,
number,
string,
StructError,
union,
} from 'superstruct';
import { assert } from './assert';
import { bytesToHex, hexToBytes } from './bytes';
import type { Hex } from './hex';
import { StrictHexStruct } from './hex';
const NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);
const NumberCoercer = coerce(number(), NumberLikeStruct, Number);
const BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);
const BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);
const BytesCoercer = coerce(
instance(Uint8Array),
union([StrictHexStruct]),
hexToBytes,
);
const HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);
export type NumberLike = Infer<typeof NumberLikeStruct>;
export type BytesLike = Infer<typeof BytesLikeStruct>;
/**
* Create a number from a number-like value.
*
* - If the value is a number, it is returned as-is.
* - If the value is a `bigint`, it is converted to a number.
* - If the value is a string, it is interpreted as a decimal number.
* - If the value is a hex string (i.e., it starts with "0x"), it is
* interpreted as a hexadecimal number.
*
* This validates that the value is a number-like value, and that the resulting
* number is not `NaN` or `Infinity`.
*
* @example
* ```typescript
* const value = createNumber('0x010203');
* console.log(value); // 66051
*
* const otherValue = createNumber(123n);
* console.log(otherValue); // 123
* ```
* @param value - The value to create the number from.
* @returns The created number.
* @throws If the value is not a number-like value, or if the resulting number
* is `NaN` or `Infinity`.
*/
export function createNumber(value: NumberLike): number {
try {
const result = create(value, NumberCoercer);
assert(
Number.isFinite(result),
`Expected a number-like value, got "${value}".`,
);
return result;
} catch (error) {
if (error instanceof StructError) {
throw new Error(`Expected a number-like value, got "${value}".`);
}
/* istanbul ignore next */
throw error;
}
}
/**
* Create a `bigint` from a number-like value.
*
* - If the value is a number, it is converted to a `bigint`.
* - If the value is a `bigint`, it is returned as-is.
* - If the value is a string, it is interpreted as a decimal number and
* converted to a `bigint`.
* - If the value is a hex string (i.e., it starts with "0x"), it is
* interpreted as a hexadecimal number and converted to a `bigint`.
*
* @example
* ```typescript
* const value = createBigInt('0x010203');
* console.log(value); // 16909060n
*
* const otherValue = createBigInt(123);
* console.log(otherValue); // 123n
* ```
* @param value - The value to create the bigint from.
* @returns The created bigint.
* @throws If the value is not a number-like value.
*/
export function createBigInt(value: NumberLike): bigint {
try {
// The `BigInt` constructor throws if the value is not a number-like value.
// There is no need to validate the value manually.
return create(value, BigIntCoercer);
} catch (error) {
if (error instanceof StructError) {
throw new Error(
`Expected a number-like value, got "${String(error.value)}".`,
);
}
/* istanbul ignore next */
throw error;
}
}
/**
* Create a byte array from a bytes-like value.
*
* - If the value is a byte array, it is returned as-is.
* - If the value is a hex string (i.e., it starts with "0x"), it is interpreted
* as a hexadecimal number and converted to a byte array.
*
* @example
* ```typescript
* const value = createBytes('0x010203');
* console.log(value); // Uint8Array [ 1, 2, 3 ]
*
* const otherValue = createBytes('0x010203');
* console.log(otherValue); // Uint8Array [ 1, 2, 3 ]
* ```
* @param value - The value to create the byte array from.
* @returns The created byte array.
* @throws If the value is not a bytes-like value.
*/
export function createBytes(value: BytesLike): Uint8Array {
if (typeof value === 'string' && value.toLowerCase() === '0x') {
return new Uint8Array();
}
try {
return create(value, BytesCoercer);
} catch (error) {
if (error instanceof StructError) {
throw new Error(
`Expected a bytes-like value, got "${String(error.value)}".`,
);
}
/* istanbul ignore next */
throw error;
}
}
/**
* Create a hexadecimal string from a bytes-like value.
*
* - If the value is a hex string (i.e., it starts with "0x"), it is returned
* as-is.
* - If the value is a `Uint8Array`, it is converted to a hex string.
*
* @example
* ```typescript
* const value = createHex(new Uint8Array([1, 2, 3]));
* console.log(value); // '0x010203'
*
* const otherValue = createHex('0x010203');
* console.log(otherValue); // '0x010203'
* ```
* @param value - The value to create the hex string from.
* @returns The created hex string.
* @throws If the value is not a bytes-like value.
*/
export function createHex(value: BytesLike): Hex {
if (
(value instanceof Uint8Array && value.length === 0) ||
(typeof value === 'string' && value.toLowerCase() === '0x')
) {
return '0x';
}
try {
return create(value, HexCoercer);
} catch (error) {
if (error instanceof StructError) {
throw new Error(
`Expected a bytes-like value, got "${String(error.value)}".`,
);
}
/* istanbul ignore next */
throw error;
}
}