-
Notifications
You must be signed in to change notification settings - Fork 627
/
Copy pathsplit.ts
51 lines (41 loc) · 1.45 KB
/
split.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Transform } from 'stream';
export const splitNewLines = () => new StreamSplitter('\n'.charCodeAt(0));
/**
* Copied and simplified from src\vs\base\node\nodeStreams.ts
*
* Exception: does not include the split character in the output.
*/
export class StreamSplitter extends Transform {
private buffer: Buffer | undefined;
constructor(private readonly splitter: number) {
super();
}
override _transform(chunk: Buffer, _encoding: string, callback: (error?: Error | null, data?: any) => void): void {
if (!this.buffer) {
this.buffer = chunk;
} else {
this.buffer = Buffer.concat([this.buffer, chunk]);
}
let offset = 0;
while (offset < this.buffer.length) {
const index = this.buffer.indexOf(this.splitter, offset);
if (index === -1) {
break;
}
this.push(this.buffer.subarray(offset, index));
offset = index + 1;
}
this.buffer = offset === this.buffer.length ? undefined : this.buffer.subarray(offset);
callback();
}
override _flush(callback: (error?: Error | null, data?: any) => void): void {
if (this.buffer) {
this.push(this.buffer);
}
callback();
}
}