-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathatomic.js
67 lines (57 loc) · 2.12 KB
/
atomic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { isUndefined } from './common/utils'
/**
* Base class for OSC Atomic Data Types
*/
export default class Atomic {
/**
* Create an Atomic instance
* @param {*} [value] Initial value of any type
*/
constructor(value) {
/** @type {*} value */
this.value = value
/** @type {number} offset */
this.offset = 0
}
/**
* Interpret the given value of this entity as packed binary data
* @param {string} method The DataView method to write to the ArrayBuffer
* @param {number} byteLength Size of array in bytes
* @return {Uint8Array} Packed binary data
*/
pack(method, byteLength) {
if (!(method && byteLength)) {
throw new Error('OSC Atomic cant\'t be packed without given method or byteLength')
}
const data = new Uint8Array(byteLength)
const dataView = new DataView(data.buffer)
if (isUndefined(this.value)) {
throw new Error('OSC Atomic cant\'t be encoded with empty value')
}
// use DataView to write to ArrayBuffer
dataView[method](this.offset, this.value, false)
// always return binary Uint8Array after packing
return data
}
/**
* Unpack binary data from DataView according to the given format
* @param {DataView} dataView The DataView holding the binary representation of the value
* @param {string} method The DataView method to read the format from the ArrayBuffer
* @param {number} byteLength Size of array in bytes
* @param {number} [initialOffset=0] Offset of DataView before unpacking
* @return {number} Offset after unpacking
*/
unpackWithMethod(dataView, method, byteLength, initialOffset = 0) {
if (!(dataView && method && byteLength)) {
throw new Error('OSC Atomic cant\'t be unpacked without given dataView, method or byteLength')
}
if (!(dataView instanceof DataView)) {
throw new Error('OSC Atomic expects an instance of type DataView')
}
// use DataView to read from ArrayBuffer and add offset
this.value = dataView[method](initialOffset, false)
this.offset = initialOffset + byteLength
// always return offset number after unpacking
return this.offset
}
}