summaryrefslogtreecommitdiff
path: root/std/io/writers.ts
blob: 8e085c84b6c3f5b2b877c5e21fadf62f80fcb02c (plain)
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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
type Writer = Deno.Writer;
import { decode, encode } from "../encoding/utf8.ts";

/** Writer utility for buffering string chunks */
export class StringWriter implements Writer {
  private chunks: Uint8Array[] = [];
  private byteLength = 0;
  private cache: string | undefined;

  constructor(private base: string = "") {
    const c = encode(base);
    this.chunks.push(c);
    this.byteLength += c.byteLength;
  }

  write(p: Uint8Array): Promise<number> {
    this.chunks.push(p);
    this.byteLength += p.byteLength;
    this.cache = undefined;
    return Promise.resolve(p.byteLength);
  }

  toString(): string {
    if (this.cache) {
      return this.cache;
    }
    const buf = new Uint8Array(this.byteLength);
    let offs = 0;
    for (const chunk of this.chunks) {
      buf.set(chunk, offs);
      offs += chunk.byteLength;
    }
    this.cache = decode(buf);
    return this.cache;
  }
}