]> Lady’s Gitweb - Pisces/commitdiff
Add arrayBufferSlice to binary.js
authorLady <redacted>
Mon, 26 Jun 2023 02:18:53 +0000 (19:18 -0700)
committerLady <redacted>
Mon, 26 Jun 2023 02:18:53 +0000 (19:18 -0700)
binary.js
binary.test.js

index aac9975d17ba374caa8c14d420a0596f86047e85..71057312fc07d1557e0d6e95c0cf3ba0efd6d772 100644 (file)
--- 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.
  *
index 00860edbed74e01d98a9997fb773e0d667e84bfb..c5c2600cce71a5a6f28a19c13a180ae9461c203a 100644 (file)
@@ -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(
This page took 0.082224 seconds and 4 git commands to generate.