Skip to content

Commit af448ec

Browse files
committed
refactor: simplify Uint8Array checks
1 parent 8cab29a commit af448ec

File tree

4 files changed

+9
-8
lines changed

4 files changed

+9
-8
lines changed

base58.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { typedView } from './array.js'
2-
import { assertUint8 } from './assert.js'
3-
import { E_STRING } from './fallback/_utils.js'
2+
import { assertU8, E_STRING } from './fallback/_utils.js'
43
import { nativeDecoder, nativeEncoder, isHermes } from './fallback/platform.js'
54
import { encodeAscii, decodeAscii } from './fallback/latin1.js'
65

@@ -24,7 +23,7 @@ const E_CHAR = 'Invalid character in base58 input'
2423
const shouldUseBigIntFrom = isHermes // faster only on Hermes, numbers path beats it on normal engines
2524

2625
function toBase58core(arr, alphabet, codes) {
27-
assertUint8(arr)
26+
assertU8(arr)
2827
const length = arr.length
2928
if (length === 0) return ''
3029

fallback/_utils.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ export function assert(condition, msg) {
66
if (!condition) throw new Error(msg)
77
}
88

9+
export function assertU8(arg) {
10+
if (!(arg instanceof Uint8Array)) throw new TypeError('Expected an Uint8Array')
11+
}
12+
913
// On arrays in heap (<= 64) it's cheaper to copy into a pooled buffer than lazy-create the ArrayBuffer storage
1014
export const toBuf = (x) =>
1115
x.byteLength <= 64 && x.BYTES_PER_ELEMENT === 1

fallback/hex.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { assertUint8 } from '../assert.js'
21
import { E_STRING } from './_utils.js'
32
import { nativeDecoder, nativeEncoder, decode2string } from './platform.js'
43
import { encodeAscii, decodeAscii } from './latin1.js'
@@ -12,9 +11,8 @@ const allowed = '0123456789ABCDEFabcdef'
1211

1312
export const E_HEX = 'Input is not a hex string'
1413

14+
// Expects a checked Uint8Array
1515
export function toHex(arr) {
16-
assertUint8(arr)
17-
1816
if (!hexArray) hexArray = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'))
1917
const length = arr.length // this helps Hermes
2018

hex.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { assertUint8 } from './assert.js'
21
import { typedView } from './array.js'
2+
import { assertU8 } from './fallback/_utils.js'
33
import * as js from './fallback/hex.js'
44

55
const { toHex: webHex } = Uint8Array.prototype // Modern engines have this
66

77
export function toHex(arr) {
8-
assertUint8(arr)
8+
assertU8(arr)
99
if (arr.length === 0) return ''
1010
if (webHex && arr.toHex === webHex) return arr.toHex()
1111
return js.toHex(arr)

0 commit comments

Comments
 (0)