UNPKG

935 BJavaScriptView Raw
1const { assert } = require('./index');
2const { WORD_CHARS } = require('../CONST');
3
4class HexStream {
5 constructor(hex) {
6 this.string = hex;
7 this.index = hex.startsWith('0x') ? 2 : 0;
8 }
9
10 eof() {
11 return this.index >= this.string.length;
12 }
13
14 read(length, alignLeft = false) {
15 assert(Number.isInteger(length) && 0 <= length, {
16 message: 'invalid length',
17 expect: 'integer && >= 0',
18 got: length,
19 stream: this,
20 });
21
22 const size = Math.ceil(length / WORD_CHARS) * WORD_CHARS;
23 const string = alignLeft
24 ? this.string.substr(this.index, length)
25 : this.string.substr(this.index + (size - length), length);
26
27 assert(string.length === length, {
28 message: 'length not match',
29 expect: length,
30 got: string.length,
31 stream: this,
32 });
33
34 this.index += size;
35 return string;
36 }
37}
38
39module.exports = HexStream;