index.js 881 B

12345678910111213141516171819202122232425262728
  1. var Buffer = require('buffer').Buffer
  2. module.exports = function (buf) {
  3. // If the buffer is backed by a Uint8Array, a faster version will work
  4. if (buf instanceof Uint8Array) {
  5. // If the buffer isn't a subarray, return the underlying ArrayBuffer
  6. if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
  7. return buf.buffer
  8. } else if (typeof buf.buffer.slice === 'function') {
  9. // Otherwise we need to get a proper copy
  10. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
  11. }
  12. }
  13. if (Buffer.isBuffer(buf)) {
  14. // This is the slow version that will work with any Buffer
  15. // implementation (even in old browsers)
  16. var arrayCopy = new Uint8Array(buf.length)
  17. var len = buf.length
  18. for (var i = 0; i < len; i++) {
  19. arrayCopy[i] = buf[i]
  20. }
  21. return arrayCopy.buffer
  22. } else {
  23. throw new Error('Argument must be a Buffer')
  24. }
  25. }