From 3149cdbc810be0a35ab14d0307f0d464a7e18f7f Mon Sep 17 00:00:00 2001 From: Asher Gomez Date: Tue, 23 Apr 2024 17:50:21 +1000 Subject: [PATCH] fix(bytes): `equals()` works with subarray (#4630) fix(bytes): `equals()` works with `.subarray()` --- bytes/equals.ts | 4 ++-- bytes/equals_test.ts | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/bytes/equals.ts b/bytes/equals.ts index e9323fedcf54..c0969612af55 100644 --- a/bytes/equals.ts +++ b/bytes/equals.ts @@ -28,8 +28,8 @@ function equalsNaive(a: Uint8Array, b: Uint8Array): boolean { function equals32Bit(a: Uint8Array, b: Uint8Array): boolean { const len = a.length; const compressible = Math.floor(len / 4); - const compressedA = new Uint32Array(a.buffer, 0, compressible); - const compressedB = new Uint32Array(b.buffer, 0, compressible); + const compressedA = new Uint32Array(a, 0, compressible); + const compressedB = new Uint32Array(b, 0, compressible); for (let i = compressible * 4; i < len; i++) { if (a[i] !== b[i]) return false; } diff --git a/bytes/equals_test.ts b/bytes/equals_test.ts index 84e26fae93a7..ad9d0fa207a8 100644 --- a/bytes/equals_test.ts +++ b/bytes/equals_test.ts @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. import { equals } from "./equals.ts"; -import { assert } from "../assert/mod.ts"; +import { assert, assertEquals, assertNotEquals } from "../assert/mod.ts"; Deno.test("equals()", () => { const v = equals(new Uint8Array([0, 1, 2, 3]), new Uint8Array([0, 1, 2, 3])); @@ -32,3 +32,19 @@ Deno.test("equals() handles randomized testing", () => { assert(!equals(arr1, arr3)); } }); + +// https://github.com/denoland/deno_std/issues/3603 +Deno.test("equals() works with .subarray()", () => { + const a = new Uint8Array(1001).subarray(1); + const b = new Uint8Array(1000); + a[0] = 123; + b[0] = 123; + assertEquals(a, b); + assert(equals(a, b)); + + const c = new Uint8Array(1001).subarray(1); + const d = new Uint8Array(1000); + c[999] = 123; + assertNotEquals(c, d); // ok + assert(!equals(c, d)); +});