From: Lady Date: Mon, 26 Jun 2023 02:18:53 +0000 (-0700) Subject: Add arrayBufferSlice to binary.js X-Git-Tag: 0.4.0~1 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/db85724e827e633157ad1961e251ea162cc0a1be?hp=dc0583fa3a21dff2e276b012dbb910eb1165000f Add arrayBufferSlice to binary.js --- diff --git a/binary.js b/binary.js index aac9975..7105731 100644 --- a/binary.js +++ b/binary.js @@ -57,8 +57,10 @@ const binaryCodeUnitIterablePrototype = { }; const { exec: reExec } = rePrototype; +const { slice: bufferSlice } = bufferPrototype; const getBufferByteLength = Object.getOwnPropertyDescriptor(bufferPrototype, "byteLength").get; +const { slice: sharedBufferSlice } = sharedBufferPrototype; const getSharedBufferByteLength = Object.getOwnPropertyDescriptor(sharedBufferPrototype, "byteLength") .get; @@ -571,6 +573,26 @@ const sourceFromArgs = ($, $s) => "", ); +/** + * Returns a slice of the provided value according to the algorithm of + * `ArrayBuffer::slice` (or `SharedArrayBuffer::slice`). + * + * ☡ This function throws if the provided value is not an array buffer. + */ +export const arrayBufferSlice = ($, start, end, ...args) => + call( + isSharedArrayBuffer($) ? sharedBufferSlice : bufferSlice, + $, + [ + start, + end, + ...objectCreate( + argumentIterablePrototype, + { args: { value: args } }, + ), + ], + ); + /** * Returns an ArrayBuffer generated from the provided base16 string. * diff --git a/binary.test.js b/binary.test.js index 00860ed..c5c2600 100644 --- a/binary.test.js +++ b/binary.test.js @@ -16,6 +16,7 @@ import { it, } from "./dev-deps.js"; import { + arrayBufferSlice, base16Binary, base16String, base32Binary, @@ -142,6 +143,45 @@ const data = new Map([ }], ]); +describe("arrayBufferSlice", () => { + it("[[Call]] slices an `ArrayBuffer`", () => { + const baseBuffer = Uint8Array.from([2, 3, 1, 9, 8, 5]).buffer; + assertEquals( + new Uint8Array(arrayBufferSlice(baseBuffer, 1, 4)), + Uint8Array.from([3, 1, 9]), + ); + }); + + it("[[Call]] slices an `SharedArrayBuffer`", () => { + const baseBuffer = new SharedArrayBuffer(6); + new Uint8Array(baseBuffer).set([2, 3, 1, 9, 8, 5], 0); + assertEquals( + new Uint8Array(arrayBufferSlice(baseBuffer, 1, 4)), + Uint8Array.from([3, 1, 9]), + ); + }); + + it("[[Call]] throws for others", () => { + [ + undefined, + null, + true, + Symbol(), + 27, + 98n, + {}, + [], + () => {}, + new Proxy({}, {}), + "string", + new DataView(new ArrayBuffer()), + new Uint8Array(), + ].forEach((value) => + assertThrows(() => arrayBufferSlice(value, 0, 0)) + ); + }); +}); + describe("base16Binary", () => { it("[[Call]] returns the correct data", () => { assertEquals(