27
27
import io .grpc .Status ;
28
28
import io .grpc .StatusException ;
29
29
import io .grpc .StatusRuntimeException ;
30
+
31
+ import java .nio .charset .StandardCharsets ;
30
32
import java .security .SecureRandom ;
33
+ import java .sql .SQLOutput ;
31
34
import java .util .ArrayList ;
32
35
import java .util .Collection ;
33
36
import java .util .Collections ;
@@ -97,12 +100,13 @@ public static int compareUtf8Strings(String left, String right) {
97
100
// ASCII comparison
98
101
return Integer .compare (leftCodePoint , rightCodePoint );
99
102
} else {
100
- // UTF-8 encoded byte comparison, substring 2 indexes to cover surrogate pairs
101
- ByteString leftBytes =
102
- ByteString .copyFromUtf8 (left .substring (i , Math .min (i + 2 , left .length ())));
103
- ByteString rightBytes =
104
- ByteString .copyFromUtf8 (right .substring (i , Math .min (i + 2 , right .length ())));
105
- return compareByteStrings (leftBytes , rightBytes );
103
+ // substring and do UTF-8 encoded byte comparison
104
+ byte [] leftBytes = getUtf8SafeBytes (left , i );
105
+ byte [] rightBytes = getUtf8SafeBytes (right , i );
106
+ int comp = compareByteArrays (leftBytes ,rightBytes );
107
+ if (comp !=0 ) {
108
+ return comp ;
109
+ }
106
110
}
107
111
}
108
112
@@ -114,6 +118,19 @@ public static int compareUtf8Strings(String left, String right) {
114
118
return Integer .compare (left .length (), right .length ());
115
119
}
116
120
121
+ private static byte [] getUtf8SafeBytes (String str , int index ) {
122
+ int firstCodePoint = str .codePointAt (index );
123
+ String sub ;
124
+ if (firstCodePoint > 0xffff ) {
125
+ // It's a surrogate pair, return the whole pair
126
+ sub = str .substring (index , index + 2 );
127
+ } else {
128
+ // It's a single code point, return it
129
+ sub = str .substring (index , index + 1 );
130
+ }
131
+ return sub .getBytes (StandardCharsets .UTF_8 );
132
+ }
133
+
117
134
/**
118
135
* Utility function to compare longs. Note that we can't use Long.compare because it's only
119
136
* available after Android 19.
0 commit comments