bufio.ts 21.4 KB
Newer Older
R
Ryan Dahl 已提交
1
// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go
R
Ryan Dahl 已提交
2 3 4 5
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

6 7
type Reader = Deno.Reader;
type Writer = Deno.Writer;
8
type SyncWriter = Deno.SyncWriter;
9
import { charCode, copyBytes } from "./util.ts";
10
import { assert } from "../testing/asserts.ts";
R
Ryan Dahl 已提交
11 12 13 14

const DEFAULT_BUF_SIZE = 4096;
const MIN_BUF_SIZE = 16;
const MAX_CONSECUTIVE_EMPTY_READS = 100;
R
Ryan Dahl 已提交
15 16
const CR = charCode("\r");
const LF = charCode("\n");
R
Ryan Dahl 已提交
17

18 19 20 21 22 23 24
export class BufferFullError extends Error {
  name = "BufferFullError";
  constructor(public partial: Uint8Array) {
    super("Buffer full");
  }
}

25 26
export class PartialReadError extends Deno.errors.UnexpectedEof {
  name = "PartialReadError";
K
Kitson Kelly 已提交
27
  partial?: Uint8Array;
28
  constructor() {
29
    super("Encountered UnexpectedEof, data only partially read");
30 31 32 33 34 35 36 37
  }
}

/** Result type returned by of BufReader.readLine(). */
export interface ReadLineResult {
  line: Uint8Array;
  more: boolean;
}
R
Ryan Dahl 已提交
38

R
Ryan Dahl 已提交
39 40
/** BufReader implements buffering for a Reader object. */
export class BufReader implements Reader {
41 42
  private buf!: Uint8Array;
  private rd!: Reader; // Reader provided by caller.
R
Ryan Dahl 已提交
43 44
  private r = 0; // buf read position.
  private w = 0; // buf write position.
45 46 47
  private eof = false;
  // private lastByte: number;
  // private lastCharSize: number;
R
Ryan Dahl 已提交
48

49
  /** return new BufReader unless r is BufReader */
50
  static create(r: Reader, size: number = DEFAULT_BUF_SIZE): BufReader {
51 52 53
    return r instanceof BufReader ? r : new BufReader(r, size);
  }

54
  constructor(rd: Reader, size: number = DEFAULT_BUF_SIZE) {
R
Ryan Dahl 已提交
55 56 57
    if (size < MIN_BUF_SIZE) {
      size = MIN_BUF_SIZE;
    }
R
Ryan Dahl 已提交
58
    this._reset(new Uint8Array(size), rd);
R
Ryan Dahl 已提交
59 60 61
  }

  /** Returns the size of the underlying buffer in bytes. */
R
Ryan Dahl 已提交
62
  size(): number {
R
Ryan Dahl 已提交
63 64 65
    return this.buf.byteLength;
  }

R
Ryan Dahl 已提交
66 67 68 69
  buffered(): number {
    return this.w - this.r;
  }

R
Ryan Dahl 已提交
70
  // Reads a new chunk into the buffer.
R
Ryan Dahl 已提交
71
  private async _fill(): Promise<void> {
R
Ryan Dahl 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
    // Slide existing data to beginning.
    if (this.r > 0) {
      this.buf.copyWithin(0, this.r, this.w);
      this.w -= this.r;
      this.r = 0;
    }

    if (this.w >= this.buf.byteLength) {
      throw Error("bufio: tried to fill full buffer");
    }

    // Read new data: try a limited number of times.
    for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) {
85 86
      const rr = await this.rd.read(this.buf.subarray(this.w));
      if (rr === Deno.EOF) {
87
        this.eof = true;
R
Ryan Dahl 已提交
88
        return;
R
Ryan Dahl 已提交
89
      }
90 91 92
      assert(rr >= 0, "negative read");
      this.w += rr;
      if (rr > 0) {
R
Ryan Dahl 已提交
93
        return;
R
Ryan Dahl 已提交
94 95
      }
    }
96 97 98 99

    throw new Error(
      `No progress after ${MAX_CONSECUTIVE_EMPTY_READS} read() calls`
    );
R
Ryan Dahl 已提交
100 101 102 103 104
  }

  /** Discards any buffered data, resets all state, and switches
   * the buffered reader to read from r.
   */
R
Ryan Dahl 已提交
105
  reset(r: Reader): void {
R
Ryan Dahl 已提交
106 107 108
    this._reset(this.buf, r);
  }

R
Ryan Dahl 已提交
109
  private _reset(buf: Uint8Array, rd: Reader): void {
R
Ryan Dahl 已提交
110 111
    this.buf = buf;
    this.rd = rd;
112 113 114
    this.eof = false;
    // this.lastByte = -1;
    // this.lastCharSize = -1;
R
Ryan Dahl 已提交
115 116
  }

R
Ryan Dahl 已提交
117 118 119 120 121 122
  /** reads data into p.
   * It returns the number of bytes read into p.
   * The bytes are taken from at most one Read on the underlying Reader,
   * hence n may be less than len(p).
   * To read exactly len(p) bytes, use io.ReadFull(b, p).
   */
123 124
  async read(p: Uint8Array): Promise<number | Deno.EOF> {
    let rr: number | Deno.EOF = p.byteLength;
125
    if (p.byteLength === 0) return rr;
R
Ryan Dahl 已提交
126 127 128 129 130

    if (this.r === this.w) {
      if (p.byteLength >= this.buf.byteLength) {
        // Large read, empty buffer.
        // Read directly into p to avoid copy.
131
        const rr = await this.rd.read(p);
132 133
        const nread = rr === Deno.EOF ? 0 : rr;
        assert(nread >= 0, "negative read");
134 135 136 137
        // if (rr.nread > 0) {
        //   this.lastByte = p[rr.nread - 1];
        //   this.lastCharSize = -1;
        // }
R
Ryan Dahl 已提交
138 139
        return rr;
      }
140

R
Ryan Dahl 已提交
141 142 143 144
      // One read.
      // Do not use this.fill, which will loop.
      this.r = 0;
      this.w = 0;
145
      rr = await this.rd.read(this.buf);
146 147 148
      if (rr === 0 || rr === Deno.EOF) return rr;
      assert(rr >= 0, "negative read");
      this.w += rr;
R
Ryan Dahl 已提交
149 150 151
    }

    // copy as much as we can
152 153
    const copied = copyBytes(p, this.buf.subarray(this.r, this.w), 0);
    this.r += copied;
154 155
    // this.lastByte = this.buf[this.r - 1];
    // this.lastCharSize = -1;
156
    return copied;
R
Ryan Dahl 已提交
157 158
  }

159 160 161 162 163 164 165 166 167 168 169 170
  /** reads exactly `p.length` bytes into `p`.
   *
   * If successful, `p` is returned.
   *
   * If the end of the underlying stream has been reached, and there are no more
   * bytes available in the buffer, `readFull()` returns `EOF` instead.
   *
   * An error is thrown if some bytes could be read, but not enough to fill `p`
   * entirely before the underlying stream reported an error or EOF. Any error
   * thrown will have a `partial` property that indicates the slice of the
   * buffer that has been successfully filled with data.
   *
171 172
   * Ported from https://golang.org/pkg/io/#ReadFull
   */
173
  async readFull(p: Uint8Array): Promise<Uint8Array | Deno.EOF> {
174 175 176 177
    let bytesRead = 0;
    while (bytesRead < p.length) {
      try {
        const rr = await this.read(p.subarray(bytesRead));
178
        if (rr === Deno.EOF) {
179
          if (bytesRead === 0) {
180
            return Deno.EOF;
181
          } else {
182
            throw new PartialReadError();
183 184
          }
        }
185
        bytesRead += rr;
186 187 188 189
      } catch (err) {
        err.partial = p.subarray(0, bytesRead);
        throw err;
      }
190
    }
191
    return p;
192 193
  }

194
  /** Returns the next byte [0, 255] or `EOF`. */
195
  async readByte(): Promise<number | Deno.EOF> {
R
Ryan Dahl 已提交
196
    while (this.r === this.w) {
197
      if (this.eof) return Deno.EOF;
R
Ryan Dahl 已提交
198
      await this._fill(); // buffer is empty.
R
Ryan Dahl 已提交
199 200 201
    }
    const c = this.buf[this.r];
    this.r++;
202
    // this.lastByte = c;
R
Ryan Dahl 已提交
203 204
    return c;
  }
R
Ryan Dahl 已提交
205 206 207 208

  /** readString() reads until the first occurrence of delim in the input,
   * returning a string containing the data up to and including the delimiter.
   * If ReadString encounters an error before finding a delimiter,
209 210 211
   * it returns the data read before the error and the error itself
   * (often io.EOF).
   * ReadString returns err != nil if and only if the returned data does not end
212
   * in delim.
R
Ryan Dahl 已提交
213 214
   * For simple uses, a Scanner may be more convenient.
   */
215
  async readString(delim: string): Promise<string | Deno.EOF> {
216
    if (delim.length !== 1) {
217
      throw new Error("Delimiter should be a single character");
218
    }
219
    const buffer = await this.readSlice(delim.charCodeAt(0));
220 221
    if (buffer == Deno.EOF) return Deno.EOF;
    return new TextDecoder().decode(buffer);
R
Ryan Dahl 已提交
222
  }
R
Ryan Dahl 已提交
223

224 225
  /** `readLine()` is a low-level line-reading primitive. Most callers should
   * use `readString('\n')` instead or use a Scanner.
R
Ryan Dahl 已提交
226
   *
227 228
   * `readLine()` tries to return a single line, not including the end-of-line
   * bytes. If the line was too long for the buffer then `more` is set and the
R
Ryan Dahl 已提交
229
   * beginning of the line is returned. The rest of the line will be returned
230
   * from future calls. `more` will be false when returning the last fragment
R
Ryan Dahl 已提交
231
   * of the line. The returned buffer is only valid until the next call to
232
   * `readLine()`.
R
Ryan Dahl 已提交
233
   *
234 235 236 237 238 239 240 241 242 243 244
   * The text returned from ReadLine does not include the line end ("\r\n" or
   * "\n").
   *
   * When the end of the underlying stream is reached, the final bytes in the
   * stream are returned. No indication or error is given if the input ends
   * without a final line end. When there are no more trailing bytes to read,
   * `readLine()` returns the `EOF` symbol.
   *
   * Calling `unreadByte()` after `readLine()` will always unread the last byte
   * read (possibly a character belonging to the line end) even if that byte is
   * not part of the line returned by `readLine()`.
R
Ryan Dahl 已提交
245
   */
246 247
  async readLine(): Promise<ReadLineResult | Deno.EOF> {
    let line: Uint8Array | Deno.EOF;
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

    try {
      line = await this.readSlice(LF);
    } catch (err) {
      let { partial } = err;
      assert(
        partial instanceof Uint8Array,
        "bufio: caught error from `readSlice()` without `partial` property"
      );

      // Don't throw if `readSlice()` failed with `BufferFullError`, instead we
      // just return whatever is available and set the `more` flag.
      if (!(err instanceof BufferFullError)) {
        throw err;
      }
R
Ryan Dahl 已提交
263 264

      // Handle the case where "\r\n" straddles the buffer.
265 266 267 268 269
      if (
        !this.eof &&
        partial.byteLength > 0 &&
        partial[partial.byteLength - 1] === CR
      ) {
R
Ryan Dahl 已提交
270 271 272 273
        // Put the '\r' back on buf and drop it from line.
        // Let the next call to ReadLine check for "\r\n".
        assert(this.r > 0, "bufio: tried to rewind past start of buffer");
        this.r--;
274
        partial = partial.subarray(0, partial.byteLength - 1);
R
Ryan Dahl 已提交
275
      }
276 277 278 279

      return { line: partial, more: !this.eof };
    }

280 281
    if (line === Deno.EOF) {
      return Deno.EOF;
R
Ryan Dahl 已提交
282 283 284
    }

    if (line.byteLength === 0) {
285
      return { line, more: false };
R
Ryan Dahl 已提交
286 287 288 289 290 291 292 293 294
    }

    if (line[line.byteLength - 1] == LF) {
      let drop = 1;
      if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {
        drop = 2;
      }
      line = line.subarray(0, line.byteLength - drop);
    }
295
    return { line, more: false };
R
Ryan Dahl 已提交
296 297
  }

298
  /** `readSlice()` reads until the first occurrence of `delim` in the input,
R
Ryan Dahl 已提交
299
   * returning a slice pointing at the bytes in the buffer. The bytes stop
300 301 302 303 304 305 306 307 308 309 310 311 312
   * being valid at the next read.
   *
   * If `readSlice()` encounters an error before finding a delimiter, or the
   * buffer fills without finding a delimiter, it throws an error with a
   * `partial` property that contains the entire buffer.
   *
   * If `readSlice()` encounters the end of the underlying stream and there are
   * any bytes left in the buffer, the rest of the buffer is returned. In other
   * words, EOF is always treated as a delimiter. Once the buffer is empty,
   * it returns `EOF`.
   *
   * Because the data returned from `readSlice()` will be overwritten by the
   * next I/O operation, most clients should use `readString()` instead.
R
Ryan Dahl 已提交
313
   */
314
  async readSlice(delim: number): Promise<Uint8Array | Deno.EOF> {
R
Ryan Dahl 已提交
315
    let s = 0; // search start index
316
    let slice: Uint8Array | undefined;
317

R
Ryan Dahl 已提交
318 319 320 321 322
    while (true) {
      // Search buffer.
      let i = this.buf.subarray(this.r + s, this.w).indexOf(delim);
      if (i >= 0) {
        i += s;
323
        slice = this.buf.subarray(this.r, this.r + i + 1);
R
Ryan Dahl 已提交
324 325 326 327
        this.r += i + 1;
        break;
      }

328 329 330
      // EOF?
      if (this.eof) {
        if (this.r === this.w) {
331
          return Deno.EOF;
332 333
        }
        slice = this.buf.subarray(this.r, this.w);
R
Ryan Dahl 已提交
334 335 336 337 338 339 340
        this.r = this.w;
        break;
      }

      // Buffer full?
      if (this.buffered() >= this.buf.byteLength) {
        this.r = this.w;
341
        throw new BufferFullError(this.buf);
R
Ryan Dahl 已提交
342 343 344 345
      }

      s = this.w - this.r; // do not rescan area we scanned before

346 347 348 349
      // Buffer is not full.
      try {
        await this._fill();
      } catch (err) {
350
        err.partial = slice;
351 352
        throw err;
      }
R
Ryan Dahl 已提交
353 354 355
    }

    // Handle last byte, if any.
356 357 358 359 360
    // const i = slice.byteLength - 1;
    // if (i >= 0) {
    //   this.lastByte = slice[i];
    //   this.lastCharSize = -1
    // }
R
Ryan Dahl 已提交
361

362
    return slice;
R
Ryan Dahl 已提交
363
  }
R
Ryan Dahl 已提交
364

365 366 367 368 369 370 371 372 373 374
  /** `peek()` returns the next `n` bytes without advancing the reader. The
   * bytes stop being valid at the next read call.
   *
   * When the end of the underlying stream is reached, but there are unread
   * bytes left in the buffer, those bytes are returned. If there are no bytes
   * left in the buffer, it returns `EOF`.
   *
   * If an error is encountered before `n` bytes are available, `peek()` throws
   * an error with the `partial` property set to a slice of the buffer that
   * contains the bytes that were available before the error occurred.
R
Ryan Dahl 已提交
375
   */
376
  async peek(n: number): Promise<Uint8Array | Deno.EOF> {
R
Ryan Dahl 已提交
377 378 379 380
    if (n < 0) {
      throw Error("negative count");
    }

381 382 383 384 385 386 387 388 389
    let avail = this.w - this.r;
    while (avail < n && avail < this.buf.byteLength && !this.eof) {
      try {
        await this._fill();
      } catch (err) {
        err.partial = this.buf.subarray(this.r, this.w);
        throw err;
      }
      avail = this.w - this.r;
R
Ryan Dahl 已提交
390 391
    }

392
    if (avail === 0 && this.eof) {
393
      return Deno.EOF;
394 395 396 397
    } else if (avail < n && this.eof) {
      return this.buf.subarray(this.r, this.r + avail);
    } else if (avail < n) {
      throw new BufferFullError(this.buf.subarray(this.r, this.w));
R
Ryan Dahl 已提交
398 399
    }

400
    return this.buf.subarray(this.r, this.r + n);
R
Ryan Dahl 已提交
401
  }
R
Ryan Dahl 已提交
402
}
R
wip  
Ryan Dahl 已提交
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
abstract class AbstractBufBase {
  buf!: Uint8Array;
  usedBufferBytes = 0;
  err: Error | null = null;

  /** Size returns the size of the underlying buffer in bytes. */
  size(): number {
    return this.buf.byteLength;
  }

  /** Returns how many bytes are unused in the buffer. */
  available(): number {
    return this.buf.byteLength - this.usedBufferBytes;
  }

  /** buffered returns the number of bytes that have been written into the
   * current buffer.
   */
  buffered(): number {
    return this.usedBufferBytes;
  }

  checkBytesWritten(numBytesWritten: number): void {
    if (numBytesWritten < this.usedBufferBytes) {
      if (numBytesWritten > 0) {
        this.buf.copyWithin(0, numBytesWritten, this.usedBufferBytes);
        this.usedBufferBytes -= numBytesWritten;
      }
      this.err = new Error("Short write");
      throw this.err;
    }
  }
}

R
wip  
Ryan Dahl 已提交
438 439 440 441 442 443 444
/** BufWriter implements buffering for an deno.Writer object.
 * If an error occurs writing to a Writer, no more data will be
 * accepted and all subsequent writes, and flush(), will return the error.
 * After all data has been written, the client should call the
 * flush() method to guarantee all data has been forwarded to
 * the underlying deno.Writer.
 */
445 446 447 448
export class BufWriter extends AbstractBufBase implements Writer {
  /** return new BufWriter unless writer is BufWriter */
  static create(writer: Writer, size: number = DEFAULT_BUF_SIZE): BufWriter {
    return writer instanceof BufWriter ? writer : new BufWriter(writer, size);
449 450
  }

451 452
  constructor(private writer: Writer, size: number = DEFAULT_BUF_SIZE) {
    super();
R
Ryan Dahl 已提交
453 454 455 456 457 458 459
    if (size <= 0) {
      size = DEFAULT_BUF_SIZE;
    }
    this.buf = new Uint8Array(size);
  }

  /** Discards any unflushed buffered data, clears any error, and
460
   * resets buffer to write its output to w.
R
Ryan Dahl 已提交
461 462 463
   */
  reset(w: Writer): void {
    this.err = null;
464 465
    this.usedBufferBytes = 0;
    this.writer = w;
R
Ryan Dahl 已提交
466 467 468
  }

  /** Flush writes any buffered data to the underlying io.Writer. */
469 470
  async flush(): Promise<void> {
    if (this.err !== null) throw this.err;
471
    if (this.usedBufferBytes === 0) return;
R
Ryan Dahl 已提交
472

473
    let numBytesWritten = 0;
R
Ryan Dahl 已提交
474
    try {
475 476 477
      numBytesWritten = await this.writer.write(
        this.buf.subarray(0, this.usedBufferBytes)
      );
R
Ryan Dahl 已提交
478
    } catch (e) {
479 480
      this.err = e;
      throw e;
R
Ryan Dahl 已提交
481 482
    }

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    this.checkBytesWritten(numBytesWritten);

    this.usedBufferBytes = 0;
  }

  /** Writes the contents of `data` into the buffer.  If the contents won't fully
   * fit into the buffer, those bytes that can are copied into the buffer, the
   * buffer is the flushed to the writer and the remaining bytes are copied into
   * the now empty buffer.
   *
   * @return the number of bytes written to the buffer.
   */
  async write(data: Uint8Array): Promise<number> {
    if (this.err !== null) throw this.err;
    if (data.length === 0) return 0;

    let totalBytesWritten = 0;
    let numBytesWritten = 0;
    while (data.byteLength > this.available()) {
      if (this.buffered() === 0) {
        // Large write, empty buffer.
        // Write directly from data to avoid copy.
        try {
          numBytesWritten = await this.writer.write(data);
        } catch (e) {
          this.err = e;
          throw e;
        }
      } else {
        numBytesWritten = copyBytes(this.buf, data, this.usedBufferBytes);
        this.usedBufferBytes += numBytesWritten;
        await this.flush();
R
Ryan Dahl 已提交
515
      }
516 517
      totalBytesWritten += numBytesWritten;
      data = data.subarray(numBytesWritten);
R
Ryan Dahl 已提交
518
    }
519

520 521 522 523
    numBytesWritten = copyBytes(this.buf, data, this.usedBufferBytes);
    this.usedBufferBytes += numBytesWritten;
    totalBytesWritten += numBytesWritten;
    return totalBytesWritten;
R
Ryan Dahl 已提交
524
  }
525
}
R
Ryan Dahl 已提交
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
/** BufWriterSync implements buffering for a deno.SyncWriter object.
 * If an error occurs writing to a SyncWriter, no more data will be
 * accepted and all subsequent writes, and flush(), will return the error.
 * After all data has been written, the client should call the
 * flush() method to guarantee all data has been forwarded to
 * the underlying deno.SyncWriter.
 */
export class BufWriterSync extends AbstractBufBase implements SyncWriter {
  /** return new BufWriterSync unless writer is BufWriterSync */
  static create(
    writer: SyncWriter,
    size: number = DEFAULT_BUF_SIZE
  ): BufWriterSync {
    return writer instanceof BufWriterSync
      ? writer
      : new BufWriterSync(writer, size);
R
Ryan Dahl 已提交
543 544
  }

545 546 547 548 549 550 551 552 553 554
  constructor(private writer: SyncWriter, size: number = DEFAULT_BUF_SIZE) {
    super();
    if (size <= 0) {
      size = DEFAULT_BUF_SIZE;
    }
    this.buf = new Uint8Array(size);
  }

  /** Discards any unflushed buffered data, clears any error, and
   * resets buffer to write its output to w.
R
Ryan Dahl 已提交
555
   */
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  reset(w: SyncWriter): void {
    this.err = null;
    this.usedBufferBytes = 0;
    this.writer = w;
  }

  /** Flush writes any buffered data to the underlying io.SyncWriter. */
  flush(): void {
    if (this.err !== null) throw this.err;
    if (this.usedBufferBytes === 0) return;

    let numBytesWritten = 0;
    try {
      numBytesWritten = this.writer.writeSync(
        this.buf.subarray(0, this.usedBufferBytes)
      );
    } catch (e) {
      this.err = e;
      throw e;
    }

    this.checkBytesWritten(numBytesWritten);

    this.usedBufferBytes = 0;
R
Ryan Dahl 已提交
580 581
  }

582 583 584 585 586 587
  /** Writes the contents of `data` into the buffer.  If the contents won't fully
   * fit into the buffer, those bytes that can are copied into the buffer, the
   * buffer is the flushed to the writer and the remaining bytes are copied into
   * the now empty buffer.
   *
   * @return the number of bytes written to the buffer.
R
Ryan Dahl 已提交
588
   */
589
  writeSync(data: Uint8Array): number {
590
    if (this.err !== null) throw this.err;
591
    if (data.length === 0) return 0;
592

593 594 595
    let totalBytesWritten = 0;
    let numBytesWritten = 0;
    while (data.byteLength > this.available()) {
596
      if (this.buffered() === 0) {
R
Ryan Dahl 已提交
597
        // Large write, empty buffer.
598
        // Write directly from data to avoid copy.
R
Ryan Dahl 已提交
599
        try {
600
          numBytesWritten = this.writer.writeSync(data);
R
Ryan Dahl 已提交
601 602
        } catch (e) {
          this.err = e;
603
          throw e;
R
Ryan Dahl 已提交
604 605
        }
      } else {
606 607 608
        numBytesWritten = copyBytes(this.buf, data, this.usedBufferBytes);
        this.usedBufferBytes += numBytesWritten;
        this.flush();
R
Ryan Dahl 已提交
609
      }
610 611
      totalBytesWritten += numBytesWritten;
      data = data.subarray(numBytesWritten);
R
Ryan Dahl 已提交
612
    }
613

614 615 616 617
    numBytesWritten = copyBytes(this.buf, data, this.usedBufferBytes);
    this.usedBufferBytes += numBytesWritten;
    totalBytesWritten += numBytesWritten;
    return totalBytesWritten;
R
Ryan Dahl 已提交
618
  }
R
wip  
Ryan Dahl 已提交
619
}
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

/** Generate longest proper prefix which is also suffix array. */
function createLPS(pat: Uint8Array): Uint8Array {
  const lps = new Uint8Array(pat.length);
  lps[0] = 0;
  let prefixEnd = 0;
  let i = 1;
  while (i < lps.length) {
    if (pat[i] == pat[prefixEnd]) {
      prefixEnd++;
      lps[i] = prefixEnd;
      i++;
    } else if (prefixEnd === 0) {
      lps[i] = 0;
      i++;
    } else {
      prefixEnd = pat[prefixEnd - 1];
    }
  }
  return lps;
}

/** Read delimited bytes from a Reader. */
export async function* readDelim(
  reader: Reader,
  delim: Uint8Array
): AsyncIterableIterator<Uint8Array> {
  // Avoid unicode problems
  const delimLen = delim.length;
  const delimLPS = createLPS(delim);

  let inputBuffer = new Deno.Buffer();
  const inspectArr = new Uint8Array(Math.max(1024, delimLen + 1));

  // Modified KMP
  let inspectIndex = 0;
  let matchIndex = 0;
  while (true) {
    const result = await reader.read(inspectArr);
    if (result === Deno.EOF) {
      // Yield last chunk.
      yield inputBuffer.bytes();
      return;
    }
    if ((result as number) < 0) {
      // Discard all remaining and silently fail.
      return;
    }
    const sliceRead = inspectArr.subarray(0, result as number);
    await Deno.writeAll(inputBuffer, sliceRead);

    let sliceToProcess = inputBuffer.bytes();
    while (inspectIndex < sliceToProcess.length) {
      if (sliceToProcess[inspectIndex] === delim[matchIndex]) {
        inspectIndex++;
        matchIndex++;
        if (matchIndex === delimLen) {
          // Full match
          const matchEnd = inspectIndex - delimLen;
          const readyBytes = sliceToProcess.subarray(0, matchEnd);
          // Copy
          const pendingBytes = sliceToProcess.slice(inspectIndex);
          yield readyBytes;
          // Reset match, different from KMP.
          sliceToProcess = pendingBytes;
          inspectIndex = 0;
          matchIndex = 0;
        }
      } else {
        if (matchIndex === 0) {
          inspectIndex++;
        } else {
          matchIndex = delimLPS[matchIndex - 1];
        }
      }
    }
    // Keep inspectIndex and matchIndex.
    inputBuffer = new Deno.Buffer(sliceToProcess);
  }
}

/** Read delimited strings from a Reader. */
export async function* readStringDelim(
  reader: Reader,
  delim: string
): AsyncIterableIterator<string> {
  const encoder = new TextEncoder();
  const decoder = new TextDecoder();
  for await (const chunk of readDelim(reader, encoder.encode(delim))) {
    yield decoder.decode(chunk);
  }
}

/** Read strings line-by-line from a Reader. */
714
// eslint-disable-next-line require-await
715 716 717 718 719
export async function* readLines(
  reader: Reader
): AsyncIterableIterator<string> {
  yield* readStringDelim(reader, "\n");
}