bufferbase 1.3.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 +186 -17
- package/dist/cjs/bases.d.ts +189 -0
- package/dist/cjs/bases.d.ts.map +1 -0
- package/dist/cjs/bases.js +134 -0
- package/dist/cjs/bases.js.map +1 -0
- package/dist/cjs/bufferbase.d.ts +22 -45
- package/dist/cjs/bufferbase.d.ts.map +1 -1
- package/dist/cjs/bufferbase.js +26 -120
- 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 +38 -0
- package/dist/cjs/codec.d.ts.map +1 -0
- package/dist/cjs/codec.js +69 -0
- package/dist/cjs/codec.js.map +1 -0
- package/dist/cjs/codecs.d.ts +20 -0
- package/dist/cjs/codecs.d.ts.map +1 -0
- package/dist/cjs/codecs.js +19 -0
- package/dist/cjs/codecs.js.map +1 -0
- package/dist/cjs/errors.d.ts +93 -0
- package/dist/cjs/errors.d.ts.map +1 -0
- package/dist/cjs/errors.js +130 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/cjs/example.js +49 -33
- package/dist/cjs/example.js.map +1 -1
- package/dist/cjs/functions.d.ts +58 -0
- package/dist/cjs/functions.d.ts.map +1 -0
- package/dist/cjs/functions.js +71 -0
- package/dist/cjs/functions.js.map +1 -0
- package/dist/cjs/index.d.ts +10 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +35 -4
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/package.json +17 -12
- package/dist/cjs/types.d.ts +144 -0
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/bases.d.ts +189 -0
- package/dist/esm/bases.d.ts.map +1 -0
- package/dist/esm/bases.js +129 -0
- package/dist/esm/bases.js.map +1 -0
- package/dist/esm/bufferbase.d.ts +22 -45
- package/dist/esm/bufferbase.d.ts.map +1 -1
- package/dist/esm/bufferbase.js +21 -115
- 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 +38 -0
- package/dist/esm/codec.d.ts.map +1 -0
- package/dist/esm/codec.js +60 -0
- package/dist/esm/codec.js.map +1 -0
- package/dist/esm/codecs.d.ts +20 -0
- package/dist/esm/codecs.d.ts.map +1 -0
- package/dist/esm/codecs.js +16 -0
- package/dist/esm/codecs.js.map +1 -0
- package/dist/esm/errors.d.ts +93 -0
- package/dist/esm/errors.d.ts.map +1 -0
- package/dist/esm/errors.js +119 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/example.js +48 -32
- package/dist/esm/example.js.map +1 -1
- package/dist/esm/functions.d.ts +58 -0
- package/dist/esm/functions.d.ts.map +1 -0
- package/dist/esm/functions.js +65 -0
- package/dist/esm/functions.js.map +1 -0
- package/dist/esm/index.d.ts +10 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +12 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/package.json +17 -12
- package/dist/esm/types.d.ts +144 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/package.json +19 -14
- package/src/algorithms.test.ts +442 -0
- package/src/bases.ts +142 -0
- package/src/bufferbase.test.ts +44 -27
- package/src/bufferbase.ts +32 -117
- 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 +328 -0
- package/src/codec.ts +67 -0
- package/src/codecs.ts +24 -0
- package/src/errors.ts +127 -0
- package/src/example.ts +49 -34
- package/src/functions.ts +73 -0
- package/src/index.ts +39 -6
- package/src/types.ts +156 -0
- package/dist/cjs/bufferbase.d.mts +0 -60
- package/dist/cjs/bufferbase.d.mts.map +0 -1
- package/dist/cjs/bufferbase.mjs +0 -150
- package/dist/cjs/bufferbase.mjs.map +0 -1
- package/dist/cjs/example.d.mts +0 -2
- package/dist/cjs/example.d.mts.map +0 -1
- package/dist/cjs/example.mjs +0 -39
- package/dist/cjs/example.mjs.map +0 -1
- package/dist/cjs/index.d.mts +0 -2
- package/dist/cjs/index.d.mts.map +0 -1
- package/dist/cjs/index.mjs +0 -11
- package/dist/cjs/index.mjs.map +0 -1
- package/dist/esm/bufferbase.d.mts +0 -60
- package/dist/esm/bufferbase.d.mts.map +0 -1
- package/dist/esm/bufferbase.mjs +0 -141
- package/dist/esm/bufferbase.mjs.map +0 -1
- package/dist/esm/example.d.mts +0 -2
- package/dist/esm/example.d.mts.map +0 -1
- package/dist/esm/example.mjs +0 -37
- package/dist/esm/example.mjs.map +0 -1
- package/dist/esm/index.d.mts +0 -2
- package/dist/esm/index.d.mts.map +0 -1
- package/dist/esm/index.mjs +0 -2
- package/dist/esm/index.mjs.map +0 -1
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import type { BlockSpec, 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
|
+
} from './errors.js';
|
|
11
|
+
|
|
12
|
+
const RFC_BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
13
|
+
const RFC_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
14
|
+
const HEX_LOWER = '0123456789abcdef';
|
|
15
|
+
const HEX_UPPER = '0123456789ABCDEF';
|
|
16
|
+
|
|
17
|
+
/** A Node encoding that produces exactly what this codec would, and whether it needs upper-casing. */
|
|
18
|
+
type NativeEncoder = { readonly encoding: 'base64' | 'base64url' | 'hex'; readonly upper: boolean };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Finds the Node encoding equivalent to a spec, if there is one.
|
|
22
|
+
*
|
|
23
|
+
* Node's encoders are 100-250x faster than the loop below and always emit
|
|
24
|
+
* canonical output, so an exact match is handed off. Decoding is never handed
|
|
25
|
+
* off: Node's decoders are lenient, and rejecting non-canonical input is the
|
|
26
|
+
* point of this codec.
|
|
27
|
+
*/
|
|
28
|
+
function nativeEncoderFor(alphabet: string, pad: string | false): NativeEncoder | null {
|
|
29
|
+
if (alphabet === RFC_BASE64 && pad === '=') {
|
|
30
|
+
return { encoding: 'base64', upper: false };
|
|
31
|
+
}
|
|
32
|
+
if (alphabet === RFC_BASE64URL && pad === false) {
|
|
33
|
+
return { encoding: 'base64url', upper: false };
|
|
34
|
+
}
|
|
35
|
+
if (pad === false && (alphabet === HEX_LOWER || alphabet === HEX_UPPER)) {
|
|
36
|
+
return { encoding: 'hex', upper: alphabet === HEX_UPPER };
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Regroups the bit stream into fixed-width chunks, as specified by RFC 4648.
|
|
45
|
+
*
|
|
46
|
+
* Each character carries `log2(alphabet.length)` bits, so the alphabet must
|
|
47
|
+
* hold 2, 4, 8, 16, 32, or 64 characters. Unlike a radix conversion the output
|
|
48
|
+
* length is a fixed function of the input length, which is what makes Base64
|
|
49
|
+
* and Base32 splittable and streamable.
|
|
50
|
+
*
|
|
51
|
+
* A trailing partial block leaves spare bits in the final character. RFC 4648
|
|
52
|
+
* §3.5 requires those bits to be zero for the encoding to be canonical; input
|
|
53
|
+
* that sets them is rejected unless the spec passes `strict: false`.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```typescript
|
|
57
|
+
* import { Codecs } from 'bufferbase';
|
|
58
|
+
*
|
|
59
|
+
* Codecs.base64.encode(Buffer.from('fo')); // 'Zm8='
|
|
60
|
+
* Codecs.base64.validate('Zm9='); // false — spare bits are not zero
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export class BlockCodec extends BaseCodec {
|
|
64
|
+
readonly algorithm = 'block' as const;
|
|
65
|
+
|
|
66
|
+
/** Bits carried by one character. */
|
|
67
|
+
private readonly bitsPerChar: number;
|
|
68
|
+
/** Characters in a whole block. */
|
|
69
|
+
private readonly charsPerBlock: number;
|
|
70
|
+
private readonly padChar: string | false;
|
|
71
|
+
private readonly native: NativeEncoder | null;
|
|
72
|
+
|
|
73
|
+
constructor(spec: BlockSpec) {
|
|
74
|
+
super(spec);
|
|
75
|
+
|
|
76
|
+
const bits = Math.log2(spec.alphabet.length);
|
|
77
|
+
if (!Number.isInteger(bits)) {
|
|
78
|
+
throw new InvalidCodecError(
|
|
79
|
+
`'block' needs an alphabet of 2, 4, 8, 16, 32, or 64 characters, got ${spec.alphabet.length}`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const pad = spec.pad ?? '=';
|
|
84
|
+
if (pad !== false) {
|
|
85
|
+
if (pad.length !== 1) {
|
|
86
|
+
throw new InvalidCodecError(`pad must be a single character, got '${pad}'`);
|
|
87
|
+
}
|
|
88
|
+
if (this.valueOf(pad) !== undefined) {
|
|
89
|
+
throw new InvalidCodecError(`pad character '${pad}' is part of the alphabet`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
this.bitsPerChar = bits;
|
|
94
|
+
this.charsPerBlock = 8 / gcd(8, bits);
|
|
95
|
+
this.padChar = pad;
|
|
96
|
+
this.native = nativeEncoderFor(spec.alphabet, pad);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
encode(input: BufferLike): string {
|
|
100
|
+
const buffer = toBuffer(input);
|
|
101
|
+
if (this.native !== null) {
|
|
102
|
+
const encoded = buffer.toString(this.native.encoding);
|
|
103
|
+
return this.native.upper ? encoded.toUpperCase() : encoded;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const bits = this.bitsPerChar;
|
|
107
|
+
const mask = this.chars.length - 1;
|
|
108
|
+
const codes = this.codes;
|
|
109
|
+
if (codes === null) {
|
|
110
|
+
return this.encodeAsText(buffer);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const dataChars = Math.ceil((buffer.length * 8) / bits);
|
|
114
|
+
const total =
|
|
115
|
+
this.padChar === false
|
|
116
|
+
? dataChars
|
|
117
|
+
: Math.ceil(dataChars / this.charsPerBlock) * this.charsPerBlock;
|
|
118
|
+
const written = new Uint8Array(total);
|
|
119
|
+
let at = 0;
|
|
120
|
+
let acc = 0;
|
|
121
|
+
let held = 0;
|
|
122
|
+
|
|
123
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
124
|
+
acc = ((acc << 8) | buffer[i]) & 0xffff;
|
|
125
|
+
held += 8;
|
|
126
|
+
while (held >= bits) {
|
|
127
|
+
held -= bits;
|
|
128
|
+
written[at++] = codes[(acc >>> held) & mask];
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (held > 0) {
|
|
132
|
+
written[at++] = codes[(acc << (bits - held)) & mask];
|
|
133
|
+
}
|
|
134
|
+
if (this.padChar !== false) {
|
|
135
|
+
const padCode = this.padChar.charCodeAt(0);
|
|
136
|
+
while (at < total) {
|
|
137
|
+
written[at++] = padCode;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return this.textFrom(written, at);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The character-by-character path, for an alphabet that is not single-byte. */
|
|
144
|
+
private encodeAsText(buffer: Uint8Array): string {
|
|
145
|
+
const bits = this.bitsPerChar;
|
|
146
|
+
const mask = this.chars.length - 1;
|
|
147
|
+
let out = '';
|
|
148
|
+
let acc = 0;
|
|
149
|
+
let held = 0;
|
|
150
|
+
|
|
151
|
+
for (const byte of buffer) {
|
|
152
|
+
acc = ((acc << 8) | byte) & 0xffff;
|
|
153
|
+
held += 8;
|
|
154
|
+
while (held >= bits) {
|
|
155
|
+
held -= bits;
|
|
156
|
+
out += this.chars[(acc >>> held) & mask];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (held > 0) {
|
|
160
|
+
out += this.chars[(acc << (bits - held)) & mask];
|
|
161
|
+
}
|
|
162
|
+
if (this.padChar !== false) {
|
|
163
|
+
while (out.length % this.charsPerBlock !== 0) {
|
|
164
|
+
out += this.padChar;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
decode(encoded: string, options?: DecodeOptions): Buffer {
|
|
171
|
+
const data = this.checkStructure(this.strip(encoded));
|
|
172
|
+
const bits = this.bitsPerChar;
|
|
173
|
+
const bytes = Buffer.alloc(Math.floor((data.length * bits) / 8));
|
|
174
|
+
let at = 0;
|
|
175
|
+
let acc = 0;
|
|
176
|
+
let held = 0;
|
|
177
|
+
|
|
178
|
+
for (let i = 0; i < data.length; i++) {
|
|
179
|
+
const value = this.valueAt(data, i);
|
|
180
|
+
if (value < 0) {
|
|
181
|
+
throw new InvalidCharacterError(data[i]);
|
|
182
|
+
}
|
|
183
|
+
acc = ((acc << bits) | value) & 0xffff;
|
|
184
|
+
held += bits;
|
|
185
|
+
if (held >= 8) {
|
|
186
|
+
held -= 8;
|
|
187
|
+
bytes[at++] = (acc >>> held) & 0xff;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const size = options?.size;
|
|
192
|
+
if (size !== undefined && bytes.length !== size) {
|
|
193
|
+
throw new BufferSizeError(bytes.length, size);
|
|
194
|
+
}
|
|
195
|
+
return bytes;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
validate(input: string): boolean {
|
|
199
|
+
try {
|
|
200
|
+
this.checkStructure(this.strip(input));
|
|
201
|
+
return true;
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Strips and checks the padding, then verifies that what remains can be the
|
|
209
|
+
* encoding of some byte sequence. Returns the data characters.
|
|
210
|
+
*
|
|
211
|
+
* Everything `decode` can reject other than `DecodeOptions.size` is checked
|
|
212
|
+
* here, so `validate` and `decode` always agree.
|
|
213
|
+
*/
|
|
214
|
+
private checkStructure(input: string): string {
|
|
215
|
+
let data = input;
|
|
216
|
+
|
|
217
|
+
if (this.padChar !== false) {
|
|
218
|
+
let dataLength = input.length;
|
|
219
|
+
while (dataLength > 0 && input[dataLength - 1] === this.padChar) {
|
|
220
|
+
dataLength--;
|
|
221
|
+
}
|
|
222
|
+
data = input.slice(0, dataLength);
|
|
223
|
+
if (input.length % this.charsPerBlock !== 0) {
|
|
224
|
+
throw new InvalidLengthError(
|
|
225
|
+
input.length,
|
|
226
|
+
`padded input must be a multiple of ${this.charsPerBlock} characters`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
if (input.length - dataLength >= this.charsPerBlock) {
|
|
230
|
+
throw new InvalidLengthError(input.length, 'too many padding characters');
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const bits = this.bitsPerChar;
|
|
235
|
+
const spare = (data.length * bits) % 8;
|
|
236
|
+
if (spare >= bits) {
|
|
237
|
+
throw new InvalidLengthError(
|
|
238
|
+
data.length,
|
|
239
|
+
`${data.length} characters carry ${data.length * bits} bits, which is not a whole number of bytes`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let last = -1;
|
|
244
|
+
for (let i = 0; i < data.length; i++) {
|
|
245
|
+
last = this.valueAt(data, i);
|
|
246
|
+
if (last < 0) {
|
|
247
|
+
throw new InvalidCharacterError(data[i]);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (this.strict && spare > 0 && last >= 0 && (last & ((1 << spare) - 1)) !== 0) {
|
|
252
|
+
throw new NonCanonicalError(
|
|
253
|
+
`the final character carries ${spare} spare bits that must be zero`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
return data;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -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
|
+
}
|