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.
|
|
|
|
*
|
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
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { repeat } from "@std/bytes/repeat";
|
2024-05-06 03:28:15 +00:00
|
|
|
* import { assertEquals } from "@std/assert/assert-equals";
|
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
|
|
|
*
|
2024-05-06 03:28:15 +00:00
|
|
|
* const result = repeat(source, 3);
|
2024-04-16 06:59:52 +00:00
|
|
|
*
|
2024-05-06 03:28:15 +00:00
|
|
|
* assertEquals(result, new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 2]));
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @example Zero count
|
|
|
|
* ```ts
|
|
|
|
* import { repeat } from "@std/bytes/repeat";
|
|
|
|
* import { assertEquals } from "@std/assert/assert-equals";
|
|
|
|
*
|
|
|
|
* const source = new Uint8Array([0, 1, 2]);
|
|
|
|
*
|
|
|
|
* const result = repeat(source, 0);
|
2024-04-16 06:59:52 +00:00
|
|
|
*
|
2024-05-06 03:28:15 +00:00
|
|
|
* assertEquals(result, new Uint8Array());
|
2022-11-29 06:01:21 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function repeat(source: Uint8Array, count: number): Uint8Array {
|
2024-04-17 05:09:24 +00:00
|
|
|
if (count < 0 || !Number.isInteger(count)) {
|
|
|
|
throw new RangeError("Count must be a non-negative integer");
|
2022-11-29 06:01:21 +00:00
|
|
|
}
|
|
|
|
|
2024-04-17 05:01:37 +00:00
|
|
|
const repeated = new Uint8Array(source.length * count);
|
|
|
|
let offset = 0;
|
2022-11-29 06:01:21 +00:00
|
|
|
|
2024-04-17 05:01:37 +00:00
|
|
|
while (offset < repeated.length) {
|
|
|
|
offset += copy(source, repeated, offset);
|
2022-11-29 06:01:21 +00:00
|
|
|
}
|
|
|
|
|
2024-04-17 05:01:37 +00:00
|
|
|
return repeated;
|
2022-11-29 06:01:21 +00:00
|
|
|
}
|