1 // ♓🌟 Piscēs ∷ binary.js
2 // ====================================================================
4 // Copyright © 2020–2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 import { fill
, map
, reduce
} from "./collection.js";
11 import { bind
, call
} from "./function.js";
12 import { ceil
, floor
} from "./numeric.js";
13 import { hasOwnProperty
, objectCreate
} from "./object.js";
21 const Buffer
= ArrayBuffer
;
22 const View
= DataView
;
23 const TypedArray
= Object
.getPrototypeOf(Uint8Array
);
24 const { prototype: arrayPrototype
} = Array
;
25 const { prototype: bufferPrototype
} = Buffer
;
26 const { iterator
: iteratorSymbol
} = Symbol
;
27 const { prototype: rePrototype
} = RegExp
;
28 const { prototype: typedArrayPrototype
} = TypedArray
;
29 const { prototype: viewPrototype
} = View
;
31 const { [iteratorSymbol
]: arrayIterator
} = arrayPrototype
;
33 next
: arrayIteratorNext
,
34 } = Object
.getPrototypeOf([][iteratorSymbol
]());
35 const argumentIterablePrototype
= {
40 call(arrayIterator
, this.args
, []),
46 const binaryCodeUnitIterablePrototype
= {
51 call(arrayIterator
, this, []),
58 const getBufferByteLength
=
59 Object
.getOwnPropertyDescriptor(bufferPrototype
, "byteLength").get;
60 const getTypedArrayBuffer
=
61 Object
.getOwnPropertyDescriptor(typedArrayPrototype
, "buffer").get;
63 Object
.getOwnPropertyDescriptor(viewPrototype
, "buffer").get;
64 const { exec
: reExec
} = rePrototype
;
66 getUint8
: viewGetUint8
,
67 setUint8
: viewSetUint8
,
68 setUint16
: viewSetUint16
,
72 * Returns an ArrayBuffer for encoding generated from the provided
75 const bufferFromArgs
= ($, $s
) =>
79 ? call(getViewBuffer
, $, [])
80 : $ instanceof TypedArray
81 ? call(getTypedArrayBuffer
, $, [])
87 (result
, ucsCharacter
, index
) => (
88 call(viewSetUint16
, result
, [
90 getCodeUnit(ucsCharacter
, 0),
93 new View(new Buffer(string
.length
* 2)),
99 : hasOwnProperty($, "raw")
102 ...objectCreate(argumentIterablePrototype
, {
110 * Returns the result of decoding the provided base64 string into an
113 * ※ This function is not exposed.
115 const decodeBase64
= (source
, safe
= false) => {
117 source
.length
% 4 == 0
118 ? stringReplace(source
, /={1,2}$/u, "")
121 const code
= getCodeUnit(ucsCharacter
, 0);
122 const result
= code
>= 0x41 && code
<= 0x5A
124 : code
>= 0x61 && code
<= 0x7A
126 : code
>= 0x30 && code
<= 0x39
128 : code
== (safe
? 0x2D : 0x2B)
130 : code
== (safe
? 0x5F : 0x2F)
134 throw new RangeError(
135 `Piscēs: Invalid character in Base64: ${ucsCharacter}.`,
142 const { length
} = u6s
;
143 if (length
% 4 == 1) {
144 throw new RangeError(
145 `Piscēs: Base64 string has invalid length: ${source}.`,
148 const dataView
= new View(new Buffer(floor(length
* 3 / 4)));
149 for (let index
= 0; index
< length
- 1;) {
150 // The final index is not handled; if the string is not divisible
151 // by 4, some bits might be dropped. This matches the “forgiving
152 // decode” behaviour specified by WhatW·G for base64.
153 const dataIndex
= ceil(index
* 3 / 4);
154 const remainder
= index
% 4;
155 if (remainder
== 0) {
156 call(viewSetUint8
, dataView
, [
158 u6s
[index
] << 2 | u6s
[++index
] >> 4,
160 } else if (remainder
== 1) {
161 call(viewSetUint8
, dataView
, [
163 u6s
[index
] << 4 | u6s
[++index
] >> 2,
165 } else { // remainder == 2
166 call(viewSetUint8
, dataView
, [
168 u6s
[index
] << 6 | u6s
[++index
, index
++],
172 return call(getViewBuffer
, dataView
, []);
177 * Returns the result of encoding the provided ArrayBuffer into a
180 * ※ This function is not exposed.
182 const encodeBase64
= (buffer
, safe
= false) => {
183 const dataView
= new View(buffer
);
184 const byteLength
= call(getBufferByteLength
, buffer
, []);
185 const minimumLengthOfResults
= ceil(byteLength
* 4 / 3);
186 const resultingCodeUnits
= fill(
188 binaryCodeUnitIterablePrototype
,
191 value
: minimumLengthOfResults
+
192 (4 - (minimumLengthOfResults
% 4)) % 4,
198 for (let index
= 0; index
< byteLength
;) {
199 const codeUnitIndex
= ceil(index
* 4 / 3);
200 const currentIndex
= codeUnitIndex
+ +(
201 index
% 3 == 0 && resultingCodeUnits
[codeUnitIndex
] != 0x3D
202 ); // every third byte handles two letters; this is for the second
203 const remainder
= currentIndex
% 4;
204 const currentByte
= call(viewGetUint8
, dataView
, [index
]);
205 const nextByte
= remainder
% 3 && ++index
< byteLength
206 // digits 1 & 2 span multiple bytes
207 ? call(viewGetUint8
, dataView
, [index
])
209 const u6
= remainder
== 0
212 ? (currentByte
& 0b00000011) << 4 | nextByte
>> 4
214 ? (currentByte
& 0b00001111) << 2 | nextByte
>> 6
215 : (++index
, currentByte
& 0b00111111); // remainder == 3
216 const result
= u6
< 26
223 ? (safe
? 0x2D : 0x2B)
225 ? (safe
? 0x5F : 0x2F)
228 throw new RangeError(`Piscēs: Unexpected Base64 value: ${u6}.`);
230 resultingCodeUnits
[currentIndex
] = result
;
233 return stringFromCodeUnits(...resultingCodeUnits
);
237 * Returns a source string generated from the arguments passed to a
240 * ※ This function is not exposed.
242 const sourceFromArgs
= ($, $s
) =>
244 typeof $ == "string" ? $ : hasOwnProperty($, "raw")
247 ...objectCreate(argumentIterablePrototype
, {
257 * Returns an ArrayBuffer generated from the provided base64 string.
259 * This function can also be used as a tag for a template literal. The
260 * literal will be interpreted akin to `String.raw`.
262 * ☡ This function throws if the provided string is not a valid base64
265 export const base64Binary
= ($, ...$s
) =>
266 decodeBase64(sourceFromArgs($, $s
));
269 * Returns a (big‐endian) base64 string created from the provided typed
270 * array, buffer, or (16‐bit) string.
272 * This function can also be used as a tag for a template literal. The
273 * literal will be interpreted akin to `String.raw`.
275 export const base64String
= ($, ...$s
) =>
276 encodeBase64(bufferFromArgs($, $s
));
279 * Returns an ArrayBuffer generated from the provided filename‐safe
282 * This function can also be used as a tag for a template literal. The
283 * literal will be interpreted akin to `String.raw`.
285 * ☡ This function throws if the provided string is not a valid
286 * filename‐safe base64 string.
288 export const filenameSafeBase64Binary
= ($, ...$s
) =>
289 decodeBase64(sourceFromArgs($, $s
), true);
292 * Returns a (big‐endian) filename‐safe base64 string created from the
293 * provided typed array, buffer, or (16‐bit) string.
295 * This function can also be used as a tag for a template literal. The
296 * literal will be interpreted akin to `String.raw`.
298 export const filenameSafeBase64String
= ($, ...$s
) =>
299 encodeBase64(bufferFromArgs($, $s
), true);
302 * Returns whether the provided value is a Base64 string.
304 * ※ This function returns false if the provided value is not a string
307 export const isBase64
= ($) => {
308 if (typeof $ !== "string") {
311 const source
= stringReplace($, /[\t\n\f\r ]+/gu, "");
312 const trimmed
= source
.length
% 4 == 0
313 ? stringReplace(source
, /={1,2}$/u, "")
315 return trimmed
.length
% 4 != 1 &&
316 call(reExec
, /[^0-9A-Za-z+\/]/u, [trimmed
]) == null;
321 * Returns whether the provided value is a filename‐safe base64 string.
323 * ※ This function returns false if the provided value is not a string
326 export const isFilenameSafeBase64
= ($) => {
327 if (typeof $ !== "string") {
330 const source
= stringReplace($, /[\t\n\f\r ]+/gu, "");
331 const trimmed
= source
.length
% 4 == 0
332 ? stringReplace(source
, /={1,2}$/u, "")
334 return trimmed
.length
% 4 != 1 &&
335 call(reExec
, /[^0-9A-Za-z_-]/u, [trimmed
]) == null;