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