File size: 1,066 Bytes
3144483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/** Frames LF-delimited bytes without decoding or consuming an incomplete final line. */
export function createBoundedLineFramer(maxBytes: number, overflowMessage: string) {
  let chunks: Buffer[] = [];
  let byteLength = 0;
  const clear = () => {
    chunks = [];
    byteLength = 0;
  };
  return {
    get pendingByteLength() {
      return byteLength;
    },
    clear,
    *push(chunk: Buffer): Generator<Buffer> {
      let offset = 0;
      while (offset < chunk.length) {
        const newline = chunk.indexOf(10, offset);
        const end = newline === -1 ? chunk.length : newline;
        byteLength += end - offset;
        if (byteLength > maxBytes) {
          throw new Error(overflowMessage);
        }
        chunks.push(chunk.subarray(offset, end));
        if (newline === -1) {
          break;
        }
        const line = Buffer.concat(chunks, byteLength);
        clear();
        offset = newline + 1;
        // A caller may retire after this frame; do not inspect later bytes until it resumes.
        yield line;
      }
    },
  };
}