diff options
author | hastri <30923193+hastri@users.noreply.github.com> | 2020-06-02 00:37:59 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-06-01 18:37:59 -0400 |
commit | b075f55d5827894de2a5df1aeae4ddd3ff86780b (patch) | |
tree | 672ecff5e759a6dbef2f1c714d887ae01cb38bdb /std/io/readers.ts | |
parent | c9aded05a6b5e4825e9be362013be74fd51e8620 (diff) |
feat(std/io): add LimitedReader (#6026)
Diffstat (limited to 'std/io/readers.ts')
-rw-r--r-- | std/io/readers.ts | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/std/io/readers.ts b/std/io/readers.ts index 10069986c..201b87cd8 100644 --- a/std/io/readers.ts +++ b/std/io/readers.ts @@ -1,4 +1,10 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + +// Based on https://github.com/golang/go/blob/0452f9460f50f0f0aba18df43dc2b31906fb66cc/src/io/io.go +// 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. + type Reader = Deno.Reader; import { encode } from "../encoding/utf8.ts"; @@ -40,3 +46,30 @@ export class MultiReader implements Reader { return result; } } + +/** + * A `LimitedReader` reads from `reader` but limits the amount of data returned to just `limit` bytes. + * Each call to `read` updates `limit` to reflect the new amount remaining. + * `read` returns `null` when `limit` <= `0` or + * when the underlying `reader` returns `null`. + */ +export class LimitedReader implements Deno.Reader { + constructor(public reader: Deno.Reader, public limit: number) {} + + async read(p: Uint8Array): Promise<number | null> { + if (this.limit <= 0) { + return null; + } + + if (p.length > this.limit) { + p = p.subarray(0, this.limit); + } + const n = await this.reader.read(p); + if (n == null) { + return null; + } + + this.limit -= n; + return n; + } +} |