fix(bytes): equals() works with subarray (#4630)

fix(bytes): `equals()` works with `.subarray()`
This commit is contained in:
Asher Gomez 2024-04-23 17:50:21 +10:00 committed by GitHub
parent d209aa3c22
commit 3149cdbc81
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 3 deletions

View File

@ -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;
}

View File

@ -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));
});