Skip to content

Commit 9feda79

Browse files
Merge pull request #7 from flitsmeister/feature/fix-underflow
Handle world boundaries
2 parents bad8f44 + 411f8b3 commit 9feda79

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Sources/FlitsGeohashC/flitsgeohash.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ GEOHASH_get_neighbors(const char* hash)
109109
void
110110
GEOHASH_free_neighbors(GEOHASH_neighbors *neighbors)
111111
{
112+
if (neighbors == NULL)
113+
return;
114+
112115
free(neighbors->north);
113116
free(neighbors->east);
114117
free(neighbors->west);
@@ -127,7 +130,18 @@ GEOHASH_get_adjacent(const char* hash, GEOHASH_direction dir)
127130
const char *border_table, *neighbor_table;
128131
char *base, *refined_base, *ptr, last;
129132

133+
if (hash == NULL)
134+
return NULL;
135+
130136
len = strlen(hash);
137+
if (len == 0) {
138+
base = (char *)malloc(sizeof(char));
139+
if (base == NULL)
140+
return NULL;
141+
base[0] = '\0';
142+
return base;
143+
}
144+
131145
last = tolower(hash[len - 1]);
132146
idx = dir * 2 + (len % 2);
133147

Tests/FlitsGeohashSwiftTests/CorrectnessTests.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,21 @@ final class CorrectnessTests: XCTestCase {
2929
XCTAssertEqual(Geohash.adjacent(hash: Fixture.hash11, direction: .west), Fixture.west)
3030
}
3131

32+
func testGeohashAdjacentHandlesWorldBoundaryHashes() {
33+
let cases: [(hash: String, direction: Geohash.Direction, expected: String)] = [
34+
("bpbpbp", .north, "000000"),
35+
("zzzzzz", .east, "bpbpbp"),
36+
("000000", .south, "bpbpbp"),
37+
("000000", .west, "pbpbpb")
38+
]
39+
40+
for testCase in cases {
41+
let adjacent = Geohash.adjacent(hash: testCase.hash, direction: testCase.direction)
42+
43+
XCTAssertEqual(adjacent, testCase.expected)
44+
}
45+
}
46+
3247
func testGeohashNeighborsAndNeighborSets() {
3348
let neighbors = Geohash.neighbors(hash: Fixture.hash11)
3449

@@ -47,6 +62,24 @@ final class CorrectnessTests: XCTestCase {
4762
)
4863
}
4964

65+
func testGeohashNeighborsHandlesOriginAdjacentGeneratedHashes() {
66+
let originAdjacentHashes = Geohash.hashesForRegion(
67+
centerCoordinate: .init(latitude: 0, longitude: 0),
68+
latitudeDelta: 0.01,
69+
longitudeDelta: 0.01,
70+
length: 6
71+
)
72+
73+
XCTAssertEqual(Set(originAdjacentHashes), Set(["7zzzzz", "ebpbpb", "kpbpbp", "s00000"]))
74+
75+
for hash in originAdjacentHashes {
76+
let neighbors = Geohash.neighbors(hash: hash)
77+
78+
XCTAssertTrue(neighbors.allNeighbors.allSatisfy { $0.count == hash.count })
79+
XCTAssertTrue(neighbors.allNeighbors.allSatisfy { !$0.isEmpty })
80+
}
81+
}
82+
5083
func testGeohashHashesForRegion() {
5184
let hashes = Geohash.hashesForRegion(
5285
centerCoordinate: Fixture.coordinate,

0 commit comments

Comments
 (0)