2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2022-11-29 06:01:21 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
import { copy } from "./copy.ts";
|
|
|
|
|
2024-04-16 06:59:52 +00:00
|
|
|
/**
|
|
|
|
* Returns a new byte slice composed of `count` repetitions of the `source`
|
2022-11-29 06:01:21 +00:00
|
|
|
* array.
|
|
|
|
*
|
|
|
|
* If `count` is negative, a `RangeError` is thrown.
|
|
|
|
*
|
2024-04-16 06:59:52 +00:00
|
|
|
* @param source Source array to repeat.
|
|
|
|
* @param count Number of times to repeat the source array.
|
|
|
|
* @returns A new byte slice composed of `count` repetitions of the `source`
|
|
|
|
* array.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2022-11-29 06:01:21 +00:00
|
|
|
* ```ts
|
2022-12-01 04:55:43 +00:00
|
|
|
* import { repeat } from "https://deno.land/std@$STD_VERSION/bytes/repeat.ts";
|
2024-04-16 06:59:52 +00:00
|
|
|
*
|
2022-11-29 06:01:21 +00:00
|
|
|
* const source = new Uint8Array([0, 1, 2]);
|
2024-04-16 06:59:52 +00:00
|
|
|
*
|
|
|
|
* repeat(source, 3); // Uint8Array(9) [0, 1, 2, 0, 1, 2, 0, 1, 2]
|
|
|
|
*
|
|
|
|
* repeat(source, 0); // Uint8Array(0) []
|
|
|
|
*
|
|
|
|
* repeat(source, -1); // Throws `RangeError`
|
2022-11-29 06:01:21 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function repeat(source: Uint8Array, count: number): Uint8Array {
|
|
|
|
if (count === 0) {
|
|
|
|
return new Uint8Array();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (count < 0) {
|
|
|
|
throw new RangeError("bytes: negative repeat count");
|
|
|
|
}
|
|
|
|
|
2022-12-03 12:27:32 +00:00
|
|
|
if (!Number.isInteger(count)) {
|
2022-11-29 06:01:21 +00:00
|
|
|
throw new Error("bytes: repeat count must be an integer");
|
|
|
|
}
|
|
|
|
|
|
|
|
const nb = new Uint8Array(source.length * count);
|
|
|
|
|
|
|
|
let bp = copy(source, nb);
|
|
|
|
|
|
|
|
for (; bp < nb.length; bp *= 2) {
|
|
|
|
copy(nb.slice(0, bp), nb, bp);
|
|
|
|
}
|
|
|
|
|
|
|
|
return nb;
|
|
|
|
}
|