Make Uint8ArrayUtils accept BufferSource.

Change-Id: Ia22b4535f4a6cbc156022299d732b27602c677d3
This commit is contained in:
Jacob Trimble
2019-08-20 14:24:24 -07:00
parent 18b59c5294
commit 887f2e614d
5 changed files with 24 additions and 28 deletions
+19 -16
View File
@@ -17,6 +17,7 @@
goog.provide('shaka.util.Uint8ArrayUtils');
goog.require('shaka.util.BufferUtils');
goog.require('shaka.util.Iterables');
goog.require('shaka.util.StringUtils');
@@ -27,29 +28,30 @@ goog.require('shaka.util.StringUtils');
*/
shaka.util.Uint8ArrayUtils = class {
/**
* Convert a Uint8Array to a base64 string. The output will be standard
* Convert a buffer to a base64 string. The output will be standard
* alphabet as opposed to base64url safe alphabet.
* @param {!Uint8Array} u8Arr
* @param {BufferSource} data
* @return {string}
* @export
*/
static toStandardBase64(u8Arr) {
const bytes = shaka.util.StringUtils.fromCharCode(u8Arr);
static toStandardBase64(data) {
const bytes = shaka.util.StringUtils.fromCharCode(
shaka.util.BufferUtils.toUint8(data));
return btoa(bytes);
}
/**
* Convert a Uint8Array to a base64 string. The output will always use the
* Convert a buffer to a base64 string. The output will always use the
* alternate encoding/alphabet also known as "base64url".
* @param {!Uint8Array} arr
* @param {BufferSource} data
* @param {boolean=} padding If true, pad the output with equals signs.
* Defaults to true.
* @return {string}
* @export
*/
static toBase64(arr, padding) {
static toBase64(data, padding) {
padding = (padding == undefined) ? true : padding;
const base64 = shaka.util.Uint8ArrayUtils.toStandardBase64(arr)
const base64 = shaka.util.Uint8ArrayUtils.toStandardBase64(data)
.replace(/\+/g, '-').replace(/\//g, '_');
return padding ? base64 : base64.replace(/[=]*$/, '');
}
@@ -91,12 +93,13 @@ shaka.util.Uint8ArrayUtils = class {
/**
* Convert a Uint8Array to a hex string.
* @param {!Uint8Array} arr
* Convert a buffer to a hex string.
* @param {BufferSource} data
* @return {string}
* @export
*/
static toHex(arr) {
static toHex(data) {
const arr = shaka.util.BufferUtils.toUint8(data);
let hex = '';
for (let value of arr) {
value = value.toString(16);
@@ -110,22 +113,22 @@ shaka.util.Uint8ArrayUtils = class {
/**
* Concatenate Uint8Arrays.
* @param {...!Uint8Array} varArgs
* Concatenate buffers.
* @param {...BufferSource} varArgs
* @return {!Uint8Array}
* @export
*/
static concat(...varArgs) {
let totalLength = 0;
for (const arr of varArgs) {
totalLength += arr.length;
totalLength += arr.byteLength;
}
const result = new Uint8Array(totalLength);
let offset = 0;
for (const arr of varArgs) {
result.set(arr, offset);
offset += arr.length;
result.set(shaka.util.BufferUtils.toUint8(arr), offset);
offset += arr.byteLength;
}
return result;
}