@@ -93,23 +93,19 @@ export function compareUtf8Strings(left: string, right: string): number {
93
93
// UTF-8 encode the character at index i for byte comparison.
94
94
const leftBytes = encoder . encode ( getUtf8SafeSubstring ( left , i ) ) ;
95
95
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 ) ;
105
108
}
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 ) ;
113
109
}
114
110
}
115
111
// Increment by 2 for surrogate pairs, 1 otherwise
@@ -131,6 +127,15 @@ function getUtf8SafeSubstring(str: string, index: number): string {
131
127
}
132
128
}
133
129
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
+
134
139
export interface Iterable < V > {
135
140
forEach : ( cb : ( v : V ) => void ) => void ;
136
141
}
0 commit comments