forked from oraoto/pib
-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathOutputBuffer.js
57 lines (47 loc) · 1.13 KB
/
OutputBuffer.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
import { _Event } from "./_Event";
export class OutputBuffer
{
constructor(target, eventType, maxLength)
{
Object.defineProperty(this, 'target', {value: target});
Object.defineProperty(this, 'buffer', {value: []});
Object.defineProperty(this, 'eventType', {value: eventType});
Object.defineProperty(this, 'maxLength', {value: maxLength});
Object.defineProperty(this, 'decoder', {value: new TextDecoder()});
Object.defineProperty(this, 'queue', {value: new Set});
}
push(...items)
{
this.buffer.push(...items);
const end = this.buffer.length - 1;
if(this.maxLength === -1 && this.buffer[end] === 10)
{
this.flush();
}
if(this.maxLength >= 0 && this.buffer.length >= this.maxLength)
{
this.flush();
}
}
flush()
{
if(!this.buffer.length)
{
return;
}
const detail = [this.decoder.decode(new Uint8Array(this.buffer))];
const event = new _Event(this.eventType, {detail});
if(this.target['on' + this.eventType])
{
if(this.target['on' + this.eventType](event) === false)
{
return;
}
}
if(!this.target.dispatchEvent(event))
{
return;
}
this.buffer.splice(0);
}
}