Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/extension/onboardDebug/node/copilotDebugWorker/streamSplitter.ts
13405 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
// Do not edit, from https://github.com/microsoft/vscode-js-debug/blob/272c88ddf0b806325a1c723b6369d524d6e9409b/src/common/streamSplitter.ts#L1
7
8
import { Transform } from 'stream';
9
10
/**
11
* A Transform stream that splits the input on the "splitter" substring.
12
* The resulting chunks will contain (and trail with) the splitter match.
13
* The last chunk when the stream ends will be emitted even if a splitter
14
* is not encountered.
15
*/
16
export class StreamSplitter extends Transform {
17
private prefix: Buffer[] = [];
18
private readonly splitter: number;
19
20
/** Suffix added after each split chunk. */
21
protected splitSuffix = Buffer.alloc(0);
22
23
constructor(splitter: string | number | Buffer) {
24
super();
25
if (typeof splitter === 'string' && splitter.length === 1) {
26
this.splitter = splitter.charCodeAt(0);
27
} else if (typeof splitter === 'number') {
28
this.splitter = splitter;
29
} else {
30
throw new Error('not implemented here');
31
}
32
}
33
34
override _transform(
35
chunk: Buffer,
36
_encoding: string,
37
callback: (error?: Error | null, data?: unknown) => void,
38
): void {
39
let offset = 0;
40
while (offset < chunk.length) {
41
const index = chunk.indexOf(this.splitter, offset);
42
if (index === -1) {
43
break;
44
}
45
46
const thisChunk = chunk.subarray(offset, index);
47
const toEmit =
48
this.prefix.length || this.splitSuffix.length
49
? Buffer.concat([...this.prefix, thisChunk, this.splitSuffix])
50
: thisChunk;
51
52
this.push(toEmit);
53
this.prefix.length = 0;
54
offset = index + 1;
55
}
56
57
if (offset < chunk.length) {
58
this.prefix.push(chunk.subarray(offset));
59
}
60
61
callback();
62
}
63
64
override _flush(callback: (error?: Error | null, data?: unknown) => void): void {
65
if (this.prefix.length) {
66
this.push(Buffer.concat([...this.prefix, this.splitSuffix]));
67
}
68
69
callback();
70
}
71
}
72
73