]> git.codecow.com Git - libnemo.git/commitdiff
Update binary-to-byte converter.
authorChris Duncan <chris@codecow.com>
Tue, 30 Jun 2026 21:59:41 +0000 (14:59 -0700)
committerChris Duncan <chris@codecow.com>
Tue, 30 Jun 2026 21:59:41 +0000 (14:59 -0700)
src/lib/convert/bin.ts

index 5ca0876701839f15fa655305ef90c0975010f21c..6da52755bd923c72f2e7c0bad1eadd0907947492 100644 (file)
@@ -8,13 +8,20 @@ export const bin = Object.freeze({
         * @param {string} bin - String to convert
         * @returns {Uint8Array} Byte array representation of the input string
         */
-       toBytes (bin: string): Uint8Array<ArrayBuffer> {
-               const bytes: number[] = []
-               while (bin.length > 0) {
-                       const bits = bin.substring(0, 8)
-                       bytes.push(parseInt(bits, 2))
-                       bin = bin.substring(8)
+       toBytes (bin: string, padding: number = 1): Uint8Array<ArrayBuffer> {
+               if (typeof bin !== 'string' || !/^[01]+$/i.test(bin)) {
+                       throw new TypeError('Invalid string when converting bin to bytes', { cause: bin })
                }
-               return new Uint8Array(bytes)
+               if (typeof padding !== 'number' || padding < 1 || padding > 0xffffffff) {
+                       throw new TypeError('Invalid padding when converting bin to bytes', { cause: padding })
+               }
+               const pad = bin.length & 7
+               if (pad) bin = bin.padStart(bin.length + 8 - pad, '0')
+               const byteLength = bin.length >> 3
+               const diff = padding - byteLength
+               const offset = diff & ~(diff >> 31)
+               const bytes = new Uint8Array(byteLength + offset)
+               bytes.set(bin.match(/.{8}/g)?.map(b => parseInt(b, 2)) ?? [], offset)
+               return bytes
        },
 })