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";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
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-08 06:18:26 +00:00
|
|
|
* assertEquals(repeat(source, 3), new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 2]));
|
2024-05-06 03:28:15 +00:00
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @example Zero count
|
|
|
|
* ```ts
|
|
|
|
* import { repeat } from "@std/bytes/repeat";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2024-05-06 03:28:15 +00:00
|
|
|
*
|
|
|
|
* const source = new Uint8Array([0, 1, 2]);
|
|
|
|
*
|
2024-05-08 06:18:26 +00:00
|
|
|
* assertEquals(repeat(source, 0), 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
|
|
|
}
|