Skip to content

Commit a17368b

Browse files
authored
Merge pull request #4 from liamdon/browserCompatible
Make browser-compatible, reduce allocations during encoding and decoding
2 parents 3983794 + 6af2851 commit a17368b

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

package-lock.json

+2-5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/base32.ts

+11-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
const alphabet = '0123456789abcdefghjkmnpqrstvwxyz'.split('').map(char => char.charCodeAt(0))
22

3+
// Reuse a single charCode buffer
4+
// for encoding and decoding to avoid allocations.
5+
const charCodes = new Uint8Array(26)
6+
37
export function encode(src: Uint8Array | number[] | Buffer): string {
4-
if (src instanceof Buffer) {
8+
if (!Array.isArray(src)) {
59
src = Array.from(src)
610
}
7-
const buffer: Buffer = Buffer.alloc(26, '')
11+
12+
src = src instanceof Uint8Array || Array.isArray(src) ? src : Array.from(src)
13+
14+
const buffer = charCodes
815

916
// 10 byte timestamp
1017
buffer[0] = alphabet[(src[0] & 224) >> 5]
@@ -36,7 +43,7 @@ export function encode(src: Uint8Array | number[] | Buffer): string {
3643
buffer[24] = alphabet[((src[14] & 3) << 3) | ((src[15] & 224) >> 5)]
3744
buffer[25] = alphabet[src[15] & 31]
3845

39-
return buffer.toString('binary')
46+
return String.fromCharCode(...buffer)
4047
}
4148

4249
// Byte to index table for O(1) lookups when unmarshaling.
@@ -74,7 +81,7 @@ export function decode(s: string): Uint8Array {
7481
throw new Error('Invalid length')
7582
}
7683

77-
const v: Uint8Array = new Uint8Array(s.length)
84+
const v = charCodes
7885
for (let i = 0; i < s.length; i++) {
7986
v[i] = s.charCodeAt(i)
8087
}

0 commit comments

Comments
 (0)