diff --git a/src/byte-helpers.js b/src/byte-helpers.js index 6ae4939..06062fc 100644 --- a/src/byte-helpers.js +++ b/src/byte-helpers.js @@ -44,3 +44,26 @@ export const stringToBytes = (string, stringIsBytes = false) => { return string.split('').map((s) => s.charCodeAt(0) & 0xFF); }; + +export const concatTypedArrays = (...buffers) => { + const totalLength = buffers.reduce((total, buf) => { + const len = buf && (buf.byteLength || buf.length); + + total += len || 0; + + return total; + }, 0); + + const tempBuffer = new Uint8Array(totalLength); + + let offset = 0; + + buffers.forEach(function(buf) { + buf = toUint8(buf); + + tempBuffer.set(buf, offset); + offset += buf.byteLength; + }); + + return tempBuffer; +}; diff --git a/test/byte-helpers.test.js b/test/byte-helpers.test.js index 8c0604c..25f7622 100644 --- a/test/byte-helpers.test.js +++ b/test/byte-helpers.test.js @@ -1,5 +1,10 @@ import QUnit from 'qunit'; -import {bytesToString, stringToBytes, toUint8} from '../src/byte-helpers.js'; +import { + bytesToString, + stringToBytes, + toUint8, + concatTypedArrays +} from '../src/byte-helpers.js'; import window from 'global/window'; const arrayNames = []; @@ -85,3 +90,49 @@ QUnit.test('should function as expected', function(assert) { assert.ok(uint instanceof Uint8Array && uint.length > 0, `converted ${name} to Uint8Array`); }); }); + +QUnit.module('concatTypedArrays'); + +QUnit.test('should function as expected', function(assert) { + const tests = { + undef: { + data: concatTypedArrays(), + expected: toUint8([]) + }, + empty: { + data: concatTypedArrays(toUint8([])), + expected: toUint8([]) + }, + single: { + data: concatTypedArrays([0x01]), + expected: toUint8([0x01]) + }, + array: { + data: concatTypedArrays([0x01], [0x02]), + expected: toUint8([0x01, 0x02]) + }, + uint: { + data: concatTypedArrays(toUint8([0x01]), toUint8([0x02])), + expected: toUint8([0x01, 0x02]) + }, + buffer: { + data: concatTypedArrays(toUint8([0x01]).buffer, toUint8([0x02]).buffer), + expected: toUint8([0x01, 0x02]) + }, + manyarray: { + data: concatTypedArrays([0x01], [0x02], [0x03], [0x04]), + expected: toUint8([0x01, 0x02, 0x03, 0x04]) + }, + manyuint: { + data: concatTypedArrays(toUint8([0x01]), toUint8([0x02]), toUint8([0x03]), toUint8([0x04])), + expected: toUint8([0x01, 0x02, 0x03, 0x04]) + } + }; + + Object.keys(tests).forEach(function(name) { + const {data, expected} = tests[name]; + + assert.ok(data instanceof Uint8Array, `obj is a Uint8Array for ${name}`); + assert.deepEqual(data, expected, `data is as expected for ${name}`); + }); +});