Skip to content

Commit 95a542d

Browse files
committed
Compare binary files >=4MB in chunks
1 parent e1a6283 commit 95a542d

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

web/src/lib/util.ts

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,48 @@ export async function isBinaryFile(file: File): Promise<boolean> {
3535
}
3636
}
3737

38-
export async function bytesEqual(a: File, b: File): Promise<boolean> {
38+
export async function bytesEqual(
39+
a: File,
40+
b: File,
41+
chunkingThreshold: number = 4 * 1024 * 1024, // 4MB
42+
chunkSize: number = chunkingThreshold,
43+
): Promise<boolean> {
3944
if (a.size !== b.size) {
4045
return false;
4146
}
4247
if (a.size === 0) {
4348
return true;
4449
}
45-
const [bytesA, bytesB] = await Promise.all([a.arrayBuffer(), b.arrayBuffer()]);
46-
if (bytesA.byteLength === bytesB.byteLength) {
50+
51+
if (a.size <= chunkingThreshold) {
52+
// Process small files in one go
53+
const [bytesA, bytesB] = await Promise.all([a.arrayBuffer(), b.arrayBuffer()]);
54+
if (bytesA.byteLength === bytesB.byteLength) {
55+
const viewA = new Uint8Array(bytesA);
56+
const viewB = new Uint8Array(bytesB);
57+
return viewA.every((byte, index) => byte === viewB[index]);
58+
}
59+
return false;
60+
}
61+
62+
// Process large files in chunks
63+
for (let offset = 0; offset < a.size; offset += chunkSize) {
64+
const sliceA = a.slice(offset, offset + chunkSize);
65+
const sliceB = b.slice(offset, offset + chunkSize);
66+
const [bytesA, bytesB] = await Promise.all([sliceA.arrayBuffer(), sliceB.arrayBuffer()]);
67+
68+
if (bytesA.byteLength !== bytesB.byteLength) {
69+
return false;
70+
}
71+
4772
const viewA = new Uint8Array(bytesA);
4873
const viewB = new Uint8Array(bytesB);
49-
if (viewA.every((byte, index) => byte === viewB[index])) {
50-
// Files are identical
51-
return true;
74+
if (!viewA.every((byte, index) => byte === viewB[index])) {
75+
return false;
5276
}
5377
}
54-
return false;
78+
79+
return true;
5580
}
5681

5782
export function binaryFileDummyDetails(fromFile: string, toFile: string, status: FileStatus): FileDetails {

0 commit comments

Comments
 (0)