Home Reference Source Test

src/atomic/blob.js

  1. import {
  2. isBlob,
  3. isUndefined,
  4. pad,
  5. } from '../common/utils'
  6.  
  7. import Atomic from '../atomic'
  8.  
  9. /**
  10. * 8-bit bytes of arbitrary binary data OSC Atomic Data Type
  11. */
  12. export default class AtomicBlob extends Atomic {
  13. /**
  14. * Create an AtomicBlob instance
  15. * @param {Uint8Array} [value] Binary data
  16. */
  17. constructor(value) {
  18. if (value && !isBlob(value)) {
  19. throw new Error('OSC AtomicBlob constructor expects value of type Uint8Array')
  20. }
  21.  
  22. super(value)
  23. }
  24.  
  25. /**
  26. * Interpret the given blob as packed binary data
  27. * @return {Uint8Array} Packed binary data
  28. */
  29. pack() {
  30. if (isUndefined(this.value)) {
  31. throw new Error('OSC AtomicBlob can not be encoded with empty value')
  32. }
  33.  
  34. const byteLength = pad(this.value.byteLength)
  35. const data = new Uint8Array(byteLength + 4)
  36. const dataView = new DataView(data.buffer)
  37.  
  38. // an int32 size count
  39. dataView.setInt32(0, this.value.byteLength, false)
  40. // followed by 8-bit bytes of arbitrary binary data
  41. data.set(this.value, 4)
  42.  
  43. return data
  44. }
  45.  
  46. /**
  47. * Unpack binary data from DataView and read a blob
  48. * @param {DataView} dataView The DataView holding the binary representation of the blob
  49. * @param {number} [initialOffset=0] Offset of DataView before unpacking
  50. * @return {number} Offset after unpacking
  51. */
  52. unpack(dataView, initialOffset = 0) {
  53. if (!(dataView instanceof DataView)) {
  54. throw new Error('OSC AtomicBlob expects an instance of type DataView')
  55. }
  56.  
  57. const byteLength = dataView.getInt32(initialOffset, false)
  58.  
  59. /** @type {Uint8Array} value */
  60. this.value = new Uint8Array(dataView.buffer, initialOffset + 4, byteLength)
  61. /** @type {number} offset */
  62. this.offset = pad(initialOffset + 4 + byteLength)
  63.  
  64. return this.offset
  65. }
  66. }