Skip to content

Commit

Permalink
feat: Add a function to concat typed arrays into one Uint8Array (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonocasey authored May 1, 2020
1 parent ab1de18 commit e733509
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/byte-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
53 changes: 52 additions & 1 deletion test/byte-helpers.test.js
Original file line number Diff line number Diff line change
@@ -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 = [];
Expand Down Expand Up @@ -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}`);
});
});

0 comments on commit e733509

Please sign in to comment.