index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @module to-array-buffer
  3. */
  4. 'use strict'
  5. var str2ab = require('string-to-arraybuffer')
  6. var flat = require('flatten-vertex-data')
  7. // var isBlob = require('is-blob')
  8. module.exports = function toArrayBuffer (arg) {
  9. //zero-length or undefined-like
  10. if (!arg) return null
  11. //array buffer
  12. if (arg instanceof ArrayBuffer) return arg
  13. //try to decode data-uri
  14. if (typeof arg === 'string') {
  15. return str2ab(arg)
  16. }
  17. // File & Blob
  18. // if (isBlob(src) || (src instanceof global.File)) {
  19. // FIXME: we cannot use it here bc FileReader is async
  20. // }
  21. //array buffer view: TypedArray, DataView, Buffer etc
  22. if (ArrayBuffer.isView(arg)) {
  23. // if byteOffset is not 0, return sub-reference (slice is the only way)
  24. if (arg.byteOffset) {
  25. return arg.buffer.slice(arg.byteOffset, arg.byteOffset + arg.byteLength)
  26. }
  27. return arg.buffer
  28. }
  29. //buffer/data nested: NDArray, ImageData etc.
  30. //FIXME: NDArrays with custom data type may be invalid for this procedure
  31. if (arg.buffer || arg.data || arg._data) {
  32. var result = toArrayBuffer(arg.buffer || arg.data || arg._data)
  33. return result
  34. }
  35. // detect if flat
  36. if (Array.isArray(arg)) {
  37. for (var i = 0; i < arg.length; i++) {
  38. if (arg[i].length != null) {
  39. arg = flat(arg)
  40. break
  41. }
  42. }
  43. }
  44. //array-like or unknown
  45. //consider Uint8Array knows how to treat the input
  46. var result = new Uint8Array(arg)
  47. if (!result.length) return null
  48. return result.buffer
  49. }