1 // ♓🌟 Piscēs ∷ binary.js
2 // ====================================================================
4 // Copyright © 2020–2022 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
,
71 const bufferFromArgs
= ($, $s
) =>
75 ? call(getViewBuffer
, $, [])
76 : $ instanceof TypedArray
77 ? call(getTypedArrayBuffer
, $, [])
83 (result
, ucsCharacter
, index
) => (
84 call(viewSetUint16
, result
, [
86 getCodeUnit(ucsCharacter
, 0),
89 new View(new Buffer(string
.length
* 2)),
95 : hasOwnProperty($, "raw")
98 ...objectCreate(argumentIterablePrototype
, {
106 * Returns the result of decoding the provided base64 string into an
109 * ※ This function is not exposed.
111 const decodeBase64
= (source
, safe
= false) => {
113 source
.length
% 4 == 0
114 ? stringReplace(source
, /={1,2}$/u, "")
117 const code
= getCodeUnit(ucsCharacter
, 0);
118 const result
= code
>= 0x41 && code
<= 0x5A
120 : code
>= 0x61 && code
<= 0x7A
122 : code
>= 0x30 && code
<= 0x39
124 : code
== (safe
? 0x2D : 0x2B)
126 : code
== (safe
? 0x5F : 0x2F)
130 throw new RangeError(
131 `Piscēs: Invalid character in Base64: ${character}.`,
138 const { length
} = u6s
;
139 const dataView
= new View(new Buffer(floor(length
* 3 / 4)));
140 for (let index
= 0; index
< length
- 1;) {
141 const dataIndex
= ceil(index
* 3 / 4);
142 const remainder
= index
% 3;
143 if (remainder
== 0) {
144 call(viewSetUint8
, dataView
, [
146 (u6s
[index
] << 2) + (u6s
[++index
] >> 4),
148 } else if (remainder
== 1) {
149 call(viewSetUint8
, dataView
, [
151 ((u6s
[index
] & 0xF) << 4) + (u6s
[++index
] >> 2),
154 call(viewSetUint8
, dataView
, [
156 ((u6s
[index
] & 0x3) << 6) + u6s
[++index
],
160 return call(getViewBuffer
, dataView
, []);
164 * Returns the result of encoding the provided ArrayBuffer into a
167 * ※ This function is not exposed.
169 const encodeBase64
= (buffer
, safe
= false) => {
170 const dataView
= new View(buffer
);
171 const byteLength
= call(getBufferByteLength
, buffer
, []);
172 const minimumLengthOfResults
= ceil(byteLength
* 4 / 3);
173 const resultingCodeUnits
= fill(
175 binaryCodeUnitIterablePrototype
,
178 value
: minimumLengthOfResults
+
179 (4 - (minimumLengthOfResults
% 4)) % 4,
185 for (let index
= 0; index
< byteLength
;) {
186 const codeUnitIndex
= ceil(index
* 4 / 3);
187 const currentIndex
= codeUnitIndex
+ +(
188 index
% 3 == 0 && resultingCodeUnits
[codeUnitIndex
] != 0x3D
190 const remainder
= currentIndex
% 4;
191 const u6
= remainder
== 0
192 ? call(viewGetUint8
, dataView
, [index
]) >> 2
194 ? ((call(viewGetUint8
, dataView
, [index
++]) & 0x3) << 4) +
196 ? call(viewGetUint8
, dataView
, [index
]) >> 4
199 ? ((call(viewGetUint8
, dataView
, [index
++]) & 0xF) << 2) +
201 ? call(viewGetUint8
, dataView
, [index
]) >> 6
203 : call(viewGetUint8
, dataView
, [index
++]) & 0x3F;
204 const result
= u6
< 26
211 ? (safe
? 0x2D : 0x2B)
213 ? (safe
? 0x5F : 0x2F)
216 throw new RangeError(`Piscēs: Unexpected Base64 value: ${u6}.`);
218 resultingCodeUnits
[currentIndex
] = result
;
221 return stringFromCodeUnits(...resultingCodeUnits
);
225 * Returns a source string generated from the arguments passed to a
228 * ※ This function is not exposed.
230 const sourceFromArgs
= ($, $s
) =>
232 typeof $ == "string" ? $ : hasOwnProperty($, "raw")
235 ...objectCreate(argumentIterablePrototype
, {
245 * Returns an ArrayBuffer generated from the provided base64 string.
247 * This function can also be used as a tag for a template literal. The
248 * literal will be interpreted akin to `String.raw`.
250 export const base64Binary
= ($, ...$s
) =>
251 decodeBase64(sourceFromArgs($, $s
));
254 * Returns a (big‐endian) base64 string created from the provided typed
255 * array, buffer, or (16‐bit) string.
257 * This function can also be used as a tag for a template literal. The
258 * literal will be interpreted akin to `String.raw`.
260 export const base64String
= ($, ...$s
) =>
261 encodeBase64(bufferFromArgs($, $s
));
264 * Returns an ArrayBuffer generated from the provided filename‐safe
267 * This function can also be used as a tag for a template literal. The
268 * literal will be interpreted akin to `String.raw`.
270 export const filenameSafeBase64Binary
= ($, ...$s
) =>
271 decodeBase64(sourceFromArgs($, $s
), true);
274 * Returns a (big‐endian) filename‐safe base64 string created from the
275 * provided typed array, buffer, or (16‐bit) string.
277 * This function can also be used as a tag for a template literal. The
278 * literal will be interpreted akin to `String.raw`.
280 export const filenameSafeBase64String
= ($, ...$s
) =>
281 encodeBase64(bufferFromArgs($, $s
), true);
284 * Returns whether the provided value is a Base64 string.
286 * ※ This function returns false if the provided value is not a string
289 export const isBase64
= ($) => {
290 if (typeof $ !== "string") {
293 const source
= stringReplace($, /[\t\n\f\r ]+/gu, "");
294 const trimmed
= source
.length
% 4 == 0
295 ? stringReplace(source
, /={1,2}$/u, "")
297 return trimmed
.length
% 4 != 1 &&
298 call(reExec
, /[^0-9A-Za-z+\/]/u, [trimmed
]) == null;
303 * Returns whether the provided value is a filename‐safe base64 string.
305 * ※ This function returns false if the provided value is not a string
308 export const isFilenameSafeBase64
= ($) => {
309 if (typeof $ !== "string") {
312 const source
= stringReplace($, /[\t\n\f\r ]+/gu, "");
313 const trimmed
= source
.length
% 4 == 0
314 ? stringReplace(source
, /={1,2}$/u, "")
316 return trimmed
.length
% 4 != 1 &&
317 call(reExec
, /[^0-9A-Za-z_-]/u, [trimmed
]) == null;