buffer-utils.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Note: Don't use destructuring assignment for `Buffer`, or we'll hit a
  2. // browserify bug that makes the statement invalid, throwing an error in
  3. // sandboxed renderer.
  4. const Buffer = require('buffer').Buffer
  5. const typedArrays = {
  6. Buffer,
  7. ArrayBuffer,
  8. Int8Array,
  9. Uint8Array,
  10. Uint8ClampedArray,
  11. Int16Array,
  12. Uint16Array,
  13. Int32Array,
  14. Uint32Array,
  15. Float32Array,
  16. Float64Array
  17. }
  18. function getType (value) {
  19. for (const type of Object.keys(typedArrays)) {
  20. if (value instanceof typedArrays[type]) {
  21. return type
  22. }
  23. }
  24. return null
  25. }
  26. exports.isBuffer = function (value) {
  27. return ArrayBuffer.isView(value) || value instanceof ArrayBuffer
  28. }
  29. exports.bufferToMeta = function (value) {
  30. const buffer = (value instanceof ArrayBuffer)
  31. ? Buffer.from(value)
  32. : Buffer.from(value.buffer, value.byteOffset, value.byteLength)
  33. return {
  34. type: getType(value),
  35. data: buffer.toString('base64'),
  36. length: value.length
  37. }
  38. }
  39. exports.metaToBuffer = function (value) {
  40. const constructor = typedArrays[value.type]
  41. const data = Buffer.from(value.data, 'base64')
  42. if (constructor === Buffer) {
  43. return data
  44. } else if (constructor === ArrayBuffer) {
  45. return data.buffer
  46. } else if (constructor) {
  47. return new constructor(data.buffer, data.byteOffset, value.length)
  48. } else {
  49. return data
  50. }
  51. }