Skip to content

Commit 4b528d9

Browse files
committed
resolve comment
1 parent 70804ee commit 4b528d9

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

packages/firestore/src/util/misc.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -93,23 +93,19 @@ export function compareUtf8Strings(left: string, right: string): number {
9393
// UTF-8 encode the character at index i for byte comparison.
9494
const leftBytes = encoder.encode(getUtf8SafeSubstring(left, i));
9595
const rightBytes = encoder.encode(getUtf8SafeSubstring(right, i));
96-
for (
97-
let j = 0;
98-
j < Math.min(leftBytes.length, rightBytes.length);
99-
j++
100-
) {
101-
const comp = primitiveComparator(leftBytes[j], rightBytes[j]);
102-
if (comp !== 0) {
103-
return comp;
104-
}
96+
97+
const comp = compareByteArrays(leftBytes, rightBytes);
98+
if (comp !== 0) {
99+
return comp;
100+
} else {
101+
// EXTREMELY RARE CASE: Code points differ, but their UTF-8 byte
102+
// representations are identical. This can happen with malformed input
103+
// (invalid surrogate pairs). The backend also actively prevents invalid
104+
// surrogates as INVALID_ARGUMENT errors, so we almost never receive
105+
// invalid strings from backend.
106+
// Fallback to code point comparison for graceful handling.
107+
return primitiveComparator(leftCodePoint, rightCodePoint);
105108
}
106-
// EXTREMELY RARE CASE: Code points differ, but their UTF-8 byte
107-
// representations are identical. This can happen with malformed input
108-
// (invalid surrogate pairs). The backend also actively prevents invalid
109-
// surrogates as INVALID_ARGUMENT errors, so we almost never receive
110-
// invalid strings from backend.
111-
// Fallback to code point comparison for graceful handling.
112-
return primitiveComparator(leftCodePoint, rightCodePoint);
113109
}
114110
}
115111
// Increment by 2 for surrogate pairs, 1 otherwise
@@ -131,6 +127,15 @@ function getUtf8SafeSubstring(str: string, index: number): string {
131127
}
132128
}
133129

130+
function compareByteArrays(left: Uint8Array, right: Uint8Array): number {
131+
for (let i = 0; i < left.length && i < right.length; ++i) {
132+
if (left[i] !== right[i]) {
133+
return primitiveComparator(left[i], right[i]);
134+
}
135+
}
136+
return primitiveComparator(left.length, right.length);
137+
}
138+
134139
export interface Iterable<V> {
135140
forEach: (cb: (v: V) => void) => void;
136141
}

0 commit comments

Comments
 (0)