Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bytes/equals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for (let i = compressible * 4; i < len; i++) {
if (a[i] !== b[i]) return false;
}
Expand Down
18 changes: 17 additions & 1 deletion bytes/equals_test.ts
Original file line number Diff line number Diff line change
@@ -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]));
Expand Down Expand Up @@ -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));
});