diff options
Diffstat (limited to 'bytes/bytes.ts')
| -rw-r--r-- | bytes/bytes.ts | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/bytes/bytes.ts b/bytes/bytes.ts index a79a9ed56..127dad1c2 100644 --- a/bytes/bytes.ts +++ b/bytes/bytes.ts @@ -1,4 +1,5 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { copyBytes } from "../io/util.ts"; /** Find first index of binary pattern from a. If not found, then return -1 **/ export function bytesFindIndex(a: Uint8Array, pat: Uint8Array): number { @@ -60,3 +61,36 @@ export function bytesHasPrefix(a: Uint8Array, prefix: Uint8Array): boolean { } return true; } + +/** + * Repeat bytes. returns a new byte slice consisting of `count` copies of `b`. + * @param b The origin bytes + * @param count The count you want to repeat. + */ +export function bytesRepeat(b: Uint8Array, count: number): Uint8Array { + if (count === 0) { + return new Uint8Array(); + } + + if (count < 0) { + throw new Error("bytes: negative repeat count"); + } else if ((b.length * count) / count !== b.length) { + throw new Error("bytes: repeat count causes overflow"); + } + + const int = Math.floor(count); + + if (int !== count) { + throw new Error("bytes: repeat count must be an integer"); + } + + const nb = new Uint8Array(b.length * count); + + let bp = copyBytes(nb, b); + + for (; bp < nb.length; bp *= 2) { + copyBytes(nb, nb.slice(0, bp), bp); + } + + return nb; +} |
