Explorar o código

Add arrayToBuffer helper function

Lennart Grahl %!s(int64=6) %!d(string=hai) anos
pai
achega
1be4d768ed
Modificáronse 1 ficheiros con 14 adicións e 0 borrados
  1. 14 0
      src/helpers.ts

+ 14 - 0
src/helpers.ts

@@ -326,6 +326,20 @@ export function bufferToUrl(buffer: ArrayBuffer, mimeType: string, log: Logger):
     return 'data:' + mimeType + ';base64,' + u8aToBase64(new Uint8Array(buffer));
 }
 
+/**
+ * Convert a TypedArray to an ArrayBuffer.
+ *
+ * **Important:** If the source array's data occupies the underlying buffer
+ *   completely, the underlying buffer will be returned directly. Thus, the
+ *   caller may not assume that the data has been copied.
+ */
+export function arrayToBuffer(array: ArrayBufferView): ArrayBuffer {
+    if (array.byteOffset === 0 && array.byteLength === array.buffer.byteLength) {
+        return array.buffer;
+    }
+    return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength);
+}
+
 /**
  * Return whether a value is not null and not undefined.
  */