Skip to content
Closed
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
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,11 @@
"./rsa": {
"import": "./dist/rsa.mjs",
"require": "./dist/rsa.cjs"
},
"./equal": {
"import": "./dist/equal.mjs",
"require": "./dist/equal.cjs"
}
},
"files": [
"dist"
]
}
"files": ["dist"]
}
25 changes: 25 additions & 0 deletions src/equal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, it, expect } from "vitest";
import { safeEqual } from "./equal";

describe("safeEqualFallback", () => {
it("returns true for identical strings", () => {
expect(safeEqual("hello", "hello")).toBe(true);
});

it("returns false for different strings", () => {
expect(safeEqual("hello", "world")).toBe(false);
});

it("returns false for strings of different lengths", () => {
expect(safeEqual("short", "longer")).toBe(false);
});

it("handles empty strings", () => {
expect(safeEqual("", "")).toBe(true);
expect(safeEqual("", "a")).toBe(false);
});

it("handles similar strings", () => {
expect(safeEqual("aaaaaaaa", "aaaaaaab")).toBe(false);
});
});
15 changes: 15 additions & 0 deletions src/equal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function safeEqual(a: string, b: string): boolean {
const aBytes = new TextEncoder().encode(a);
const bBytes = new TextEncoder().encode(b);

let len = Math.max(aBytes.length, bBytes.length);
let result = BigInt(aBytes.length ^ bBytes.length);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why do we need bigint here? I think the number is enough?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

i did that to fix this warning by the ai #12 (comment)


for (let i = 0; i < len; i++) {
const aByte = i < aBytes.length ? BigInt(aBytes[i]) : 0n;
const bByte = i < bBytes.length ? BigInt(bBytes[i]) : 0n;
result |= aByte ^ bByte;
}

return result === 0n;
}