to-arraybuffer.js 1.0 KB

123456789101112131415161718192021222324252627282930
  1. // from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js
  2. // MIT License
  3. // Copyright (c) 2016 John Hiesey
  4. import {isBuffer} from 'buffer';
  5. export default function (buf) {
  6. // If the buffer is backed by a Uint8Array, a faster version will work
  7. if (buf instanceof Uint8Array) {
  8. // If the buffer isn't a subarray, return the underlying ArrayBuffer
  9. if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
  10. return buf.buffer
  11. } else if (typeof buf.buffer.slice === 'function') {
  12. // Otherwise we need to get a proper copy
  13. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
  14. }
  15. }
  16. if (isBuffer(buf)) {
  17. // This is the slow version that will work with any Buffer
  18. // implementation (even in old browsers)
  19. var arrayCopy = new Uint8Array(buf.length)
  20. var len = buf.length
  21. for (var i = 0; i < len; i++) {
  22. arrayCopy[i] = buf[i]
  23. }
  24. return arrayCopy.buffer
  25. } else {
  26. throw new Error('Argument must be a Buffer')
  27. }
  28. }