Skip to main content
Home
This release is 38 versions behind 1.0.6 — the latest version of @std/bytes. Jump to latest
Works with
This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score100%
Downloads100,229/wk
Published2 years ago (0.198.0)

Utilities to manipulate Uint8Arrays that are not built-in to JavaScript

// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // This module is browser compatible. /** Copy bytes from the `src` array to the `dst` array. Returns the number of * bytes copied. * * If the `src` array is larger than what the `dst` array can hold, only the * amount of bytes that fit in the `dst` array are copied. * * An offset can be specified as the third argument that begins the copy at * that given index in the `dst` array. The offset defaults to the beginning of * the array. * * ```ts * import { copy } from "@std/bytes/copy"; * const src = new Uint8Array([9, 8, 7]); * const dst = new Uint8Array([0, 1, 2, 3, 4, 5]); * console.log(copy(src, dst)); // 3 * console.log(dst); // [9, 8, 7, 3, 4, 5] * ``` * * ```ts * import { copy } from "@std/bytes/copy"; * const src = new Uint8Array([1, 1, 1, 1]); * const dst = new Uint8Array([0, 0, 0, 0]); * console.log(copy(src, dst, 1)); // 3 * console.log(dst); // [0, 1, 1, 1] * ``` */ export function copy(src: Uint8Array, dst: Uint8Array, off = 0): number { off = Math.max(0, Math.min(off, dst.byteLength)); const dstBytesAvailable = dst.byteLength - off; if (src.byteLength > dstBytesAvailable) { src = src.subarray(0, dstBytesAvailable); } dst.set(src, off); return src.byteLength; }