File size: 1,538 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

/* Wrapper for accessing buffer through sequential reads */



module.exports = class Stream {
	constructor (buffer) {
		this.array = new Uint8Array(buffer);
		this.position = 0;
	}


	eof () {
		return this.position >= this.array.length;
	}


	read (length) {
		const result = this.array.slice(this.position, this.position + length);
		this.position += length;

		return result;
	}


	readString (length) {
		const data = Array.from(this.read(length));

		return data.map(c => String.fromCharCode(c)).join("");
	}


	// read a big-endian 32-bit integer
	readInt32 () {
		const result = (
			(this.array[this.position] << 24) +
			(this.array[this.position + 1] << 16) +
			(this.array[this.position + 2] << 8) +
			this.array[this.position + 3]);
		this.position += 4;

		return result;
	}


	// read a big-endian 16-bit integer
	readInt16 () {
		const result = (
			(this.array[this.position] << 8) +
			this.array[this.position + 1]);
		this.position += 2;

		return result;
	}


	// read an 8-bit integer
	readInt8 (signed) {
		let result = this.array[this.position];
		if (signed && result > 127)
			result -= 256;
		this.position += 1;

		return result;
	}


	/* read a MIDI-style variable-length integer
		(big-endian value in groups of 7 bits,
		with top bit set to signify that another byte follows)
	*/
	readVarInt () {
		let result = 0;
		while (true) {
			const b = this.readInt8();
			if (b & 0x80) {
				result += (b & 0x7f);
				result <<= 7;
			}
			else {
				// b is the last byte
				return result + b;
			}
		}
	}
};