index.js 758 B

1234567891011121314151617181920212223242526
  1. /**
  2. * Convert a typed array to a Buffer without a copy
  3. *
  4. * Author: Feross Aboukhadijeh <https://feross.org>
  5. * License: MIT
  6. *
  7. * `npm install typedarray-to-buffer`
  8. */
  9. var isTypedArray = require('is-typedarray').strict
  10. module.exports = function typedarrayToBuffer (arr) {
  11. if (isTypedArray(arr)) {
  12. // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer
  13. var buf = Buffer.from(arr.buffer)
  14. if (arr.byteLength !== arr.buffer.byteLength) {
  15. // Respect the "view", i.e. byteOffset and byteLength, without doing a copy
  16. buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
  17. }
  18. return buf
  19. } else {
  20. // Pass through all other types to `Buffer.from`
  21. return Buffer.from(arr)
  22. }
  23. }