bufferbase 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -63
- package/dist/cjs/bases.d.ts +152 -45
- package/dist/cjs/bases.d.ts.map +1 -1
- package/dist/cjs/bases.js +90 -77
- package/dist/cjs/bases.js.map +1 -1
- package/dist/cjs/bufferbase.d.ts +21 -27
- package/dist/cjs/bufferbase.d.ts.map +1 -1
- package/dist/cjs/bufferbase.js +21 -31
- package/dist/cjs/bufferbase.js.map +1 -1
- package/dist/cjs/codec-base.d.ts +56 -0
- package/dist/cjs/codec-base.d.ts.map +1 -0
- package/dist/cjs/codec-base.js +132 -0
- package/dist/cjs/codec-base.js.map +1 -0
- package/dist/cjs/codec-block.d.ts +47 -0
- package/dist/cjs/codec-block.d.ts.map +1 -0
- package/dist/cjs/codec-block.js +213 -0
- package/dist/cjs/codec-block.js.map +1 -0
- package/dist/cjs/codec-block85.d.ts +56 -0
- package/dist/cjs/codec-block85.d.ts.map +1 -0
- package/dist/cjs/codec-block85.js +271 -0
- package/dist/cjs/codec-block85.js.map +1 -0
- package/dist/cjs/codec-radix.d.ts +46 -0
- package/dist/cjs/codec-radix.d.ts.map +1 -0
- package/dist/cjs/codec-radix.js +181 -0
- package/dist/cjs/codec-radix.js.map +1 -0
- package/dist/cjs/codec.d.ts +25 -111
- package/dist/cjs/codec.d.ts.map +1 -1
- package/dist/cjs/codec.js +50 -228
- package/dist/cjs/codec.js.map +1 -1
- package/dist/cjs/codecs.d.ts +8 -59
- package/dist/cjs/codecs.d.ts.map +1 -1
- package/dist/cjs/codecs.js +6 -79
- package/dist/cjs/codecs.js.map +1 -1
- package/dist/cjs/errors.d.ts +65 -48
- package/dist/cjs/errors.d.ts.map +1 -1
- package/dist/cjs/errors.js +89 -51
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/example.js +44 -21
- package/dist/cjs/example.js.map +1 -1
- package/dist/cjs/functions.d.ts +27 -31
- package/dist/cjs/functions.d.ts.map +1 -1
- package/dist/cjs/functions.js +25 -47
- package/dist/cjs/functions.js.map +1 -1
- package/dist/cjs/index.d.ts +7 -5
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +17 -7
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/package.json +13 -7
- package/dist/cjs/types.d.ts +108 -71
- package/dist/cjs/types.d.ts.map +1 -1
- package/dist/esm/bases.d.ts +152 -45
- package/dist/esm/bases.d.ts.map +1 -1
- package/dist/esm/bases.js +88 -75
- package/dist/esm/bases.js.map +1 -1
- package/dist/esm/bufferbase.d.ts +21 -27
- package/dist/esm/bufferbase.d.ts.map +1 -1
- package/dist/esm/bufferbase.js +18 -30
- package/dist/esm/bufferbase.js.map +1 -1
- package/dist/esm/codec-base.d.ts +56 -0
- package/dist/esm/codec-base.d.ts.map +1 -0
- package/dist/esm/codec-base.js +127 -0
- package/dist/esm/codec-base.js.map +1 -0
- package/dist/esm/codec-block.d.ts +47 -0
- package/dist/esm/codec-block.d.ts.map +1 -0
- package/dist/esm/codec-block.js +209 -0
- package/dist/esm/codec-block.js.map +1 -0
- package/dist/esm/codec-block85.d.ts +56 -0
- package/dist/esm/codec-block85.d.ts.map +1 -0
- package/dist/esm/codec-block85.js +267 -0
- package/dist/esm/codec-block85.js.map +1 -0
- package/dist/esm/codec-radix.d.ts +46 -0
- package/dist/esm/codec-radix.d.ts.map +1 -0
- package/dist/esm/codec-radix.js +177 -0
- package/dist/esm/codec-radix.js.map +1 -0
- package/dist/esm/codec.d.ts +25 -111
- package/dist/esm/codec.d.ts.map +1 -1
- package/dist/esm/codec.js +44 -226
- package/dist/esm/codec.js.map +1 -1
- package/dist/esm/codecs.d.ts +8 -59
- package/dist/esm/codecs.d.ts.map +1 -1
- package/dist/esm/codecs.js +7 -80
- package/dist/esm/codecs.js.map +1 -1
- package/dist/esm/errors.d.ts +65 -48
- package/dist/esm/errors.d.ts.map +1 -1
- package/dist/esm/errors.js +83 -50
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/example.js +45 -22
- package/dist/esm/example.js.map +1 -1
- package/dist/esm/functions.d.ts +27 -31
- package/dist/esm/functions.d.ts.map +1 -1
- package/dist/esm/functions.js +26 -48
- package/dist/esm/functions.js.map +1 -1
- package/dist/esm/index.d.ts +7 -5
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +6 -6
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/package.json +13 -7
- package/dist/esm/types.d.ts +108 -71
- package/dist/esm/types.d.ts.map +1 -1
- package/package.json +13 -7
- package/src/algorithms.test.ts +442 -0
- package/src/bases.ts +98 -76
- package/src/bufferbase.ts +26 -36
- package/src/codec-base.ts +181 -0
- package/src/codec-block.ts +258 -0
- package/src/codec-block85.ts +315 -0
- package/src/codec-radix.ts +206 -0
- package/src/codec.test.ts +17 -9
- package/src/codec.ts +48 -247
- package/src/codecs.ts +11 -105
- package/src/errors.ts +90 -50
- package/src/example.ts +47 -22
- package/src/functions.ts +34 -54
- package/src/index.ts +27 -7
- package/src/types.ts +113 -86
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import type { Block85Spec, BufferLike, DecodeOptions } from './types.js';
|
|
3
|
+
import { BaseCodec, toBuffer } from './codec-base.js';
|
|
4
|
+
import {
|
|
5
|
+
BufferSizeError,
|
|
6
|
+
InvalidCharacterError,
|
|
7
|
+
InvalidCodecError,
|
|
8
|
+
InvalidLengthError,
|
|
9
|
+
NonCanonicalError,
|
|
10
|
+
ValueRangeError,
|
|
11
|
+
} from './errors.js';
|
|
12
|
+
|
|
13
|
+
const BYTES_PER_BLOCK = 4;
|
|
14
|
+
const CHARS_PER_BLOCK = 5;
|
|
15
|
+
const BLOCK_LIMIT = 0x1_00_00_00_00;
|
|
16
|
+
const ZERO_CHAR = 'z';
|
|
17
|
+
const ZERO_CODE = ZERO_CHAR.charCodeAt(0);
|
|
18
|
+
const SPACE_CHAR = 'y';
|
|
19
|
+
const SPACE_CODE = SPACE_CHAR.charCodeAt(0);
|
|
20
|
+
const SPACE_BLOCK = 0x20202020;
|
|
21
|
+
const OPEN = '<~';
|
|
22
|
+
const CLOSE = '~>';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Converts each 4-byte block to 5 characters, the Ascii85 and Z85 family.
|
|
26
|
+
*
|
|
27
|
+
* 85^5 is the smallest power of 85 above 2^32, so five characters are enough
|
|
28
|
+
* for four bytes and the expansion is 25% instead of Base64's 33%.
|
|
29
|
+
*
|
|
30
|
+
* Several mutually incompatible encodings share this algorithm and alphabet,
|
|
31
|
+
* differing only in the shortcuts and framing they add. They are options here
|
|
32
|
+
* rather than separate codecs: the btoa form is `zeroShortcut` plus
|
|
33
|
+
* `spaceShortcut`, and the Adobe form is `zeroShortcut` plus `delimiters`. The
|
|
34
|
+
* default, `zeroShortcut` alone, matches Python's `base64.a85encode`.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* import { Codecs } from 'bufferbase';
|
|
39
|
+
*
|
|
40
|
+
* Codecs.ascii85.encode(Buffer.from('Man ')); // '9jqo^'
|
|
41
|
+
* Codecs.ascii85.encode(Buffer.alloc(4)); // 'z'
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export class Block85Codec extends BaseCodec {
|
|
45
|
+
readonly algorithm = 'block85' as const;
|
|
46
|
+
|
|
47
|
+
private readonly zeroShortcut: boolean;
|
|
48
|
+
private readonly spaceShortcut: boolean;
|
|
49
|
+
private readonly delimiters: boolean;
|
|
50
|
+
private readonly requireFullBlocks: boolean;
|
|
51
|
+
|
|
52
|
+
constructor(spec: Block85Spec) {
|
|
53
|
+
super(spec);
|
|
54
|
+
|
|
55
|
+
if (spec.alphabet.length !== 85) {
|
|
56
|
+
throw new InvalidCodecError(
|
|
57
|
+
`'block85' needs an alphabet of exactly 85 characters, got ${spec.alphabet.length}`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
for (const [enabled, char] of [
|
|
61
|
+
[spec.zeroShortcut, ZERO_CHAR],
|
|
62
|
+
[spec.spaceShortcut, SPACE_CHAR],
|
|
63
|
+
] as const) {
|
|
64
|
+
if (enabled === true && this.valueOf(char) !== undefined) {
|
|
65
|
+
throw new InvalidCodecError(`shortcut character '${char}' is part of the alphabet`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
this.zeroShortcut = spec.zeroShortcut ?? false;
|
|
70
|
+
this.spaceShortcut = spec.spaceShortcut ?? false;
|
|
71
|
+
this.delimiters = spec.delimiters ?? false;
|
|
72
|
+
this.requireFullBlocks = spec.requireFullBlocks ?? false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
encode(input: BufferLike): string {
|
|
76
|
+
const buffer = toBuffer(input);
|
|
77
|
+
if (this.requireFullBlocks && buffer.length % BYTES_PER_BLOCK !== 0) {
|
|
78
|
+
throw new InvalidLengthError(
|
|
79
|
+
buffer.length,
|
|
80
|
+
`this codec encodes whole ${BYTES_PER_BLOCK}-byte blocks only`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const codes = this.codes;
|
|
85
|
+
if (codes === null) {
|
|
86
|
+
return this.encodeAsText(buffer);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const blocks = Math.ceil(buffer.length / BYTES_PER_BLOCK);
|
|
90
|
+
const written = new Uint8Array(blocks * CHARS_PER_BLOCK + OPEN.length + CLOSE.length);
|
|
91
|
+
let at = 0;
|
|
92
|
+
if (this.delimiters) {
|
|
93
|
+
at += this.writeAscii(written, at, OPEN);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Whole blocks, with the five divisions unrolled. Dividing a float by 85
|
|
97
|
+
// and truncating with `>>> 0` is several times quicker than `%` paired
|
|
98
|
+
// with `Math.floor`, because every quotient here still fits in 32 bits.
|
|
99
|
+
const whole = buffer.length - (buffer.length % BYTES_PER_BLOCK);
|
|
100
|
+
for (let from = 0; from < whole; from += BYTES_PER_BLOCK) {
|
|
101
|
+
const value = buffer.readUInt32BE(from);
|
|
102
|
+
if (this.zeroShortcut && value === 0) {
|
|
103
|
+
written[at++] = ZERO_CODE;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (this.spaceShortcut && value === SPACE_BLOCK) {
|
|
107
|
+
written[at++] = SPACE_CODE;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const q1 = (value / 85) >>> 0;
|
|
111
|
+
const q2 = (q1 / 85) >>> 0;
|
|
112
|
+
const q3 = (q2 / 85) >>> 0;
|
|
113
|
+
const q4 = (q3 / 85) >>> 0;
|
|
114
|
+
written[at] = codes[q4];
|
|
115
|
+
written[at + 1] = codes[q3 - q4 * 85];
|
|
116
|
+
written[at + 2] = codes[q2 - q3 * 85];
|
|
117
|
+
written[at + 3] = codes[q1 - q2 * 85];
|
|
118
|
+
written[at + 4] = codes[value - q1 * 85];
|
|
119
|
+
at += CHARS_PER_BLOCK;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The trailing partial block, encoded as `size + 1` characters.
|
|
123
|
+
if (whole < buffer.length) {
|
|
124
|
+
const size = buffer.length - whole;
|
|
125
|
+
let value = 0;
|
|
126
|
+
for (let i = 0; i < BYTES_PER_BLOCK; i++) {
|
|
127
|
+
value = value * 256 + (whole + i < buffer.length ? buffer[whole + i] : 0);
|
|
128
|
+
}
|
|
129
|
+
const digits = new Uint8Array(CHARS_PER_BLOCK);
|
|
130
|
+
for (let i = CHARS_PER_BLOCK - 1; i >= 0; i--) {
|
|
131
|
+
const quotient = (value / 85) >>> 0;
|
|
132
|
+
digits[i] = codes[value - quotient * 85];
|
|
133
|
+
value = quotient;
|
|
134
|
+
}
|
|
135
|
+
for (let i = 0; i <= size; i++) {
|
|
136
|
+
written[at++] = digits[i];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (this.delimiters) {
|
|
140
|
+
at += this.writeAscii(written, at, CLOSE);
|
|
141
|
+
}
|
|
142
|
+
return this.textFrom(written, at);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
decode(encoded: string, options?: DecodeOptions): Buffer {
|
|
146
|
+
const bytes = this.readBytes(this.undelimit(this.strip(encoded)));
|
|
147
|
+
const size = options?.size;
|
|
148
|
+
if (size !== undefined && bytes.length !== size) {
|
|
149
|
+
throw new BufferSizeError(bytes.length, size);
|
|
150
|
+
}
|
|
151
|
+
return Buffer.from(bytes);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
validate(input: string): boolean {
|
|
155
|
+
try {
|
|
156
|
+
this.readBytes(this.undelimit(this.strip(input)));
|
|
157
|
+
return true;
|
|
158
|
+
} catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Writes an ASCII marker, returning how many bytes it took. */
|
|
164
|
+
private writeAscii(into: Uint8Array, at: number, text: string): number {
|
|
165
|
+
for (let i = 0; i < text.length; i++) {
|
|
166
|
+
into[at + i] = text.charCodeAt(i);
|
|
167
|
+
}
|
|
168
|
+
return text.length;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The character-by-character path, for an alphabet that is not single-byte. */
|
|
172
|
+
private encodeAsText(buffer: Uint8Array): string {
|
|
173
|
+
let out = '';
|
|
174
|
+
for (let at = 0; at < buffer.length; at += BYTES_PER_BLOCK) {
|
|
175
|
+
const size = Math.min(BYTES_PER_BLOCK, buffer.length - at);
|
|
176
|
+
let value = 0;
|
|
177
|
+
for (let i = 0; i < BYTES_PER_BLOCK; i++) {
|
|
178
|
+
value = value * 256 + (at + i < buffer.length ? buffer[at + i] : 0);
|
|
179
|
+
}
|
|
180
|
+
if (size === BYTES_PER_BLOCK && this.zeroShortcut && value === 0) {
|
|
181
|
+
out += ZERO_CHAR;
|
|
182
|
+
} else if (size === BYTES_PER_BLOCK && this.spaceShortcut && value === SPACE_BLOCK) {
|
|
183
|
+
out += SPACE_CHAR;
|
|
184
|
+
} else {
|
|
185
|
+
out += this.digitsOf(value).slice(0, size === BYTES_PER_BLOCK ? CHARS_PER_BLOCK : size + 1);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return this.delimiters ? OPEN + out + CLOSE : out;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Renders a block value as its five characters, most significant first. */
|
|
192
|
+
private digitsOf(value: number): string {
|
|
193
|
+
let rest = value;
|
|
194
|
+
const digits: string[] = [];
|
|
195
|
+
for (let i = 0; i < CHARS_PER_BLOCK; i++) {
|
|
196
|
+
digits.unshift(this.chars[rest % 85]);
|
|
197
|
+
rest = Math.floor(rest / 85);
|
|
198
|
+
}
|
|
199
|
+
return digits.join('');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Removes the framing, rejecting input that is missing or misplacing it. */
|
|
203
|
+
private undelimit(input: string): string {
|
|
204
|
+
if (!this.delimiters) {
|
|
205
|
+
return input;
|
|
206
|
+
}
|
|
207
|
+
if (!input.startsWith(OPEN) || !input.endsWith(CLOSE) || input.length < OPEN.length + CLOSE.length) {
|
|
208
|
+
throw new InvalidCharacterError();
|
|
209
|
+
}
|
|
210
|
+
return input.slice(OPEN.length, input.length - CLOSE.length);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Decodes the body. Everything `decode` can reject other than
|
|
215
|
+
* `DecodeOptions.size` is checked here, so `validate` and `decode` agree.
|
|
216
|
+
*/
|
|
217
|
+
private readBytes(body: string): number[] {
|
|
218
|
+
const bytes: number[] = [];
|
|
219
|
+
let held = 0;
|
|
220
|
+
let value = 0;
|
|
221
|
+
let groupAt = 0;
|
|
222
|
+
|
|
223
|
+
for (let i = 0; i < body.length; i++) {
|
|
224
|
+
if (held === 0) {
|
|
225
|
+
const code = body.charCodeAt(i);
|
|
226
|
+
if (this.zeroShortcut && code === ZERO_CODE) {
|
|
227
|
+
bytes.push(0, 0, 0, 0);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (this.spaceShortcut && code === SPACE_CODE) {
|
|
231
|
+
bytes.push(0x20, 0x20, 0x20, 0x20);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
groupAt = i;
|
|
235
|
+
}
|
|
236
|
+
const digit = this.valueAt(body, i);
|
|
237
|
+
if (digit < 0) {
|
|
238
|
+
throw new InvalidCharacterError(body[i]);
|
|
239
|
+
}
|
|
240
|
+
value = value * 85 + digit;
|
|
241
|
+
held++;
|
|
242
|
+
if (held === CHARS_PER_BLOCK) {
|
|
243
|
+
if (value >= BLOCK_LIMIT) {
|
|
244
|
+
throw new ValueRangeError(body.slice(groupAt, i + 1));
|
|
245
|
+
}
|
|
246
|
+
bytes.push(
|
|
247
|
+
(value / 0x1000000) & 0xff,
|
|
248
|
+
(value / 0x10000) & 0xff,
|
|
249
|
+
(value / 0x100) & 0xff,
|
|
250
|
+
value & 0xff,
|
|
251
|
+
);
|
|
252
|
+
held = 0;
|
|
253
|
+
value = 0;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (held > 0) {
|
|
258
|
+
this.readPartial(body.slice(groupAt), bytes);
|
|
259
|
+
}
|
|
260
|
+
return bytes;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Decodes a trailing group of 2..4 characters into 1..3 bytes.
|
|
265
|
+
*
|
|
266
|
+
* The group is padded to a whole block with the highest digit so that the
|
|
267
|
+
* missing low-order bytes cannot round the value down, then the bytes the
|
|
268
|
+
* group actually carries are kept.
|
|
269
|
+
*/
|
|
270
|
+
private readPartial(group: string, bytes: number[]): void {
|
|
271
|
+
if (this.requireFullBlocks) {
|
|
272
|
+
throw new InvalidLengthError(
|
|
273
|
+
group.length,
|
|
274
|
+
`this codec decodes whole ${CHARS_PER_BLOCK}-character blocks only`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
if (group.length < 2) {
|
|
278
|
+
throw new InvalidLengthError(
|
|
279
|
+
group.length,
|
|
280
|
+
`a trailing group needs at least 2 characters to carry a byte`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const padded = group.padEnd(CHARS_PER_BLOCK, this.chars[84]);
|
|
285
|
+
let value = 0;
|
|
286
|
+
for (let i = 0; i < CHARS_PER_BLOCK; i++) {
|
|
287
|
+
const digit = this.valueAt(padded, i);
|
|
288
|
+
if (digit < 0) {
|
|
289
|
+
throw new InvalidCharacterError(padded[i]);
|
|
290
|
+
}
|
|
291
|
+
value = value * 85 + digit;
|
|
292
|
+
}
|
|
293
|
+
if (value >= BLOCK_LIMIT) {
|
|
294
|
+
throw new ValueRangeError(group);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const carried = group.length - 1;
|
|
298
|
+
const block: number[] = [];
|
|
299
|
+
for (let shift = 24; shift >= 0; shift -= 8) {
|
|
300
|
+
block.push((value / 2 ** shift) & 0xff);
|
|
301
|
+
}
|
|
302
|
+
const kept = block.slice(0, carried);
|
|
303
|
+
|
|
304
|
+
if (this.strict) {
|
|
305
|
+
let padded = 0;
|
|
306
|
+
for (let i = 0; i < BYTES_PER_BLOCK; i++) {
|
|
307
|
+
padded = padded * 256 + (i < carried ? kept[i] : 0);
|
|
308
|
+
}
|
|
309
|
+
if (this.digitsOf(padded).slice(0, group.length) !== group) {
|
|
310
|
+
throw new NonCanonicalError(`'${group}' is not the shortest encoding of its bytes`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
bytes.push(...kept);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import type { BufferLike, DecodeOptions, RadixSpec } from './types.js';
|
|
3
|
+
import { BaseCodec, toBuffer } from './codec-base.js';
|
|
4
|
+
import {
|
|
5
|
+
BufferSizeError,
|
|
6
|
+
CheckSymbolError,
|
|
7
|
+
InvalidCharacterError,
|
|
8
|
+
InvalidCodecError,
|
|
9
|
+
InvalidLengthError,
|
|
10
|
+
} from './errors.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Reads the buffer as one big integer and rewrites it in base
|
|
14
|
+
* `alphabet.length`.
|
|
15
|
+
*
|
|
16
|
+
* This is the Base58 family of encodings. It accepts any alphabet and any
|
|
17
|
+
* input length, but it is not RFC 4648: the output length is not a fixed
|
|
18
|
+
* function of the input length, so it cannot be streamed, and encoding is
|
|
19
|
+
* O(n²) in the input size.
|
|
20
|
+
*
|
|
21
|
+
* Leading zero bytes carry no value in an integer, so they are recorded
|
|
22
|
+
* separately as leading `alphabet[0]` characters.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* import { RadixCodec } from 'bufferbase';
|
|
27
|
+
*
|
|
28
|
+
* const binary = new RadixCodec({ alphabet: '01', algorithm: 'radix' });
|
|
29
|
+
* binary.encode(Uint8Array.of(5)); // '101'
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export class RadixCodec extends BaseCodec {
|
|
33
|
+
readonly algorithm = 'radix' as const;
|
|
34
|
+
|
|
35
|
+
/** Alphabet plus the extra check symbols, or `null` when unchecked. */
|
|
36
|
+
private readonly checkChars: string | null;
|
|
37
|
+
|
|
38
|
+
/** Value of every character a check symbol may be written as. */
|
|
39
|
+
private readonly checkValues: ReadonlyMap<string, number>;
|
|
40
|
+
|
|
41
|
+
constructor(spec: RadixSpec) {
|
|
42
|
+
super(spec);
|
|
43
|
+
|
|
44
|
+
const extra = spec.checkSymbols;
|
|
45
|
+
if (extra === undefined || extra === '') {
|
|
46
|
+
this.checkChars = null;
|
|
47
|
+
this.checkValues = new Map();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const combined = spec.alphabet + extra;
|
|
51
|
+
if (new Set(combined).size !== combined.length) {
|
|
52
|
+
throw new InvalidCodecError('checkSymbols repeat a character of the alphabet');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The symbol is matched by value, so that a case-insensitive codec accepts
|
|
56
|
+
// it in either case just as it does the rest of the string.
|
|
57
|
+
const values = new Map<string, number>();
|
|
58
|
+
for (let i = 0; i < combined.length; i++) {
|
|
59
|
+
const char = combined[i];
|
|
60
|
+
values.set(char, i);
|
|
61
|
+
if (spec.caseInsensitive === true) {
|
|
62
|
+
values.set(char.toLowerCase(), i);
|
|
63
|
+
values.set(char.toUpperCase(), i);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
this.checkChars = combined;
|
|
67
|
+
this.checkValues = values;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
encode(input: BufferLike): string {
|
|
71
|
+
const buffer = toBuffer(input);
|
|
72
|
+
const base = this.chars.length;
|
|
73
|
+
const digits: number[] = [];
|
|
74
|
+
|
|
75
|
+
for (const byte of buffer) {
|
|
76
|
+
let carry = byte;
|
|
77
|
+
for (let i = 0; i < digits.length; i++) {
|
|
78
|
+
carry += digits[i] * 256;
|
|
79
|
+
digits[i] = carry % base;
|
|
80
|
+
carry = Math.floor(carry / base);
|
|
81
|
+
}
|
|
82
|
+
while (carry > 0) {
|
|
83
|
+
digits.push(carry % base);
|
|
84
|
+
carry = Math.floor(carry / base);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (let i = 0; i < buffer.length && buffer[i] === 0; i++) {
|
|
89
|
+
digits.push(0);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let out = '';
|
|
93
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
94
|
+
out += this.chars[digits[i]];
|
|
95
|
+
}
|
|
96
|
+
if (this.checkChars !== null) {
|
|
97
|
+
out += this.checkChars[this.remainderOf(buffer, this.checkChars.length)];
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
decode(encoded: string, options?: DecodeOptions): Buffer {
|
|
103
|
+
const bytes = this.read(this.strip(encoded));
|
|
104
|
+
|
|
105
|
+
const size = options?.size;
|
|
106
|
+
if (size === undefined) {
|
|
107
|
+
return Buffer.from(bytes);
|
|
108
|
+
}
|
|
109
|
+
if (bytes.length > size) {
|
|
110
|
+
throw new BufferSizeError(bytes.length, size);
|
|
111
|
+
}
|
|
112
|
+
const padded = Buffer.alloc(size);
|
|
113
|
+
Buffer.from(bytes).copy(padded, size - bytes.length);
|
|
114
|
+
return padded;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
validate(input: string): boolean {
|
|
118
|
+
const stripped = this.strip(input);
|
|
119
|
+
if (this.checkChars === null) {
|
|
120
|
+
// Every string over the alphabet decodes, so the characters settle it.
|
|
121
|
+
for (let i = 0; i < stripped.length; i++) {
|
|
122
|
+
if (this.valueAt(stripped, i) < 0) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
this.read(stripped);
|
|
130
|
+
return true;
|
|
131
|
+
} catch {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Decodes the body, verifying the check symbol when the codec carries one.
|
|
138
|
+
*
|
|
139
|
+
* Everything `decode` can reject other than `DecodeOptions.size` is checked
|
|
140
|
+
* here, so `validate` and `decode` always agree.
|
|
141
|
+
*/
|
|
142
|
+
private read(input: string): number[] {
|
|
143
|
+
let body = input;
|
|
144
|
+
|
|
145
|
+
if (this.checkChars !== null) {
|
|
146
|
+
if (body.length === 0) {
|
|
147
|
+
throw new InvalidLengthError(0, 'a checked encoding always carries a check symbol');
|
|
148
|
+
}
|
|
149
|
+
const found = body.slice(-1);
|
|
150
|
+
body = body.slice(0, -1);
|
|
151
|
+
const bytes = this.toBytes(body);
|
|
152
|
+
const expected = this.remainderOf(bytes, this.checkChars.length);
|
|
153
|
+
if (this.checkValues.get(found) !== expected) {
|
|
154
|
+
throw new CheckSymbolError(found, this.checkChars[expected]);
|
|
155
|
+
}
|
|
156
|
+
return bytes;
|
|
157
|
+
}
|
|
158
|
+
return this.toBytes(input);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Rewrites the digits of `body` as bytes, most significant first. */
|
|
162
|
+
private toBytes(body: string): number[] {
|
|
163
|
+
const base = this.chars.length;
|
|
164
|
+
const bytes: number[] = [];
|
|
165
|
+
let leadingZeros = 0;
|
|
166
|
+
let stillLeading = true;
|
|
167
|
+
|
|
168
|
+
for (let at = 0; at < body.length; at++) {
|
|
169
|
+
const value = this.valueAt(body, at);
|
|
170
|
+
if (value < 0) {
|
|
171
|
+
throw new InvalidCharacterError(body[at]);
|
|
172
|
+
}
|
|
173
|
+
if (stillLeading && value === 0) {
|
|
174
|
+
leadingZeros++;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
stillLeading = false;
|
|
178
|
+
|
|
179
|
+
let carry = value;
|
|
180
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
181
|
+
carry += bytes[i] * base;
|
|
182
|
+
bytes[i] = carry % 256;
|
|
183
|
+
carry = Math.floor(carry / 256);
|
|
184
|
+
}
|
|
185
|
+
while (carry > 0) {
|
|
186
|
+
bytes.push(carry % 256);
|
|
187
|
+
carry = Math.floor(carry / 256);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
for (let i = 0; i < leadingZeros; i++) {
|
|
192
|
+
bytes.push(0);
|
|
193
|
+
}
|
|
194
|
+
bytes.reverse();
|
|
195
|
+
return bytes;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The value the bytes denote, modulo `divisor`. */
|
|
199
|
+
private remainderOf(bytes: Iterable<number>, divisor: number): number {
|
|
200
|
+
let remainder = 0;
|
|
201
|
+
for (const byte of bytes) {
|
|
202
|
+
remainder = (remainder * 256 + byte) % divisor;
|
|
203
|
+
}
|
|
204
|
+
return remainder;
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/codec.test.ts
CHANGED
|
@@ -23,12 +23,17 @@ describe('Function API', () => {
|
|
|
23
23
|
});
|
|
24
24
|
|
|
25
25
|
test('encode/decode with custom character set', () => {
|
|
26
|
+
const spec = { alphabet: Chars.Base58, algorithm: 'radix' } as const;
|
|
26
27
|
const buffer = Buffer.from('Test', 'utf8');
|
|
27
|
-
const encoded = encode(buffer,
|
|
28
|
-
const decoded = decode(encoded,
|
|
28
|
+
const encoded = encode(buffer, spec);
|
|
29
|
+
const decoded = decode(encoded, spec);
|
|
29
30
|
expect(decoded.toString('utf8')).toBe('Test');
|
|
30
31
|
});
|
|
31
32
|
|
|
33
|
+
test('a bare alphabet is no longer accepted as a base', () => {
|
|
34
|
+
expect(() => encode(Buffer.from('Test'), Chars.Base58 as never)).toThrow(UnknownBaseError);
|
|
35
|
+
});
|
|
36
|
+
|
|
32
37
|
test('convert between bases', () => {
|
|
33
38
|
const buffer = Buffer.from('Hello', 'utf8');
|
|
34
39
|
const base58Encoded = encode(buffer, 'base58');
|
|
@@ -183,17 +188,20 @@ describe('All character sets', () => {
|
|
|
183
188
|
'base58',
|
|
184
189
|
'base64',
|
|
185
190
|
'base64url',
|
|
191
|
+
'base32hex',
|
|
186
192
|
'ascii85',
|
|
187
|
-
'base85',
|
|
188
193
|
'z85',
|
|
189
194
|
] as const;
|
|
190
195
|
|
|
196
|
+
// 12 bytes, so that z85 (whole 4-byte blocks only) is covered by the loop.
|
|
197
|
+
const payload = 'Hello, World';
|
|
198
|
+
|
|
191
199
|
for (const base of baseNames) {
|
|
192
200
|
test(`${base} encode/decode round-trip`, () => {
|
|
193
|
-
const buffer = Buffer.from(
|
|
201
|
+
const buffer = Buffer.from(payload, 'utf8');
|
|
194
202
|
const encoded = encode(buffer, base);
|
|
195
203
|
const decoded = decode(encoded, base);
|
|
196
|
-
expect(decoded.toString('utf8')).toBe(
|
|
204
|
+
expect(decoded.toString('utf8')).toBe(payload);
|
|
197
205
|
});
|
|
198
206
|
}
|
|
199
207
|
});
|
|
@@ -258,13 +266,13 @@ describe('Uint8Array support', () => {
|
|
|
258
266
|
});
|
|
259
267
|
|
|
260
268
|
test('encode Uint8Array across all base encodings', () => {
|
|
261
|
-
const uint8Array = new Uint8Array([1, 2, 3, 4
|
|
262
|
-
const buffer = Buffer.from([1, 2, 3, 4
|
|
269
|
+
const uint8Array = new Uint8Array([1, 2, 3, 4]);
|
|
270
|
+
const buffer = Buffer.from([1, 2, 3, 4]);
|
|
263
271
|
|
|
264
272
|
const baseNames = [
|
|
265
|
-
'decimal', 'base16', 'hex', 'base32', 'base32crockford',
|
|
273
|
+
'decimal', 'base16', 'hex', 'base32', 'base32hex', 'base32crockford',
|
|
266
274
|
'base36', 'base52', 'base58', 'base64', 'base64url',
|
|
267
|
-
'ascii85', '
|
|
275
|
+
'ascii85', 'z85',
|
|
268
276
|
] as const;
|
|
269
277
|
|
|
270
278
|
for (const base of baseNames) {
|