Skip to content

Commit ec37ebd

Browse files
committed
fix the failing test
1 parent 4c4d1a7 commit ec37ebd

File tree

1 file changed

+23
-6
lines changed
  • firebase-firestore/src/main/java/com/google/firebase/firestore/util

1 file changed

+23
-6
lines changed

firebase-firestore/src/main/java/com/google/firebase/firestore/util/Util.java

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@
2727
import io.grpc.Status;
2828
import io.grpc.StatusException;
2929
import io.grpc.StatusRuntimeException;
30+
31+
import java.nio.charset.StandardCharsets;
3032
import java.security.SecureRandom;
33+
import java.sql.SQLOutput;
3134
import java.util.ArrayList;
3235
import java.util.Collection;
3336
import java.util.Collections;
@@ -97,12 +100,13 @@ public static int compareUtf8Strings(String left, String right) {
97100
// ASCII comparison
98101
return Integer.compare(leftCodePoint, rightCodePoint);
99102
} 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+
}
106110
}
107111
}
108112

@@ -114,6 +118,19 @@ public static int compareUtf8Strings(String left, String right) {
114118
return Integer.compare(left.length(), right.length());
115119
}
116120

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+
117134
/**
118135
* Utility function to compare longs. Note that we can't use Long.compare because it's only
119136
* available after Android 19.

0 commit comments

Comments
 (0)