This repository has been archived by the owner on Dec 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
b32.js
89 lines (68 loc) · 1.81 KB
/
b32.js
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2016-2021 Linus Unnebäck
// from github.com/LinusU/base32-encode/blob/b970e2ee5/index.js
// and github.com/LinusU/base32-decode/blob/fa61c01b/index.js
// and github.com/LinusU/to-data-view/blob/e80ca034/index.js
const ALPHA32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
function toDataView(data) {
if (
data instanceof Int8Array || data instanceof Uint8Array ||
data instanceof Uint8ClampedArray
) {
return new DataView(data.buffer, data.byteOffset, data.byteLength);
}
if (data instanceof ArrayBuffer) {
return new DataView(data);
}
return null;
}
function readChar(chr) {
chr = chr.toUpperCase();
const idx = ALPHA32.indexOf(chr);
if (idx === -1) {
throw new Error("invalid b32 character: " + chr);
}
return idx;
}
function base32(arrbuf, padding) {
const view = toDataView(arrbuf);
if (!view) throw new Error("cannot create data-view from given input");
let bits = 0;
let value = 0;
let output = "";
for (let i = 0; i < view.byteLength; i++) {
value = (value << 8) | view.getUint8(i);
bits += 8;
while (bits >= 5) {
output += ALPHA32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
output += ALPHA32[(value << (5 - bits)) & 31];
}
if (padding) {
while ((output.length % 8) !== 0) {
output += "=";
}
}
return output;
}
function rbase32(input) {
input = input.replace(/=+$/, "");
const length = input.length;
let bits = 0;
let value = 0;
let index = 0;
let output = new Uint8Array((length * 5 / 8) | 0);
for (var i = 0; i < length; i++) {
value = (value << 5) | readChar(input[i]);
bits += 5;
if (bits >= 8) {
output[index++] = (value >>> (bits - 8)) & 255;
bits -= 8;
}
}
return output;
}
export { base32, rbase32 };