Move some utilities to BufferUtils.

Change-Id: Ifb3c4348cc912640b99ff53f7cac59a63480c68e
This commit is contained in:
Jacob Trimble
2019-08-20 10:32:12 -07:00
parent fdd2602acd
commit a2bcf7278d
19 changed files with 264 additions and 131 deletions
-85
View File
@@ -109,35 +109,6 @@ shaka.util.Uint8ArrayUtils = class {
}
/**
* Compare two Uint8Arrays for equality.
* For convenience, this also accepts Arrays, so that one can trivially
* compare a Uint8Array to an Array of numbers.
*
* @param {(Uint8Array|Array.<number>)} arr1
* @param {(Uint8Array|Array.<number>)} arr2
* @return {boolean}
* @export
*/
static equal(arr1, arr2) {
if (!arr1 && !arr2) {
return true;
}
if (!arr1 || !arr2) {
return false;
}
if (arr1.length != arr2.length) {
return false;
}
for (const i of shaka.util.Iterables.range(arr1.length)) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
/**
* Concatenate Uint8Arrays.
* @param {...!Uint8Array} varArgs
@@ -158,60 +129,4 @@ shaka.util.Uint8ArrayUtils = class {
}
return result;
}
/**
* Creates a DataView over the given buffer.
* @param {!BufferSource} buffer
* @return {!DataView}
*/
static toDataView(buffer) {
if (buffer instanceof ArrayBuffer) {
return new DataView(buffer);
} else {
return new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
}
/**
* Gets the underlying ArrayBuffer of the given view. The caller needs to
* ensure it uses the "byteOffset" and "byteLength" fields of the view to
* only use the same "view" of the data.
*
* @param {!BufferSource} view
* @return {!ArrayBuffer}
*/
static unsafeGetArrayBuffer(view) {
if (view instanceof ArrayBuffer) {
return view;
} else {
return view.buffer;
}
}
/**
* Gets an ArrayBuffer that contains the data from the given TypedArray. Note
* this will allocate a new ArrayBuffer if the object is a partial view of
* the data.
*
* @param {!BufferSource} view
* @return {!ArrayBuffer}
*/
static toArrayBuffer(view) {
if (view instanceof ArrayBuffer) {
return view;
} else {
if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {
// This is a TypedArray over the whole buffer.
return view.buffer;
}
// This is a "view" on the buffer. Create a new buffer that only contains
// the data.
const ret = new Uint8Array(view.byteLength);
ret.set(view);
return ret.buffer;
}
}
};