Skip to content

Commit 12550a3

Browse files
committed
fix geohash's comparison according to base32 encoded comparison
1 parent cdf0b9b commit 12550a3

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/main/java/ch/hsr/geohash/GeoHash.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,11 @@ private long maskLastNBits(long value, long n) {
514514

515515
@Override
516516
public int compareTo(GeoHash o) {
517-
return new Long(bits).compareTo(o.bits);
517+
int bitsCmp = Long.compare(bits ^ FIRST_BIT_FLAGGED, o.bits ^ FIRST_BIT_FLAGGED);
518+
if (bitsCmp != 0){
519+
return bitsCmp;
520+
} else {
521+
return Integer.compare(significantBits, o.significantBits);
522+
}
518523
}
519524
}

src/test/java/ch/hsr/geohash/GeoHashTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,4 +536,28 @@ public void testStepsBetween() {
536536
assertEquals(steps, lonLess + latLess + latMore + lonMore + inBbox - latLessLonMore - latMoreLonLess - 1);
537537

538538
}
539+
540+
@Test
541+
public void testCompareTo() {
542+
GeoHash prevHash = null;
543+
for (int i = 0; i < 1000000; i++) {
544+
double latitude = rand.nextDouble() * 180 - 90;
545+
double longitude = rand.nextDouble() * 360 - 180;
546+
int numberOfBits = rand.nextInt(6) * 10 + 10;
547+
GeoHash hash = GeoHash.withBitPrecision(latitude, longitude, numberOfBits);
548+
if (i >= 1) {
549+
String prevHashBase32 = prevHash.toBase32();
550+
String hashBase32 = hash.toBase32();
551+
String errorMessage = String.format("prev: %s, cur: %s", prevHashBase32, hashBase32);
552+
if (prevHashBase32.compareTo(hashBase32) < 0) {
553+
assertTrue(errorMessage, prevHash.compareTo(hash) < 0);
554+
} else if (prevHashBase32.compareTo(hashBase32) > 0) {
555+
assertTrue(errorMessage, prevHash.compareTo(hash) > 0);
556+
} else {
557+
assertTrue(errorMessage, prevHash.compareTo(hash) == 0);
558+
}
559+
}
560+
prevHash = hash;
561+
}
562+
}
539563
}

0 commit comments

Comments
 (0)