File size: 1,314 Bytes
4cadbaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

/* Wrapper for accessing strings through sequential writes */



module.exports = class OStream {
	constructor () {
		this.buffer = "";
	}

	write (str) {
		this.buffer += str;
	}

	/* write a big-endian 32-bit integer */
	writeInt32 (i) {
		this.buffer += String.fromCharCode((i >> 24) & 0xff) + String.fromCharCode((i >> 16) & 0xff) +
			String.fromCharCode((i >> 8) & 0xff) + String.fromCharCode(i & 0xff);
	}

	/* write a big-endian 16-bit integer */
	writeInt16 (i) {
		this.buffer += String.fromCharCode((i >> 8) & 0xff) + String.fromCharCode(i & 0xff);
	}

	/* write an 8-bit integer */
	writeInt8 (i) {
		this.buffer += String.fromCharCode(i & 0xff);
	}

	/* write a MIDI-style variable-length integer

		(big-endian value in groups of 7 bits,

		with top bit set to signify that another byte follows)

	*/
	writeVarInt (i) {
		if (i < 0)
			throw new Error("OStream.writeVarInt minus number: " + i);

		const b = i & 0x7f;
		i >>= 7;
		let str = String.fromCharCode(b);

		while (i) {
			const b = i & 0x7f;
			i >>= 7;
			str = String.fromCharCode(b | 0x80) + str;
		}

		this.buffer += str;
	}

	getBuffer () {
		return this.buffer;
	}

	getArrayBuffer () {
		return Uint8Array.from(this.buffer.split("").map(c => c.charCodeAt(0))).buffer;
	}
};