networklocation: move geocoder generation to C++ (scripts/) and search to Rust JNI
- Commit
fb7a7719518bb72d5a485dd3b940f6759a3ea725- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-10 02:00 UTC (3 months ago)
- Parents
a22d778
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 9cd1121f5d..889820e06c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1189,10 +1189,15 @@ dependencies = [ ] [[package]]-name = "networklocation"+name = "network_location_position_estimation_rust" version = "0.1.0" dependencies = [+ "itertools", "jni",+ "libc",+ "log",+ "rand 0.8.7",+ "ruzstd", ] [[package]]@@ -1596,6 +1601,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]]+name = "ruzstd"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fad02996bfc73da3e301efe90b1837be9ed8f4a462b6ed410aa35d00381de89f"+dependencies = [+ "twox-hash",+]+ [[package]] name = "salsa20" version = "0.11.0"@@ -1753,6 +1767,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+ [[package]] name = "stringprep" version = "0.1.5"@@ -1902,6 +1922,16 @@ dependencies = [ "cipher 0.5.2", ] +[[package]]+name = "twox-hash"+version = "1.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"+dependencies = [+ "cfg-if",+ "static_assertions",+]+ [[package]] name = "typed-builder" version = "0.21.2"
networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsindex 8c2382b6b6..7b9d18618f 100644--- a/networklocation/build.gradle.kts+++ b/networklocation/build.gradle.kts@@ -30,8 +30,9 @@ androidComponents { } } -// Native device-position estimation (weighted-centroid / inverse-variance least-// squares over the cached gs-loc beacon fixes). See networklocation/src/main/rust/.+// Native code for this module, loaded as libnetworklocation.so: RANSAC + EM multilateration+// device-position estimation over the cached gs-loc beacon fixes, AND the offline geocoder+// search over geocoder.geodb. Both live in networklocation/src/main/rust/. rustNativeLib("networklocation") // The packed geocoder DB (~1-1.5 GB) is not committed (see src/main/assets/.gitignore).@@ -74,7 +75,7 @@ val fetchGeocoderDb = tasks.register("fetchGeocoderDb") { tmp.delete() logger.warn( "WARNING: could not fetch geocoder.geodb ({}). The APK will build WITHOUT the offline " +- "geocoder DB. Generate it locally (tools/) or check {} and rebuild.",+ "geocoder DB. Generate it locally (scripts/geocoder_gen.sh) or check {} and rebuild.", e.message, geocoderDbUrl, ) }@@ -85,13 +86,6 @@ tasks.matching { it.name == "preBuild" }.configureEach { dependsOn(fetchGeocoderDb) } -// The geocoder generator runs on the JVM test classpath (GeoDb* are pure-Kotlin). The planet-// build needs a large heap; override with GEOCODER_HEAP (e.g. 100g). Normal unit tests are-// unaffected — they won't allocate near this ceiling.-tasks.withType<Test>().configureEach {- maxHeapSize = System.getenv("GEOCODER_HEAP") ?: "2g"-}- dependencies { // Compile-only stubs for the framework's unbundled provider API (com.android.location.provider). // Provided at runtime by <uses-library>; must NOT be packaged.@@ -102,11 +96,8 @@ dependencies { implementRoom(libs) // Reporting loop + IO for the gs-loc queries. implementation(libs.kotlinx.coroutines.android)- // Geocoder DB is a self-contained mmap'd binary (see geocoder/). Block compression uses- // Zstandard via zstd-jni (compress/decompress one 4096-record block fully in RAM).- implementation(libs.zstd.jni)- // kotlinx-serialization-json (from the app convention) is used only by the generator to- // parse osmium's GeoJSONSeq export.+ // The offline geocoder search runs natively (Rust/ruzstd) over the bundled geocoder.geodb+ // asset; there is no Kotlin-side DB code, so no zstd-jni / serialization deps are needed here. } protobuf {
networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.ktindex a16c2784b5..55296ae839 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt@@ -2,13 +2,12 @@ package com.vayunmathur.networklocation import android.app.Service import android.content.Intent+import android.content.res.AssetFileDescriptor import android.location.Address import android.location.GeocoderParams import android.os.IBinder import com.android.location.provider.GeocodeProvider-import com.vayunmathur.networklocation.geocoder.GeoDbAssets-import com.vayunmathur.networklocation.geocoder.GeoDbReader-import com.vayunmathur.networklocation.geocoder.GeoResult+import java.io.IOException import java.util.Locale /**@@ -16,10 +15,13 @@ import java.util.Locale * framework via the `com.android.location.service.GeocodeProvider` action; the app must be the * configured geocode provider (config_geocoderProviderPackageName) and hold INSTALL_LOCATION_PROVIDER. *- * The provider contract: return null on success (results appended to `addrs`) or an error string.+ * The search itself runs in native Rust ([GeocoderNative]) over `geocoder.geodb`, opened straight+ * from the APK asset fd. The provider contract: return null on success (results appended to+ * `addrs`) or an error string. */ class GeocodeService : Service() {- private var db: GeoDbReader? = null+ private var afd: AssetFileDescriptor? = null+ private var handle: Long = 0L private val provider: GeocodeProvider by lazy { object : GeocodeProvider() {@@ -30,9 +32,9 @@ class GeocodeService : Service() { params: GeocoderParams, addrs: MutableList<Address>, ): String? {- val reader = db ?: return "geocoder database unavailable"- val r = reader.reverse(latitude, longitude) ?: return null- addrs.add(r.toAddress(params.locale))+ if (handle == 0L) return "geocoder database unavailable"+ val flat = GeocoderNative.reverse(handle, latitude, longitude) ?: return null+ if (flat.size >= GeocoderNative.FIELDS_PER_ADDRESS) addrs.add(flat.toAddress(0, params.locale)) return null } @@ -46,9 +48,21 @@ class GeocodeService : Service() { params: GeocoderParams, addrs: MutableList<Address>, ): String? {- val reader = db ?: return "geocoder database unavailable"- for (r in forwardSearch(reader, locationName, maxResults)) {- addrs.add(r.toAddress(params.locale))+ if (handle == 0L) return "geocoder database unavailable"+ val parts = locationName.split(",").map { it.trim() }.filter { it.isNotEmpty() }+ if (parts.size < 4) return null+ val country = parts[parts.size - 1]+ val state = parts[parts.size - 2]+ val city = parts[parts.size - 3]+ val street = parts[parts.size - 4]+ val flat = GeocoderNative.forward(+ handle, country, state, city, street, maxResults.coerceIn(1, 50),+ ) ?: return null+ val stride = GeocoderNative.FIELDS_PER_ADDRESS+ var base = 0+ while (base + stride <= flat.size && addrs.size < maxResults) {+ addrs.add(flat.toAddress(base, params.locale))+ base += stride } return null }@@ -57,36 +71,39 @@ class GeocodeService : Service() { override fun onCreate() { super.onCreate()- db = GeoDbAssets.open(this)+ if (!GeocoderNative.available) return+ try {+ val fd = assets.openFd(ASSET_NAME)+ afd = fd+ handle = GeocoderNative.open(fd.parcelFileDescriptor.fd, fd.startOffset, fd.length)+ } catch (_: IOException) {+ handle = 0L+ } } override fun onBind(intent: Intent?): IBinder? = provider.binder override fun onDestroy() {- db?.close()- db = null+ if (handle != 0L) {+ GeocoderNative.close(handle)+ handle = 0L+ }+ afd?.close()+ afd = null super.onDestroy() } - /**- * Best-effort freeform forward geocoding over structured data. The DB indexes by- * country/state/city/street, so we map the trailing comma-separated components of the query- * onto those fields. Full natural-language parsing is a known limitation.- */- private fun forwardSearch(db: GeoDbReader, query: String, maxResults: Int): List<GeoResult> {- val parts = query.split(",").map { it.trim() }.filter { it.isNotEmpty() }- if (parts.size < 4) return emptyList()- val country = parts[parts.size - 1]- val state = parts[parts.size - 2]- val city = parts[parts.size - 3]- val street = parts[parts.size - 4]- return db.forward(country, state, city, street, limit = maxResults.coerceIn(1, 50))- }-- private fun GeoResult.toAddress(locale: Locale): Address {+ /** A flat result slice `[lat, lon, house, street, city, state, country, postcode]` at [base]. */+ private fun Array<String>.toAddress(base: Int, locale: Locale): Address { val a = Address(locale)- a.latitude = lat- a.longitude = lon+ a.latitude = this[base].toDoubleOrNull() ?: 0.0+ a.longitude = this[base + 1].toDoubleOrNull() ?: 0.0+ val house = this[base + 2]+ val street = this[base + 3]+ val city = this[base + 4]+ val state = this[base + 5]+ val country = this[base + 6]+ val postcode = this[base + 7] val line = listOf(house, street).filter { it.isNotEmpty() }.joinToString(" ") if (line.isNotEmpty()) a.setAddressLine(0, line) if (house.isNotEmpty()) a.featureName = house@@ -97,4 +114,8 @@ class GeocodeService : Service() { if (country.isNotEmpty()) a.countryCode = country return a }++ private companion object {+ const val ASSET_NAME = "geocoder.geodb"+ } }
networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.ktnew file mode 100644index 0000000000..3c7ddb2848--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt@@ -0,0 +1,49 @@+package com.vayunmathur.networklocation++/**+ * JNI bridge to the native offline geocoder search in the `networklocation` Rust library+ * (see networklocation/src/main/rust/src/geocoder.rs). The database itself is generated+ * offline by scripts/geocoder_gen.cpp and bundled uncompressed as the `geocoder.geodb` asset;+ * this object opens it straight from the APK asset fd (no copy to disk) and answers reverse /+ * forward geocoding queries entirely in Rust.+ *+ * Results are flat String arrays with [FIELDS_PER_ADDRESS] entries per address:+ * `[lat, lon, house, street, city, state, country, postcode]` (lat/lon formatted to 6 dp).+ *+ * The fully-qualified name MUST stay `com.vayunmathur.networklocation.GeocoderNative` so the+ * JNI symbol mangling (`Java_com_vayunmathur_networklocation_GeocoderNative_*`) matches.+ */+object GeocoderNative {+ /** Strings per address in the flat arrays returned by [reverse] / [forward]. */+ const val FIELDS_PER_ADDRESS = 8++ /** Whether the `.so` loaded. Guarded so host/unit contexts degrade gracefully. */+ val available: Boolean = runCatching { System.loadLibrary("networklocation") }.isSuccess++ /**+ * Open the geocoder DB from an APK asset file descriptor. [fd] is the (uncompressed) asset's+ * fd, [offset] its start offset within the APK; [length] is reserved for future validation.+ * Returns an opaque handle, or 0 on failure. The native side dups [fd], so the caller may+ * close its own descriptor after this returns.+ */+ external fun open(fd: Int, offset: Long, length: Long): Long++ /** Nearest stored address to (lat, lon): [FIELDS_PER_ADDRESS] strings, or null. */+ external fun reverse(handle: Long, lat: Double, lon: Double): Array<String>?++ /**+ * Addresses matching the components exactly. Returns a flat array of+ * `FIELDS_PER_ADDRESS * k` strings (k results, possibly empty), or null on error.+ */+ external fun forward(+ handle: Long,+ country: String,+ state: String,+ city: String,+ street: String,+ limit: Int,+ ): Array<String>?++ /** Free the handle and its underlying descriptor. Safe to call with 0. */+ external fun close(handle: Long)+}
networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDb.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDb.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDb.ktdeleted file mode 100644index 6b6e349b71..0000000000--- a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDb.kt+++ /dev/null@@ -1,325 +0,0 @@-package com.vayunmathur.networklocation.geocoder--import com.github.luben.zstd.Zstd-import java.io.ByteArrayOutputStream-import java.io.DataOutputStream-import java.io.File-import java.io.RandomAccessFile-import java.nio.ByteBuffer-import java.nio.channels.FileChannel-import kotlin.math.min-import kotlin.math.roundToInt--/**- * Self-contained, offline geocoder database for the whole planet.- *- * Design (see the sizing discussion): addresses are stored in **grid-primary order** so that- * - reverse geocoding (coord -> nearest address) is a cheap cell lookup + local scan, needing- * only a small sparse grid directory (no per-record spatial index), and- * - coordinates delta-compress well because neighbours are adjacent in the file.- * Every field is a dictionary index (strings deduped once), and every column is stored in- * Zstandard-compressed blocks so the reader mmaps the file and decompresses just one small block- * per access. Forward geocoding uses a second ordering (records sorted by- * country/state/city/street/house) for binary search.- *- * Coordinates are micro-degrees (1e-6 deg, ~11 cm) as Int.- *- * NOTE: this is the v1 core (correct + compressed). Two follow-up optimisations, documented- * where relevant: (a) resolve dictionary strings on-demand from the mmap instead of holding- * them in RAM, and (b) make the forward index street-granular to drop the per-record second- * ordering. Neither changes the on-disk contract for reverse geocoding.- */-object GeoDb {- const val MAGIC = 0x4D41_4745 // "MAGE"- const val VERSION = 2 // v2: per-block codec is Zstandard (was Deflate in v1)- const val BLOCK = 4096-- // Grid: 0.05-degree cells over the whole planet.- const val CELL_MICRO = 50_000- const val COLS = 360_000_000 / CELL_MICRO // 7200- const val MIN_LAT_MICRO = -90_000_000- const val MIN_LON_MICRO = -180_000_000-- val FIELD_COUNT = 6 // house, street, city, state, country, postcode- // Column indices.- const val C_LAT = 0- const val C_LON = 1- const val C_HOUSE = 2- const val C_STREET = 3- const val C_CITY = 4- const val C_STATE = 5- const val C_COUNTRY = 6- const val C_POSTCODE = 7- const val COLUMN_COUNT = 8-- fun cellIdOf(latMicro: Int, lonMicro: Int): Long {- val row = ((latMicro - MIN_LAT_MICRO) / CELL_MICRO).toLong()- val col = ((lonMicro - MIN_LON_MICRO) / CELL_MICRO).toLong()- return row * COLS + col- }-- fun toMicro(deg: Double): Int = (deg * 1_000_000.0).roundToInt()- fun toDeg(micro: Int): Double = micro / 1_000_000.0-}--data class GeoAddress(- val lat: Double,- val lon: Double,- val house: String,- val street: String,- val city: String,- val state: String,- val country: String,- val postcode: String,-)--/** A resolved reverse-geocode / forward-geocode hit. */-data class GeoResult(- val lat: Double,- val lon: Double,- val house: String,- val street: String,- val city: String,- val state: String,- val country: String,- val postcode: String,-)--// ----------------------------------------------------------------------------------------------// VarInt / zig-zag helpers.-// -----------------------------------------------------------------------------------------------private fun ByteArrayOutputStream.writeVarInt(v0: Int) {- var v = v0- while (true) {- val b = v and 0x7F- v = v ushr 7- if (v == 0) { write(b); return }- write(b or 0x80)- }-}--private fun zigzag(v: Int): Int = (v shl 1) xor (v shr 31)-internal fun unzigzag(v: Int): Int = (v ushr 1) xor -(v and 1)--internal class VarIntReader(val a: ByteArray) {- var pos = 0- fun readVarInt(): Int {- var shift = 0- var result = 0- while (true) {- val b = a[pos++].toInt() and 0xFF- result = result or ((b and 0x7F) shl shift)- if (b and 0x80 == 0) return result- shift += 7- }- }-}--/** Max standard Zstandard level; the DB is built once offline, so favour ratio over speed. */-private const val ZSTD_LEVEL = 19--/** Compress one block fully in RAM. */-private fun compress(data: ByteArray): ByteArray = Zstd.compress(data, ZSTD_LEVEL)--/** Decompress one block fully in RAM; [expected] is the known original size. */-internal fun decompress(data: ByteArray, expected: Int): ByteArray = Zstd.decompress(data, expected)--// ----------------------------------------------------------------------------------------------// Random-access byte source. Backs the reader by either a plain File or an mmap'd APK asset.-// Reads are positional (thread-safe FileChannel.read) with no 2 GB limit, so a multi-GB DB is-// fine. Values are big-endian to match DataOutputStream on the writer side.-// -----------------------------------------------------------------------------------------------interface ByteSource : AutoCloseable {- val size: Long- fun read(pos: Long, len: Int): ByteArray- fun readIntAt(pos: Long): Int = ByteBuffer.wrap(read(pos, 4)).int- fun readLongAt(pos: Long): Long = ByteBuffer.wrap(read(pos, 8)).long-}--/**- * [ByteSource] over a region of a [FileChannel] starting at [base]. Works for a whole file- * (base = 0) or an uncompressed asset embedded in the APK (base = AssetFileDescriptor.startOffset).- */-class ChannelByteSource(- private val channel: FileChannel,- private val base: Long,- override val size: Long,-) : ByteSource {- override fun read(pos: Long, len: Int): ByteArray {- val b = ByteArray(len)- val bb = ByteBuffer.wrap(b)- var read = 0- while (read < len) {- val r = channel.read(bb, base + pos + read)- if (r < 0) break- read += r- }- return b- }-- override fun close() = channel.close()-- companion object {- fun of(file: File): ChannelByteSource =- ChannelByteSource(RandomAccessFile(file, "r").channel, 0, file.length())- }-}--// ----------------------------------------------------------------------------------------------// Writer.-// -----------------------------------------------------------------------------------------------/** Column encoded as delta+zigzag+varint per block, each block Zstandard-compressed. */-private fun encodeColumn(values: IntArray, delta: Boolean): Pair<ByteArray, IntArray> {- val n = values.size- val blocks = (n + GeoDb.BLOCK - 1) / GeoDb.BLOCK- val body = ByteArrayOutputStream()- val rawLens = IntArray(blocks)- val compLens = IntArray(blocks)- for (b in 0 until blocks) {- val start = b * GeoDb.BLOCK- val end = min(start + GeoDb.BLOCK, n)- val raw = ByteArrayOutputStream()- var prev = 0- for (i in start until end) {- val v = values[i]- val enc = if (delta) v - prev else v- raw.writeVarInt(zigzag(enc))- prev = v- }- val rawBytes = raw.toByteArray()- val comp = compress(rawBytes)- rawLens[b] = rawBytes.size- compLens[b] = comp.size- body.write(comp)- }- // Section layout: [n][blocks]{rawLen,compLen}*blocks [body]- val head = ByteArrayOutputStream()- val d = DataOutputStream(head)- d.writeInt(n); d.writeInt(blocks)- for (b in 0 until blocks) { d.writeInt(rawLens[b]); d.writeInt(compLens[b]) }- val out = head.toByteArray() + body.toByteArray()- return out to compLens-}--private fun encodeDict(strings: List<String>): ByteArray {- val raw = ByteArrayOutputStream()- val d = DataOutputStream(raw)- d.writeInt(strings.size)- for (s in strings) {- val b = s.toByteArray(Charsets.UTF_8)- d.writeInt(b.size); d.write(b)- }- val rawBytes = raw.toByteArray()- val comp = compress(rawBytes)- val out = ByteArrayOutputStream()- val h = DataOutputStream(out)- h.writeInt(rawBytes.size); h.writeInt(comp.size)- out.write(comp)- return out.toByteArray()-}--class GeoDbWriter {- fun write(file: File, addresses: List<GeoAddress>) {- // Build dictionaries (sorted unique -> index is lexical order).- val houses = sortedDict(addresses) { it.house }- val streets = sortedDict(addresses) { it.street }- val cities = sortedDict(addresses) { it.city }- val states = sortedDict(addresses) { it.state }- val countries = sortedDict(addresses) { it.country }- val postcodes = sortedDict(addresses) { it.postcode }-- // Quantise + assign grid cells, then sort by cell (grid-primary order).- data class Rec(- val cell: Long, val latM: Int, val lonM: Int,- val house: Int, val street: Int, val city: Int,- val state: Int, val country: Int, val postcode: Int,- )- val recs = addresses.map { a ->- val latM = GeoDb.toMicro(a.lat)- val lonM = GeoDb.toMicro(a.lon)- Rec(- GeoDb.cellIdOf(latM, lonM), latM, lonM,- houses.index(a.house), streets.index(a.street), cities.index(a.city),- states.index(a.state), countries.index(a.country), postcodes.index(a.postcode),- )- }.sortedBy { it.cell }- val n = recs.size-- // Columns.- val lat = IntArray(n) { recs[it].latM }- val lon = IntArray(n) { recs[it].lonM }- val house = IntArray(n) { recs[it].house }- val street = IntArray(n) { recs[it].street }- val city = IntArray(n) { recs[it].city }- val state = IntArray(n) { recs[it].state }- val country = IntArray(n) { recs[it].country }- val postcode = IntArray(n) { recs[it].postcode }-- // Sparse grid directory: for each non-empty cell, its start record index.- val cellIds = ArrayList<Long>()- val cellStarts = ArrayList<Int>()- var prevCell = Long.MIN_VALUE- for (i in 0 until n) {- val c = recs[i].cell- if (c != prevCell) { cellIds.add(c); cellStarts.add(i); prevCell = c }- }-- // Forward ordering: record indices sorted by (country,state,city,street,house).- val fwd = (0 until n).sortedWith(compareBy(- { country[it] }, { state[it] }, { city[it] }, { street[it] }, { house[it] },- )).toIntArray()-- // Serialise. Sections are length-prefixed and written sequentially; the reader scans- // the length prefixes once to record each section's (offset, length) for seek-based- // block reads.- java.io.DataOutputStream(- java.io.BufferedOutputStream(java.io.FileOutputStream(file))- ).use { out ->- out.writeInt(GeoDb.MAGIC)- out.writeInt(GeoDb.VERSION)- out.writeInt(n)-- // Dictionaries (6).- for (dict in listOf(houses, streets, cities, states, countries, postcodes)) {- val bytes = encodeDict(dict.list)- out.writeInt(bytes.size); out.write(bytes)- }-- // Columns (8): lat/lon delta-encoded, index columns raw-varint.- val columns = listOf(- lat to true, lon to true,- house to false, street to false, city to false,- state to false, country to false, postcode to false,- )- for ((values, delta) in columns) {- val (bytes, _) = encodeColumn(values, delta)- out.writeInt(bytes.size); out.write(bytes)- }-- // Grid directory.- val gridBytes = ByteArrayOutputStream()- DataOutputStream(gridBytes).use { g ->- g.writeInt(cellIds.size)- for (i in cellIds.indices) { g.writeLong(cellIds[i]); g.writeInt(cellStarts[i]) }- }- out.writeInt(gridBytes.size()); gridBytes.writeTo(out)-- // Forward ordering (delta-varint, Zstandard-compressed as a single column).- val (fwdBytes, _) = encodeColumn(fwd, delta = true)- out.writeInt(fwdBytes.size); out.write(fwdBytes)- }- }-- private class Dict(val list: List<String>) {- private val idx = HashMap<String, Int>(list.size * 2).apply {- list.forEachIndexed { i, s -> put(s, i) }- }- fun index(s: String): Int = idx[s]!!- }-- private fun sortedDict(addresses: List<GeoAddress>, sel: (GeoAddress) -> String): Dict =- Dict(addresses.map(sel).toSortedSet().toList())-}
networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbAssets.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbAssets.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbAssets.ktdeleted file mode 100644index b55ef7fb62..0000000000--- a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbAssets.kt+++ /dev/null@@ -1,24 +0,0 @@-package com.vayunmathur.networklocation.geocoder--import android.content.Context-import java.io.FileInputStream-import java.io.IOException--/**- * Opens the bundled geocoder database straight from the APK asset via its file descriptor —- * no unzip, no copy to filesDir. Requires the asset to be stored uncompressed- * (`androidResources { noCompress += "geodb" }`), which lets [android.content.res.AssetManager.openFd]- * return a real fd + offset that we mmap.- */-object GeoDbAssets {- const val ASSET_NAME = "geocoder.geodb"-- /** Returns a reader, or null if the DB isn't bundled (e.g. a dev build without the fetch). */- fun open(context: Context, assetName: String = ASSET_NAME): GeoDbReader? = try {- val afd = context.assets.openFd(assetName)- val channel = FileInputStream(afd.fileDescriptor).channel- GeoDbReader(ChannelByteSource(channel, afd.startOffset, afd.length))- } catch (_: IOException) {- null- }-}
networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbReader.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbReader.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbReader.ktdeleted file mode 100644index d117409457..0000000000--- a/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbReader.kt+++ /dev/null@@ -1,278 +0,0 @@-package com.vayunmathur.networklocation.geocoder--import java.io.DataInputStream-import java.io.File-import kotlin.math.cos-import kotlin.math.min--/**- * Reader for a [GeoDb] file, backed by a [ByteSource] (a plain file or an mmap'd APK asset).- * Dictionaries and the grid directory are held in memory; address columns are read- * block-by-block on demand (positional read + decompress one block), so the bulk of the database- * is never resident. Supports reverse (coord -> address) and structured forward geocoding.- */-class GeoDbReader(private val src: ByteSource) : AutoCloseable {- /** Convenience: read from a plain file. */- constructor(file: File) : this(ChannelByteSource.of(file))-- private val n: Int-- private val dictHouse: Array<String>- private val dictStreet: Array<String>- private val dictCity: Array<String>- private val dictState: Array<String>- private val dictCountry: Array<String>- private val dictPostcode: Array<String>-- private val cellIds: LongArray- private val cellStarts: IntArray-- private val columns: Array<Column>- private val fwd: Column // record indices in forward-sorted order-- init {- var cursor = 0L- require(src.readIntAt(cursor) == GeoDb.MAGIC) { "bad magic" }; cursor += 4- require(src.readIntAt(cursor) == GeoDb.VERSION) { "bad version" }; cursor += 4- n = src.readIntAt(cursor); cursor += 4-- fun readSectionBytes(): ByteArray {- val size = src.readIntAt(cursor); cursor += 4- val b = src.read(cursor, size); cursor += size- return b- }- fun skipSection(): Long {- val size = src.readIntAt(cursor); cursor += 4- val off = cursor- cursor += size- return off- }-- dictHouse = decodeDict(readSectionBytes())- dictStreet = decodeDict(readSectionBytes())- dictCity = decodeDict(readSectionBytes())- dictState = decodeDict(readSectionBytes())- dictCountry = decodeDict(readSectionBytes())- dictPostcode = decodeDict(readSectionBytes())-- val colOffsets = LongArray(GeoDb.COLUMN_COUNT) { skipSection() }-- val grid = readSectionBytes()- DataInputStream(grid.inputStream()).use { g ->- val count = g.readInt()- cellIds = LongArray(count)- cellStarts = IntArray(count)- for (i in 0 until count) { cellIds[i] = g.readLong(); cellStarts[i] = g.readInt() }- }-- val fwdOff = skipSection()-- val delta = booleanArrayOf(true, true, false, false, false, false, false, false)- columns = Array(GeoDb.COLUMN_COUNT) { i -> Column(src, colOffsets[i], delta[i]) }- fwd = Column(src, fwdOff, delta = true)- }-- val size: Int get() = n-- // ------------------------------------------------------------------ reverse geocoding-- /** Nearest stored address to (lat, lon), or null if the DB is empty. */- fun reverse(lat: Double, lon: Double): GeoResult? {- if (n == 0) return null- val qLatM = GeoDb.toMicro(lat)- val qLonM = GeoDb.toMicro(lon)- val row = (qLatM - GeoDb.MIN_LAT_MICRO) / GeoDb.CELL_MICRO- val col = (qLonM - GeoDb.MIN_LON_MICRO) / GeoDb.CELL_MICRO- val lonScale = cos(Math.toRadians(lat))-- var bestRec = -1- var bestDist = Double.MAX_VALUE- var radius = 1- while (bestRec < 0 && radius <= 32) {- for (r in (row - radius)..(row + radius)) {- if (r < 0) continue- for (c in (col - radius)..(col + radius)) {- // On expansions past the first, only scan the new ring edge.- if (radius > 1 && r > row - radius && r < row + radius &&- c > col - radius && c < col + radius- ) continue- val cc = ((c % GeoDb.COLS) + GeoDb.COLS) % GeoDb.COLS- val cell = r.toLong() * GeoDb.COLS + cc- val gi = gridIndex(cell)- if (gi < 0) continue- val start = cellStarts[gi]- val end = if (gi + 1 < cellStarts.size) cellStarts[gi + 1] else n- for (i in start until end) {- val dLat = (columns[GeoDb.C_LAT].get(i) - qLatM).toDouble()- val dLon = (columns[GeoDb.C_LON].get(i) - qLonM).toDouble() * lonScale- val d = dLat * dLat + dLon * dLon- if (d < bestDist) { bestDist = d; bestRec = i }- }- }- }- radius++- }- return if (bestRec < 0) null else resolve(bestRec)- }-- // ------------------------------------------------------------------ forward geocoding-- /** All addresses matching the given components (exact per field). */- fun forward(- country: String,- state: String,- city: String,- street: String,- limit: Int = 20,- ): List<GeoResult> {- val kCountry = dictIndex(dictCountry, country)- val kState = dictIndex(dictState, state)- val kCity = dictIndex(dictCity, city)- val kStreet = dictIndex(dictStreet, street)- if (kCountry < 0 || kState < 0 || kCity < 0 || kStreet < 0) return emptyList()-- val target = intArrayOf(kCountry, kState, kCity, kStreet)- var lo = 0- var hi = n- while (lo < hi) {- val mid = (lo + hi) ushr 1- if (compareKey(fwd.get(mid), target) < 0) lo = mid + 1 else hi = mid- }- val out = ArrayList<GeoResult>()- var k = lo- while (k < n && out.size < limit) {- val rec = fwd.get(k)- if (compareKey(rec, target) != 0) break- out.add(resolve(rec))- k++- }- return out- }-- private fun compareKey(rec: Int, target: IntArray): Int {- var c = columns[GeoDb.C_COUNTRY].get(rec).compareTo(target[0]); if (c != 0) return c- c = columns[GeoDb.C_STATE].get(rec).compareTo(target[1]); if (c != 0) return c- c = columns[GeoDb.C_CITY].get(rec).compareTo(target[2]); if (c != 0) return c- return columns[GeoDb.C_STREET].get(rec).compareTo(target[3])- }-- // ------------------------------------------------------------------ helpers-- private fun resolve(rec: Int): GeoResult = GeoResult(- lat = GeoDb.toDeg(columns[GeoDb.C_LAT].get(rec)),- lon = GeoDb.toDeg(columns[GeoDb.C_LON].get(rec)),- house = dictHouse[columns[GeoDb.C_HOUSE].get(rec)],- street = dictStreet[columns[GeoDb.C_STREET].get(rec)],- city = dictCity[columns[GeoDb.C_CITY].get(rec)],- state = dictState[columns[GeoDb.C_STATE].get(rec)],- country = dictCountry[columns[GeoDb.C_COUNTRY].get(rec)],- postcode = dictPostcode[columns[GeoDb.C_POSTCODE].get(rec)],- )-- /** Index of [cell] in the sparse grid directory, or -1. */- private fun gridIndex(cell: Long): Int {- var lo = 0- var hi = cellIds.size - 1- while (lo <= hi) {- val mid = (lo + hi) ushr 1- val v = cellIds[mid]- when {- v < cell -> lo = mid + 1- v > cell -> hi = mid - 1- else -> return mid- }- }- return -1- }-- private fun dictIndex(dict: Array<String>, key: String): Int {- var lo = 0- var hi = dict.size - 1- while (lo <= hi) {- val mid = (lo + hi) ushr 1- val c = dict[mid].compareTo(key)- when {- c < 0 -> lo = mid + 1- c > 0 -> hi = mid - 1- else -> return mid- }- }- return -1- }-- override fun close() = src.close()-- private fun decodeDict(section: ByteArray): Array<String> {- val di = DataInputStream(section.inputStream())- val rawSize = di.readInt()- val compSize = di.readInt()- val comp = ByteArray(compSize); di.readFully(comp)- val raw = decompress(comp, rawSize)- val r = DataInputStream(raw.inputStream())- val count = r.readInt()- return Array(count) {- val len = r.readInt()- val b = ByteArray(len); r.readFully(b)- String(b, Charsets.UTF_8)- }- }-}--/**- * On-demand column reader. Parses the column header (block sizes) up front, then decompresses and- * decodes a single block per access, caching the most recently used block. [get] is- * synchronised so multiple binder threads can share one reader.- */-private class Column(- private val src: ByteSource,- sectionOffset: Long,- private val delta: Boolean,-) {- private val n: Int- private val blockCount: Int- private val rawLens: IntArray- private val compLens: IntArray- private val blockFileOffset: LongArray-- private var cachedBlock = -1- private var cachedValues: IntArray = IntArray(0)-- init {- var p = sectionOffset- n = src.readIntAt(p); p += 4- blockCount = src.readIntAt(p); p += 4- rawLens = IntArray(blockCount)- compLens = IntArray(blockCount)- for (b in 0 until blockCount) {- rawLens[b] = src.readIntAt(p); p += 4- compLens[b] = src.readIntAt(p); p += 4- }- blockFileOffset = LongArray(blockCount)- var off = p- for (b in 0 until blockCount) { blockFileOffset[b] = off; off += compLens[b] }- }-- @Synchronized- fun get(i: Int): Int {- val block = i / GeoDb.BLOCK- if (block != cachedBlock) decode(block)- return cachedValues[i - block * GeoDb.BLOCK]- }-- private fun decode(block: Int) {- val comp = src.read(blockFileOffset[block], compLens[block])- val raw = decompress(comp, rawLens[block])- val count = min(GeoDb.BLOCK, n - block * GeoDb.BLOCK)- val values = IntArray(count)- val vr = VarIntReader(raw)- var prev = 0- for (k in 0 until count) {- val v = unzigzag(vr.readVarInt())- val actual = if (delta) prev + v else v- values[k] = actual- prev = actual- }- cachedValues = values- cachedBlock = block- }-}
networklocation/src/main/rust/Cargo.toml
diff --git a/networklocation/src/main/rust/Cargo.toml b/networklocation/src/main/rust/Cargo.tomlindex 80b5d2e6a0..9429e7d932 100644--- a/networklocation/src/main/rust/Cargo.toml+++ b/networklocation/src/main/rust/Cargo.toml@@ -13,6 +13,10 @@ crate-type = ["cdylib", "rlib"] jni.workspace = true log.workspace = true itertools = "0.14"+# Runtime geocoder search reads geocoder.geodb and only ever DECOMPRESSES zstd blocks, so we+# use the pure-Rust decoder (no NDK C toolchain needed to cross-compile for Android).+ruzstd = "0.7"+libc = "0.2" [dev-dependencies] rand = { version = "0.8", features = ["small_rng"] }
networklocation/src/main/rust/src/geocoder.rs
diff --git a/networklocation/src/main/rust/src/geocoder.rs b/networklocation/src/main/rust/src/geocoder.rsnew file mode 100644index 0000000000..2dba5edbb2--- /dev/null+++ b/networklocation/src/main/rust/src/geocoder.rs@@ -0,0 +1,548 @@+//! Offline reverse/forward geocoding over the packed `geocoder.geodb`, exposed via JNI.+//!+//! The on-disk format is produced by `scripts/geocoder_gen.cpp` and mirrors the design+//! documented in `GeoDb.kt`: grid-primary record order for cheap reverse lookup, dictionary+//! -indexed fields, delta+zigzag+varint columns in per-4096-record Zstandard blocks, plus a+//! forward-sorted index for structured lookup. All ints/longs are big-endian.+//!+//! This replaces the former Kotlin `GeoDbReader`: the address columns are read block-by-block+//! straight from the mmap-friendly APK asset fd (positional `pread`, no copy to disk), and the+//! search runs in Rust for speed. Runtime is decompress-only, so we use the pure-Rust `ruzstd`+//! decoder — no NDK C toolchain needed.+//!+//! JNI result layout: each address is 8 consecutive strings+//! `[lat, lon, house, street, city, state, country, postcode]` (lat/lon formatted to 6dp).+//! `reverse` returns one address (8 strings) or null; `forward` returns 8*k strings.++use std::cmp::Ordering;+use std::fs::File;+use std::io::{Cursor, Read};+use std::os::unix::fs::FileExt;+use std::os::unix::io::FromRawFd;+use std::sync::Mutex;++use jni::objects::{JClass, JString};+use jni::sys::{jdouble, jint, jlong, jobjectArray};+use jni::JNIEnv;++const MAGIC: u32 = 0x4D41_4745;+const VERSION: u32 = 2;+const BLOCK: i32 = 4096;+const CELL_MICRO: i64 = 50_000;+const COLS: i64 = 360_000_000 / CELL_MICRO; // 7200+const MIN_LAT_MICRO: i32 = -90_000_000;+const MIN_LON_MICRO: i32 = -180_000_000;++const C_LAT: usize = 0;+const C_LON: usize = 1;+const C_HOUSE: usize = 2;+const C_STREET: usize = 3;+const C_CITY: usize = 4;+const C_STATE: usize = 5;+const C_COUNTRY: usize = 6;+const C_POSTCODE: usize = 7;++// --------------------------------------------------------------------------- byte source+/// Positional reader over a region of a file (the APK asset), starting at `base`.+struct Src {+ file: File,+ base: u64,+}+impl Src {+ fn read(&self, pos: u64, len: usize) -> Option<Vec<u8>> {+ let mut b = vec![0u8; len];+ self.file.read_exact_at(&mut b, self.base + pos).ok()?;+ Some(b)+ }+ fn rd_u32(&self, pos: u64) -> Option<u32> {+ let b = self.read(pos, 4)?;+ Some(be32(&b))+ }+ fn rd_i32(&self, pos: u64) -> Option<i32> {+ Some(self.rd_u32(pos)? as i32)+ }+}++fn be32(b: &[u8]) -> u32 {+ ((b[0] as u32) << 24) | ((b[1] as u32) << 16) | ((b[2] as u32) << 8) | (b[3] as u32)+}+fn be64(b: &[u8]) -> i64 {+ let mut v: i64 = 0;+ for i in 0..8 {+ v = (v << 8) | (b[i] as i64);+ }+ v+}+fn unzigzag(v: u32) -> i32 {+ ((v >> 1) as i32) ^ -((v & 1) as i32)+}+fn read_varint(a: &[u8], p: &mut usize) -> u32 {+ let mut v: u32 = 0;+ let mut shift = 0;+ loop {+ let b = a[*p];+ *p += 1;+ v |= ((b & 0x7F) as u32) << shift;+ if b & 0x80 == 0 {+ break;+ }+ shift += 7;+ }+ v+}+fn zstd_decompress(comp: &[u8], raw_len: usize) -> Option<Vec<u8>> {+ let mut dec = ruzstd::StreamingDecoder::new(Cursor::new(comp)).ok()?;+ let mut out = Vec::with_capacity(raw_len);+ dec.read_to_end(&mut out).ok()?;+ if out.len() != raw_len {+ return None;+ }+ Some(out)+}+/// Kotlin `String.compareTo` compares UTF-16 code units; the dictionaries are sorted that way,+/// so the binary search must compare the same way.+fn cmp_utf16(a: &str, b: &str) -> Ordering {+ a.encode_utf16().cmp(b.encode_utf16())+}++// --------------------------------------------------------------------------- column reader+/// One column, decoding a single block on demand (cf. `GeoDbReader.Column`).+struct Column {+ n: i32,+ delta: bool,+ comp_lens: Vec<i32>,+ raw_lens: Vec<i32>,+ block_off: Vec<u64>,+ cached_block: i32,+ cached: Vec<i32>,+}+impl Column {+ fn new(src: &Src, body_off: u64, delta: bool) -> Option<Column> {+ let n = src.rd_i32(body_off)?;+ let blocks = src.rd_i32(body_off + 4)? as usize;+ let mut raw_lens = Vec::with_capacity(blocks);+ let mut comp_lens = Vec::with_capacity(blocks);+ let mut p = body_off + 8;+ for _ in 0..blocks {+ raw_lens.push(src.rd_i32(p)?);+ comp_lens.push(src.rd_i32(p + 4)?);+ p += 8;+ }+ let mut block_off = Vec::with_capacity(blocks);+ let mut off = p;+ for b in 0..blocks {+ block_off.push(off);+ off += comp_lens[b] as u64;+ }+ Some(Column { n, delta, comp_lens, raw_lens, block_off, cached_block: -1, cached: Vec::new() })+ }+ fn ensure(&mut self, src: &Src, block: i32) -> bool {+ if block == self.cached_block {+ return true;+ }+ let bi = block as usize;+ let comp = match src.read(self.block_off[bi], self.comp_lens[bi] as usize) {+ Some(c) => c,+ None => return false,+ };+ let raw = match zstd_decompress(&comp, self.raw_lens[bi] as usize) {+ Some(r) => r,+ None => return false,+ };+ let count = std::cmp::min(BLOCK, self.n - block * BLOCK) as usize;+ let mut vals = vec![0i32; count];+ let mut rp = 0usize;+ let mut prev = 0i32;+ for k in 0..count {+ let dv = unzigzag(read_varint(&raw, &mut rp));+ let actual = if self.delta { prev + dv } else { dv };+ vals[k] = actual;+ prev = actual;+ }+ self.cached = vals;+ self.cached_block = block;+ true+ }+ fn get(&mut self, src: &Src, i: i32) -> i32 {+ let block = i / BLOCK;+ if !self.ensure(src, block) {+ return 0;+ }+ self.cached[(i - block * BLOCK) as usize]+ }+}++fn decode_dict(section: &[u8]) -> Option<Vec<String>> {+ let raw_size = be32(§ion[0..4]) as usize;+ let comp_size = be32(§ion[4..8]) as usize;+ let raw = zstd_decompress(§ion[8..8 + comp_size], raw_size)?;+ let mut r = 0usize;+ let count = be32(&raw[r..r + 4]) as usize;+ r += 4;+ let mut out = Vec::with_capacity(count);+ for _ in 0..count {+ let len = be32(&raw[r..r + 4]) as usize;+ r += 4;+ out.push(String::from_utf8_lossy(&raw[r..r + len]).into_owned());+ r += len;+ }+ Some(out)+}++// --------------------------------------------------------------------------- reader+pub struct Reader {+ src: Src,+ n: i32,+ dicts: Vec<Vec<String>>, // house, street, city, state, country, postcode+ cell_ids: Vec<i64>,+ cell_starts: Vec<i32>,+ cols: Vec<Column>, // 8+ fwd: Column,+}++fn sect_bytes(src: &Src, cur: &mut u64) -> Option<Vec<u8>> {+ let size = src.rd_i32(*cur)? as usize;+ *cur += 4;+ let b = src.read(*cur, size)?;+ *cur += size as u64;+ Some(b)+}+fn sect_body(src: &Src, cur: &mut u64) -> Option<u64> {+ let size = src.rd_i32(*cur)? as usize;+ *cur += 4;+ let off = *cur;+ *cur += size as u64;+ Some(off)+}++impl Reader {+ fn open(fd: i32, offset: i64) -> Option<Reader> {+ let dupfd = unsafe { libc::dup(fd) };+ if dupfd < 0 {+ return None;+ }+ let file = unsafe { File::from_raw_fd(dupfd) };+ let src = Src { file, base: offset as u64 };++ if src.rd_u32(0)? != MAGIC || src.rd_u32(4)? != VERSION {+ return None;+ }+ let n = src.rd_i32(8)?;+ let mut cursor: u64 = 12;++ let mut dicts = Vec::with_capacity(6);+ for _ in 0..6 {+ dicts.push(decode_dict(§_bytes(&src, &mut cursor)?)?);+ }++ let delta = [true, true, false, false, false, false, false, false];+ let mut cols = Vec::with_capacity(8);+ for i in 0..8 {+ let off = sect_body(&src, &mut cursor)?;+ cols.push(Column::new(&src, off, delta[i])?);+ }++ let grid = sect_bytes(&src, &mut cursor)?;+ let count = be32(&grid[0..4]) as usize;+ let mut cell_ids = Vec::with_capacity(count);+ let mut cell_starts = Vec::with_capacity(count);+ let mut g = 4usize;+ for _ in 0..count {+ cell_ids.push(be64(&grid[g..g + 8]));+ cell_starts.push(be32(&grid[g + 8..g + 12]) as i32);+ g += 12;+ }++ let fwd_off = sect_body(&src, &mut cursor)?;+ let fwd = Column::new(&src, fwd_off, true)?;++ Some(Reader { src, n, dicts, cell_ids, cell_starts, cols, fwd })+ }++ fn grid_index(&self, cell: i64) -> i32 {+ let mut lo = 0i32;+ let mut hi = self.cell_ids.len() as i32 - 1;+ while lo <= hi {+ let mid = (lo + hi) >> 1;+ let v = self.cell_ids[mid as usize];+ if v < cell {+ lo = mid + 1;+ } else if v > cell {+ hi = mid - 1;+ } else {+ return mid;+ }+ }+ -1+ }++ fn dict_index(&self, field: usize, key: &str) -> i32 {+ let dict = &self.dicts[field];+ let mut lo = 0i32;+ let mut hi = dict.len() as i32 - 1;+ while lo <= hi {+ let mid = (lo + hi) >> 1;+ match cmp_utf16(&dict[mid as usize], key) {+ Ordering::Less => lo = mid + 1,+ Ordering::Greater => hi = mid - 1,+ Ordering::Equal => return mid,+ }+ }+ -1+ }++ fn reverse(&mut self, lat: f64, lon: f64) -> Option<i32> {+ if self.n == 0 {+ return None;+ }+ let q_lat = to_micro(lat);+ let q_lon = to_micro(lon);+ let row = ((q_lat - MIN_LAT_MICRO) as i64 / CELL_MICRO) as i64;+ let col = ((q_lon - MIN_LON_MICRO) as i64 / CELL_MICRO) as i64;+ let lon_scale = (lat.to_radians()).cos();++ let mut best_rec = -1i32;+ let mut best_dist = f64::MAX;+ let mut radius = 1i64;+ while best_rec < 0 && radius <= 32 {+ let mut r = row - radius;+ while r <= row + radius {+ if r >= 0 {+ let mut c = col - radius;+ while c <= col + radius {+ let on_edge = !(radius > 1+ && r > row - radius+ && r < row + radius+ && c > col - radius+ && c < col + radius);+ if on_edge {+ let cc = ((c % COLS) + COLS) % COLS;+ let cell = r * COLS + cc;+ let gi = self.grid_index(cell);+ if gi >= 0 {+ let start = self.cell_starts[gi as usize];+ let end = if (gi as usize) + 1 < self.cell_starts.len() {+ self.cell_starts[gi as usize + 1]+ } else {+ self.n+ };+ for i in start..end {+ let d_lat = (self.cols[C_LAT].get(&self.src, i) - q_lat) as f64;+ let d_lon =+ (self.cols[C_LON].get(&self.src, i) - q_lon) as f64 * lon_scale;+ let d = d_lat * d_lat + d_lon * d_lon;+ if d < best_dist {+ best_dist = d;+ best_rec = i;+ }+ }+ }+ }+ c += 1;+ }+ }+ r += 1;+ }+ radius += 1;+ }+ if best_rec < 0 {+ None+ } else {+ Some(best_rec)+ }+ }++ fn compare_key(&mut self, rec: i32, target: [i32; 4]) -> i32 {+ let c = self.cols[C_COUNTRY].get(&self.src, rec) - target[0];+ if c != 0 {+ return c;+ }+ let c = self.cols[C_STATE].get(&self.src, rec) - target[1];+ if c != 0 {+ return c;+ }+ let c = self.cols[C_CITY].get(&self.src, rec) - target[2];+ if c != 0 {+ return c;+ }+ self.cols[C_STREET].get(&self.src, rec) - target[3]+ }++ fn forward(&mut self, country: &str, state: &str, city: &str, street: &str, limit: i32) -> Vec<i32> {+ let k_country = self.dict_index(C_COUNTRY - 2, country);+ let k_state = self.dict_index(C_STATE - 2, state);+ let k_city = self.dict_index(C_CITY - 2, city);+ let k_street = self.dict_index(C_STREET - 2, street);+ if k_country < 0 || k_state < 0 || k_city < 0 || k_street < 0 {+ return Vec::new();+ }+ let target = [k_country, k_state, k_city, k_street];+ let mut lo = 0i32;+ let mut hi = self.n;+ while lo < hi {+ let mid = (lo + hi) >> 1;+ let rec = self.fwd.get(&self.src, mid);+ if self.compare_key(rec, target) < 0 {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ let mut out = Vec::new();+ let mut k = lo;+ while k < self.n && (out.len() as i32) < limit {+ let rec = self.fwd.get(&self.src, k);+ if self.compare_key(rec, target) != 0 {+ break;+ }+ out.push(rec);+ k += 1;+ }+ out+ }++ /// `[lat, lon, house, street, city, state, country, postcode]` for a grid-ordered record.+ fn resolve(&mut self, rec: i32) -> [String; 8] {+ let lat = self.cols[C_LAT].get(&self.src, rec) as f64 / 1e6;+ let lon = self.cols[C_LON].get(&self.src, rec) as f64 / 1e6;+ let h = self.cols[C_HOUSE].get(&self.src, rec);+ let s = self.cols[C_STREET].get(&self.src, rec);+ let ci = self.cols[C_CITY].get(&self.src, rec);+ let st = self.cols[C_STATE].get(&self.src, rec);+ let co = self.cols[C_COUNTRY].get(&self.src, rec);+ let pc = self.cols[C_POSTCODE].get(&self.src, rec);+ [+ format!("{:.6}", lat),+ format!("{:.6}", lon),+ self.dicts[0][h as usize].clone(),+ self.dicts[1][s as usize].clone(),+ self.dicts[2][ci as usize].clone(),+ self.dicts[3][st as usize].clone(),+ self.dicts[4][co as usize].clone(),+ self.dicts[5][pc as usize].clone(),+ ]+ }+}++fn to_micro(deg: f64) -> i32 {+ (deg * 1_000_000.0 + 0.5).floor() as i32+}++// --------------------------------------------------------------------------- JNI+type Handle = Mutex<Reader>;++fn build_string_array(env: &mut JNIEnv, reader: &mut Reader, recs: &[i32]) -> jobjectArray {+ let string_class = match env.find_class("java/lang/String") {+ Ok(c) => c,+ Err(_) => return std::ptr::null_mut(),+ };+ let empty = match env.new_string("") {+ Ok(s) => s,+ Err(_) => return std::ptr::null_mut(),+ };+ let arr = match env.new_object_array((recs.len() * 8) as i32, &string_class, &empty) {+ Ok(a) => a,+ Err(_) => return std::ptr::null_mut(),+ };+ for (idx, &rec) in recs.iter().enumerate() {+ let fields = reader.resolve(rec);+ for (j, val) in fields.iter().enumerate() {+ let s = match env.new_string(val) {+ Ok(s) => s,+ Err(_) => return std::ptr::null_mut(),+ };+ if env+ .set_object_array_element(&arr, (idx * 8 + j) as i32, &s)+ .is_err()+ {+ return std::ptr::null_mut();+ }+ }+ }+ arr.into_raw()+}++/// `open(fd, offset, length) -> handle` (0 on failure). `length` is currently unused (the+/// section framing bounds every read) but kept for API symmetry / future validation.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_networklocation_GeocoderNative_open<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ fd: jint,+ offset: jlong,+ _length: jlong,+) -> jlong {+ match Reader::open(fd, offset) {+ Some(r) => Box::into_raw(Box::new(Mutex::new(r))) as jlong,+ None => 0,+ }+}++/// `reverse(handle, lat, lon) -> String[8]` (nearest address) or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_networklocation_GeocoderNative_reverse<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ lat: jdouble,+ lon: jdouble,+) -> jobjectArray {+ if handle == 0 {+ return std::ptr::null_mut();+ }+ let m = unsafe { &*(handle as *const Handle) };+ let mut reader = match m.lock() {+ Ok(g) => g,+ Err(_) => return std::ptr::null_mut(),+ };+ match reader.reverse(lat, lon) {+ Some(rec) => build_string_array(&mut env, &mut reader, &[rec]),+ None => std::ptr::null_mut(),+ }+}++/// `forward(handle, country, state, city, street, limit) -> String[8*k]` (may be empty).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_networklocation_GeocoderNative_forward<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ country: JString<'l>,+ state: JString<'l>,+ city: JString<'l>,+ street: JString<'l>,+ limit: jint,+) -> jobjectArray {+ if handle == 0 {+ return std::ptr::null_mut();+ }+ let m = unsafe { &*(handle as *const Handle) };+ let mut reader = match m.lock() {+ Ok(g) => g,+ Err(_) => return std::ptr::null_mut(),+ };+ let get = |env: &mut JNIEnv<'l>, s: &JString<'l>| -> String {+ env.get_string(s).map(|js| js.into()).unwrap_or_default()+ };+ let country = get(&mut env, &country);+ let state = get(&mut env, &state);+ let city = get(&mut env, &city);+ let street = get(&mut env, &street);+ let limit = limit.clamp(1, 50);+ let recs = reader.forward(&country, &state, &city, &street, limit);+ build_string_array(&mut env, &mut reader, &recs)+}++/// `close(handle)` — frees the reader and its dup'd fd.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_networklocation_GeocoderNative_close<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle != 0 {+ unsafe {+ drop(Box::from_raw(handle as *mut Handle));+ }+ }+}
networklocation/src/main/rust/src/lib.rs
diff --git a/networklocation/src/main/rust/src/lib.rs b/networklocation/src/main/rust/src/lib.rsindex 6dbcd66ff6..1b4d8d3315 100644--- a/networklocation/src/main/rust/src/lib.rs+++ b/networklocation/src/main/rust/src/lib.rs@@ -16,6 +16,7 @@ use measurement::Measurement; use position::Position; pub mod coordinate;+pub mod geocoder; mod jni; pub mod measurement; pub mod multilateration;
networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeoDbTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeoDbTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeoDbTest.ktdeleted file mode 100644index 13bdd0f3ed..0000000000--- a/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeoDbTest.kt+++ /dev/null@@ -1,74 +0,0 @@-package com.vayunmathur.networklocation.geocoder--import java.io.File-import kotlin.test.AfterTest-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--class GeoDbTest {- private val tmp: File = File.createTempFile("geodb", ".bin").apply { deleteOnExit() }-- @AfterTest fun cleanup() { tmp.delete() }-- /** Synthetic world with realistic field reuse (few countries/states, many streets/houses). */- private fun synth(count: Int): List<GeoAddress> {- val countries = listOf("US", "CA", "GB", "FR", "DE")- val out = ArrayList<GeoAddress>(count)- var k = 0- while (out.size < count) {- val country = countries[k % countries.size]- val state = "State${k % 50}"- val city = "City${k % 2000}"- val street = "Street ${k % 10000}"- val house = ((k % 500) + 1).toString()- val postcode = (10000 + (k % 90000)).toString()- // Spread coordinates deterministically across the globe, distinct per record.- val lat = -60.0 + (k % 12000) * 0.01- val lon = -179.0 + ((k / 12000) % 35000) * 0.01- out.add(GeoAddress(lat, lon, house, street, city, state, country, postcode))- k++- }- return out- }-- @Test fun roundTripReverseAndForward() {- val addrs = synth(20_000)- GeoDbWriter().write(tmp, addrs)-- GeoDbReader(tmp).use { db ->- assertEquals(addrs.size, db.size)-- // Reverse: query the exact coordinate of a few addresses -> nearest should match.- for (i in listOf(0, 7, 123, 9999, 19_999)) {- val a = addrs[i]- val r = db.reverse(a.lat, a.lon)!!- assertEquals(a.lat, r.lat, 1e-4, "reverse lat @${i}")- assertEquals(a.lon, r.lon, 1e-4, "reverse lon @${i}")- }-- // Forward: structured lookup returns matching addresses on that street.- val a = addrs[123]- val hits = db.forward(a.country, a.state, a.city, a.street)- assertTrue(hits.isNotEmpty(), "forward returned nothing")- assertTrue(hits.all { it.street == a.street && it.city == a.city && it.country == a.country })- assertTrue(hits.any { it.house == a.house }, "target house not found")-- // Unknown location name -> empty.- assertTrue(db.forward("US", "State0", "Nowhere", "No Street").isEmpty())- }- }-- @Test fun sizeExtrapolation() {- val n = 50_000- GeoDbWriter().write(tmp, synth(n))- val bytesPerRecord = tmp.length().toDouble() / n- val projectedGb = bytesPerRecord * 170_000_000 / 1e9- println(- "GeoDb size: ${tmp.length()} bytes for $n records = " +- "%.2f B/record -> ~%.2f GB at 170M".format(bytesPerRecord, projectedGb)- )- // Sanity only: the packed format must stay well under the naive fixed-width (~24 B/rec).- assertTrue(bytesPerRecord < 24.0, "packing worse than fixed-width: $bytesPerRecord B/rec")- }-}
networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.ktdeleted file mode 100644index fbe922a366..0000000000--- a/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt+++ /dev/null@@ -1,202 +0,0 @@-package com.vayunmathur.networklocation.geocoder--import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.doubleOrNull-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObject-import java.io.File-import java.nio.file.Files-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/**- * Real geocoder-DB generator. Not a unit test — it reuses the JVM test classpath (GeoDb* are- * pure Kotlin) so it can be run without an Android device or a bespoke JavaExec setup.- *- * Pipeline (see tools/extract-osm-addresses.sh):- * planet.osm.pbf --osmium--> addr.geojsonseq (one GeoJSON Feature per line, addr:* tags)- * addr.geojsonseq --this--> geocoder.geodb (packed, mmap'd by the app at runtime)- *- * Run (give it a big heap for the whole planet):- * GEOCODER_HEAP=100g ./gradlew :networklocation:testDebugUnitTest \- * --tests '*GeocoderGenerator' \- * -Dgeocoder.input=/data/addr.geojsonseq \- * -Dgeocoder.output=networklocation/src/main/assets/geocoder.geodb- *- * With no -Dgeocoder.input it is a no-op, so ordinary test runs skip it.- */-class GeocoderGenerator {-- @Test- fun generate() {- val input = System.getProperty("geocoder.input") ?: run {- println("GeocoderGenerator: no -Dgeocoder.input set; skipping.")- return- }- val output = System.getProperty("geocoder.output")- ?: "networklocation/src/main/assets/geocoder.geodb"-- val inFile = File(input)- require(inFile.exists()) { "input not found: $input" }- val outFile = File(output).apply { parentFile?.mkdirs() }- buildDb(inFile, outFile)- }-- /**- * Parse a GeoJSONSeq file (one Feature per line, optional RS separators) into a GeoDb.- * Returns the number of addresses kept. Shared by [generate] and the self-test so both- * exercise exactly the same parse -> write path.- */- internal fun buildDb(inFile: File, outFile: File): Int {- val json = Json { ignoreUnknownKeys = true; isLenient = true }- val addresses = ArrayList<GeoAddress>(1 shl 20)- var lines = 0L- var skipped = 0L-- inFile.bufferedReader().useLines { seq ->- for (raw in seq) {- val line = raw.trim().trim('\u001e') // GeoJSONSeq may use RS (0x1e) separators- if (line.isEmpty() || line[0] != '{') continue- lines++- val a = parseFeature(json, line)- if (a == null) skipped++ else addresses.add(a)- if (lines % 5_000_000L == 0L) {- println("…parsed $lines features, kept ${addresses.size}")- }- }- }-- println("Parsed $lines features; kept ${addresses.size}; skipped $skipped (no coord/street).")- GeoDbWriter().write(outFile, addresses)- val mb = outFile.length() / (1024.0 * 1024.0)- println("Wrote ${outFile.absolutePath} — %.1f MB for ${addresses.size} addresses.".format(mb))- return addresses.size- }-- /**- * Self-contained end-to-end check: synthesise a tiny GeoJSONSeq sample (Point + LineString +- * Polygon features spread across two grid cells, plus RS separators and a junk line that must- * be skipped), run the real parse -> write pipeline, then read it back and assert both reverse- * and forward lookups. Uses the same [buildDb] path as the planet build, so it protects the- * parser and the on-disk format in ordinary unit-test runs.- */- @Test- fun selfTestSyntheticSample() {- val dir = Files.createTempDirectory("geocoder-selftest").toFile()- val seq = File(dir, "addr.geojsonseq")- val out = File(dir, "geocoder.geodb")- try {- // Cell A ~ (39.78, -89.65); Cell B ~ (40.10, -89.00). CELL is 0.05deg so these differ.- fun feature(- house: String, street: String, city: String, state: String,- country: String, postcode: String, geometry: String,- ): String = """{"type":"Feature","properties":{""" +- """"addr:housenumber":"$house","addr:street":"$street",""" +- """"addr:city":"$city","addr:state":"$state",""" +- """"addr:country":"$country","addr:postcode":"$postcode"},""" +- """"geometry":$geometry}"""-- val rs = "\u001e" // GeoJSONSeq record separator; parser must tolerate it.- val lines = listOf(- rs + feature("10", "Main St", "Springfield", "IL", "US", "62704",- """{"type":"Point","coordinates":[-89.6500,39.7800]}"""),- feature("12", "Main St", "Springfield", "IL", "US", "62704",- """{"type":"Point","coordinates":[-89.6510,39.7810]}"""),- // A way (LineString): centroid is the average of the two endpoints.- feature("20", "Oak Ave", "Springfield", "IL", "US", "62704",- """{"type":"LineString","coordinates":[[-89.6400,39.7700],[-89.6420,39.7720]]}"""),- // A building (Polygon) in a different grid cell; centroid ~ (40.10, -89.00).- rs + feature("5", "Elm St", "Lincoln", "IL", "US", "62656",- """{"type":"Polygon","coordinates":[[[-89.0010,40.0990],[-88.9990,40.0990],""" +- """[-88.9990,40.1010],[-89.0010,40.1010],[-89.0010,40.0990]]]}"""),- // No street/house -> must be skipped.- """{"type":"Feature","properties":{"addr:city":"Nowhere"},""" +- """"geometry":{"type":"Point","coordinates":[0,0]}}""",- "not-json-garbage-line",- )- seq.writeText(lines.joinToString("\n"))-- val kept = buildDb(seq, out)- assertEquals(4, kept, "expected 4 kept addresses (1 no-addr + 1 junk skipped)")-- GeoDbReader(out).use { db ->- assertEquals(4, db.size)-- // Reverse: query the exact coord of "10 Main St" -> nearest must be it.- val r = db.reverse(39.7800, -89.6500)!!- assertEquals("10", r.house, "reverse house")- assertEquals("Main St", r.street, "reverse street")- assertEquals(39.7800, r.lat, 1e-4, "reverse lat")- assertEquals(-89.6500, r.lon, 1e-4, "reverse lon")-- // Reverse in the other cell -> Elm St polygon centroid.- val r2 = db.reverse(40.1000, -89.0000)!!- assertEquals("Elm St", r2.street, "reverse cell B street")- assertEquals(40.1000, r2.lat, 1e-3, "polygon centroid lat")- assertEquals(-89.0000, r2.lon, 1e-3, "polygon centroid lon")-- // Forward: both Main St houses come back, none from Oak Ave.- val hits = db.forward("US", "IL", "Springfield", "Main St")- assertEquals(2, hits.size, "forward Main St count")- assertTrue(hits.all { it.street == "Main St" && it.city == "Springfield" })- assertTrue(hits.map { it.house }.toSet() == setOf("10", "12"), "forward houses")-- // Unknown street -> empty.- assertTrue(db.forward("US", "IL", "Springfield", "No Such St").isEmpty())- }- } finally {- dir.deleteRecursively()- }- }-- private fun parseFeature(json: Json, line: String): GeoAddress? {- val obj = runCatching { json.parseToJsonElement(line).jsonObject }.getOrNull() ?: return null- val props = obj["properties"]?.jsonObject ?: return null- val street = props.str("addr:street")- val house = props.str("addr:housenumber")- // Require at least a street or house number to be a useful address.- if (street.isEmpty() && house.isEmpty()) return null-- val geom = obj["geometry"]?.jsonObject ?: return null- val coords = geom["coordinates"]?.jsonArray ?: return null- val (lon, lat) = averageCoord(coords) ?: return null-- return GeoAddress(- lat = lat,- lon = lon,- house = house,- street = street,- city = props.str("addr:city"),- state = props.str("addr:state").ifEmpty { props.str("addr:province") },- country = props.str("addr:country"),- postcode = props.str("addr:postcode"),- )- }-- private fun JsonObject.str(key: String): String =- (this[key] as? JsonPrimitive)?.content ?: ""-- /** Average of all [lon,lat] leaves — a cheap representative point for ways/areas. */- private fun averageCoord(arr: JsonArray): Pair<Double, Double>? {- var sumLon = 0.0- var sumLat = 0.0- var n = 0- fun walk(e: JsonArray) {- // A coordinate pair is [number, number]; otherwise recurse into nested arrays.- val first = e.firstOrNull()- if (first is JsonPrimitive && first.doubleOrNull != null) {- val lon = (e[0] as JsonPrimitive).doubleOrNull ?: return- val lat = (e[1] as JsonPrimitive).doubleOrNull ?: return- sumLon += lon; sumLat += lat; n++- } else {- for (child in e) if (child is JsonArray) walk(child)- }- }- walk(arr)- return if (n == 0) null else (sumLon / n) to (sumLat / n)- }-}
networklocation/tools/extract-osm-addresses.sh
diff --git a/networklocation/tools/extract-osm-addresses.sh b/networklocation/tools/extract-osm-addresses.shdeleted file mode 100644index 9799b447b0..0000000000--- a/networklocation/tools/extract-osm-addresses.sh+++ /dev/null@@ -1,36 +0,0 @@-#!/usr/bin/env bash-#-# Extract every addressed object from an OSM planet (or region) extract into a GeoJSONSeq file-# that GeocoderGenerator packs into geocoder.geodb.-#-# ./extract-osm-addresses.sh /path/planet.osm.pbf /path/addr.geojsonseq-#-# Needs `osmium` (osmium-tool). On the planet this takes a while and ~a few GB of scratch.-# Try a country/region extract first to validate the pipeline before the full planet.-set -euo pipefail--IN="${1:?usage: extract-osm-addresses.sh <planet.osm.pbf> <out.geojsonseq>}"-OUT="${2:?usage: extract-osm-addresses.sh <planet.osm.pbf> <out.geojsonseq>}"-TMP="$(mktemp -d)"-trap 'rm -rf "$TMP"' EXIT--echo "==> Filtering objects that carry addr:housenumber (nodes, ways, relations)…"-# Keep any object with a house number OR a street; -R keeps referenced nodes so way/area-# geometries can be assembled for centroids.-osmium tags-filter "$IN" \- n/addr:housenumber w/addr:housenumber r/addr:housenumber \- n/addr:street w/addr:street r/addr:street \- -o "$TMP/addr.osm.pbf"--echo "==> Exporting to GeoJSONSeq (one Feature per line)…"-# --add-unique-id gives stable ids; areas/ways are exported with their geometry and the-# generator averages coordinates to a representative point.-osmium export "$TMP/addr.osm.pbf" \- -f geojsonseq \- --geometry-types=point,linestring,polygon \- -o "$OUT" \- --overwrite--echo "==> Done: $OUT ($(du -h "$OUT" | cut -f1))"-echo "Next: GEOCODER_HEAP=100g ./gradlew :networklocation:testDebugUnitTest --tests '*GeocoderGenerator' \\"-echo " -Dgeocoder.input=$OUT -Dgeocoder.output=networklocation/src/main/assets/geocoder.geodb"
networklocation/tools/generate-geocoder-db.sh
diff --git a/networklocation/tools/generate-geocoder-db.sh b/networklocation/tools/generate-geocoder-db.shdeleted file mode 100644index 547b834e73..0000000000--- a/networklocation/tools/generate-geocoder-db.sh+++ /dev/null@@ -1,169 +0,0 @@-#!/usr/bin/env bash-#-# Build-machine pipeline: OSM planet -> geocoder.geodb -> Cloudflare R2.-#-# Runs the whole geocoder database build end to end:-# 1. Obtain a planet PBF (use --pbf, or download planet-latest.osm.pbf).-# 2. extract-osm-addresses.sh -> addr.geojsonseq (osmium tags-filter + export).-# 3. GeocoderGenerator (JVM test) -> geocoder.geodb (packed, mmap'd by the app).-# 4. Print the final byte size.-# 5. Upload to s3://maps/geocoder/geocoder.geodb, served at-# https://data.vayunmathur.com/geocoder/geocoder.geodb.-#-# This is a HEAVY job: the planet PBF is ~80 GB, extraction needs a few GB of scratch,-# and the generator wants a large heap (GEOCODER_HEAP, default 100g). Run it on the build-# machine, NOT a laptop. Requires: osmium (osmium-tool), a JDK, curl, awscli v2.-#-# Usage:-# # A) build only, from an already-downloaded planet:-# ./networklocation/tools/generate-geocoder-db.sh --pbf /data/planet-latest.osm.pbf --skip-upload-#-# # B) full run (download + build + upload). R2 creds come from the environment:-# export AWS_ACCESS_KEY_ID=... # R2 access key id-# export AWS_SECRET_ACCESS_KEY=... # R2 secret-# export R2_ENDPOINT=https://<account>.r2.cloudflarestorage.com-# ./networklocation/tools/generate-geocoder-db.sh --work /data/geocoder-#-# Options:-# --pbf PATH Use an existing planet/region .osm.pbf (skips the download).-# --planet-url URL Download source (default: planet-latest.osm.pbf). Download is-# resumable (curl -C -).-# --work DIR Scratch/output dir (default: a mktemp dir under $TMPDIR).-# --output PATH Output .geodb path (default: <work>/geocoder.geodb).-# --prefix PREFIX R2 key prefix (default: geocoder/).-# --heap SIZE GEOCODER_HEAP passed to Gradle (default: 100g).-# --skip-upload Build and size only; do not touch R2.-# -h, --help Show this help.-#-# Notes:-# - R2 rejects AWS CLI v2's default CRC64NVME trailing checksum, so we export-# AWS_REQUEST_CHECKSUM_CALCULATION=when_required (+ the response counterpart), matching how-# the rest of the repo talks to R2. Bucket is `maps`; region is always `auto`.-# - After upload, pin the printed SHA256 wherever the fetch step verifies the asset.-set -euo pipefail--# --------------------------------------------------------------------------- args-PBF=""-PLANET_URL="https://planet.openstreetmap.org/pbf/planet-latest.osm.pbf"-WORK=""-OUTPUT=""-PREFIX="geocoder/"-HEAP="100g"-SKIP_UPLOAD=0--while [[ $# -gt 0 ]]; do- case "$1" in- --pbf) PBF="$2"; shift 2;;- --pbf=*) PBF="${1#--pbf=}"; shift;;- --planet-url) PLANET_URL="$2"; shift 2;;- --planet-url=*) PLANET_URL="${1#--planet-url=}"; shift;;- --work) WORK="$2"; shift 2;;- --work=*) WORK="${1#--work=}"; shift;;- --output) OUTPUT="$2"; shift 2;;- --output=*) OUTPUT="${1#--output=}"; shift;;- --prefix) PREFIX="$2"; shift 2;;- --prefix=*) PREFIX="${1#--prefix=}"; shift;;- --heap) HEAP="$2"; shift 2;;- --heap=*) HEAP="${1#--heap=}"; shift;;- --skip-upload) SKIP_UPLOAD=1; shift;;- -h|--help) sed -n '2,60p' "$0"; exit 0;;- *) echo "unknown arg: $1" >&2; exit 2;;- esac-done--[[ "$PREFIX" != */ ]] && PREFIX="$PREFIX/"--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"-EXTRACT="$SCRIPT_DIR/extract-osm-addresses.sh"--# Scratch/output locations.-if [[ -z "$WORK" ]]; then- WORK="$(mktemp -d "${TMPDIR:-/tmp}/geocoder.XXXXXX")"- echo "==> Using scratch dir $WORK"-fi-mkdir -p "$WORK"-GEOJSONSEQ="$WORK/addr.geojsonseq"-[[ -z "$OUTPUT" ]] && OUTPUT="$WORK/geocoder.geodb"-mkdir -p "$(dirname "$OUTPUT")"--# --------------------------------------------------------------------------- deps-need() { command -v "$1" >/dev/null 2>&1 || { echo "missing dependency: $1" >&2; exit 1; }; }-need osmium-need curl-[[ -x "$REPO_ROOT/gradlew" ]] || { echo "gradlew not found at $REPO_ROOT/gradlew" >&2; exit 1; }-[[ -f "$EXTRACT" ]] || { echo "extract script not found: $EXTRACT" >&2; exit 1; }--# --------------------------------------------------------------------------- 1. PBF-if [[ -z "$PBF" ]]; then- PBF="$WORK/planet-latest.osm.pbf"- echo "==> [1/5] Downloading planet PBF"- echo " from $PLANET_URL"- echo " to $PBF (this is ~80 GB; resumable with curl -C -)"- curl -L --fail --retry 5 --retry-delay 30 -C - -o "$PBF" "$PLANET_URL"-else- echo "==> [1/5] Using existing PBF: $PBF"-fi-[[ -f "$PBF" ]] || { echo "PBF not found: $PBF" >&2; exit 1; }-echo " PBF size: $(du -h "$PBF" | cut -f1)"--# --------------------------------------------------------------------------- 2. extract-echo "==> [2/5] Extracting addressed objects to GeoJSONSeq"-bash "$EXTRACT" "$PBF" "$GEOJSONSEQ"--# --------------------------------------------------------------------------- 3. generate-echo "==> [3/5] Packing geocoder.geodb (GEOCODER_HEAP=$HEAP)"-(- cd "$REPO_ROOT"- GEOCODER_HEAP="$HEAP" ./gradlew :networklocation:testDebugUnitTest \- --tests '*GeocoderGenerator' \- --rerun-tasks --console=plain \- -Dgeocoder.input="$GEOJSONSEQ" \- -Dgeocoder.output="$OUTPUT"-)-[[ -f "$OUTPUT" ]] || { echo "generator did not produce $OUTPUT" >&2; exit 1; }--# --------------------------------------------------------------------------- 4. size-BYTES="$(stat -c%s "$OUTPUT" 2>/dev/null || stat -f%z "$OUTPUT")"-SHA="$(sha256sum "$OUTPUT" 2>/dev/null | cut -d' ' -f1 || shasum -a 256 "$OUTPUT" | cut -d' ' -f1)"-echo "==> [4/5] Built $OUTPUT"-echo " size: $BYTES bytes ($(du -h "$OUTPUT" | cut -f1))"-echo " sha256: $SHA"--# --------------------------------------------------------------------------- 5. upload-if [[ "$SKIP_UPLOAD" -eq 1 ]]; then- echo "==> [5/5] --skip-upload set; leaving $OUTPUT local. Done."- exit 0-fi--: "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID (R2 access key id)}"-: "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY (R2 secret)}"-: "${R2_ENDPOINT:?set R2_ENDPOINT=https://<account>.r2.cloudflarestorage.com}"-need aws-if [[ "$R2_ENDPOINT" == *"<account>"* || "$R2_ENDPOINT" == *"<ACCOUNT_ID>"* ]]; then- echo "R2_ENDPOINT still contains a placeholder: $R2_ENDPOINT" >&2- exit 1-fi--# R2 compatibility: skip AWS CLI v2's default CRC64NVME trailing checksum, which R2 rejects.-export AWS_REQUEST_CHECKSUM_CALCULATION=when_required-export AWS_RESPONSE_CHECKSUM_VALIDATION=when_required-export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-auto}"--BUCKET="maps"-KEY="${PREFIX}geocoder.geodb"-echo "==> [5/5] Uploading to s3://$BUCKET/$KEY"-aws s3 cp "$OUTPUT" "s3://$BUCKET/$KEY" \- --endpoint-url "$R2_ENDPOINT" \- --content-type "application/octet-stream" \- --cache-control "public, max-age=31536000, immutable" \- --expected-size "$BYTES"--echo "--- head-object s3://$BUCKET/$KEY ---"-aws s3api head-object --bucket "$BUCKET" --key "$KEY" --endpoint-url "$R2_ENDPOINT"--echo ""-echo "Uploaded: https://data.vayunmathur.com/$KEY"-echo " bytes: $BYTES"-echo " sha256: $SHA"-echo "Pin this sha256 wherever the app's fetch step verifies the geocoder asset."
scripts/geocoder_gen.cpp
diff --git a/scripts/geocoder_gen.cpp b/scripts/geocoder_gen.cppnew file mode 100644index 0000000000..7511f2ecca--- /dev/null+++ b/scripts/geocoder_gen.cpp@@ -0,0 +1,612 @@+// geocoder_gen.cpp — offline planet geocoder database builder.+//+// Reads an OSM-address GeoJSONSeq stream (one GeoJSON Feature per line, as produced by+// `osmium export`) and writes a packed `geocoder.geodb` that the Modern Apps network-location+// app mmaps at runtime (see networklocation/.../geocoder/GeoDb.kt + GeoDbReader.kt).+//+// This replaces the old in-app Kotlin generator: generating the whole planet needs tens of GB+// of working memory and a multi-hour run, which does not belong on the JVM test classpath.+//+// On-disk format (must byte-match GeoDbReader.kt — all ints/longs are BIG-ENDIAN):+// int MAGIC = 0x4D414745 ("MAGE")+// int VERSION = 2 (v2 = per-block codec is Zstandard)+// int n (record count)+// 6x dict section : [int size][ [int rawLen][int compLen][zstd(raw)] ]+// raw = [int count]( [int len][utf8 bytes] )*count+// order: house, street, city, state, country, postcode+// entries sorted in Kotlin String order (UTF-16 code units) so the+// reader's binary search over the dict works.+// 8x column section : [int size][ [int n][int blocks]([int rawLen][int compLen])*blocks+// [zstd block]*blocks ]+// each block: up to BLOCK values, delta(optional)+zigzag+varint(LEB128).+// order: lat(delta), lon(delta), house, street, city, state, country,+// postcode. lat/lon are micro-degrees; the rest are dict indices.+// Records are in grid-primary order (sorted by 0.05-deg cell id).+// grid section : [int size][ [int cellCount]( [long cellId][int startRec] )*count ]+// (uncompressed; cellIds ascending)+// fwd section : one delta column of record indices sorted by+// (country,state,city,street,house) dict index — for forward lookup.+//+// Build (see geocoder_gen.sh):+// g++ -O2 -fopenmp -std=c++17 geocoder_gen.cpp simdjson.cpp -lzstd -o geocoder_gen+// Run:+// ./geocoder_gen generate addr.geojsonseq geocoder.geodb # build (then self-verifies)+// ./geocoder_gen verify geocoder.geodb # re-check an existing DB++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <string>+#include <unordered_map>+#include <vector>++#include <fcntl.h>+#include <sys/mman.h>+#include <sys/stat.h>+#include <unistd.h>++#include <zstd.h>++#include "simdjson.h"++// ------------------------------------------------------------------ constants (match GeoDb.kt)+static const uint32_t MAGIC = 0x4D414745u;+static const uint32_t VERSION = 2u;+static const int BLOCK = 4096;+static const int CELL_MICRO = 50000;+static const int64_t COLS = 360000000LL / CELL_MICRO; // 7200+static const int MIN_LAT_MICRO = -90000000;+static const int MIN_LON_MICRO = -180000000;+static const int ZSTD_LEVEL = 19;+static const int FIELDS = 6; // house, street, city, state, country, postcode+enum { F_HOUSE = 0, F_STREET, F_CITY, F_STATE, F_COUNTRY, F_POSTCODE };++[[noreturn]] static void die(const std::string& m) {+ fprintf(stderr, "geocoder_gen: %s\n", m.c_str());+ exit(1);+}++// ------------------------------------------------------------------ little helpers+static inline void be32(std::string& o, uint32_t v) {+ o.push_back((char)(v >> 24)); o.push_back((char)(v >> 16));+ o.push_back((char)(v >> 8)); o.push_back((char)v);+}+static inline void be64(std::string& o, uint64_t v) {+ for (int s = 56; s >= 0; s -= 8) o.push_back((char)(v >> s));+}+static inline uint32_t rd32(const uint8_t* p) {+ return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];+}+static inline uint64_t rd64(const uint8_t* p) {+ uint64_t v = 0; for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; return v;+}+static inline uint32_t zigzag(int32_t v) { return ((uint32_t)v << 1) ^ (uint32_t)(v >> 31); }+static inline int32_t unzigzag(uint32_t v) { return (int32_t)(v >> 1) ^ -(int32_t)(v & 1); }+static inline void writeVarInt(std::string& o, uint32_t v) {+ while (true) {+ uint8_t b = v & 0x7F; v >>= 7;+ if (v == 0) { o.push_back((char)b); return; }+ o.push_back((char)(b | 0x80));+ }+}+static inline int toMicro(double deg) {+ // Kotlin roundToInt(): ties round toward +infinity == floor(x + 0.5).+ return (int)std::floor(deg * 1000000.0 + 0.5);+}+static inline int64_t cellIdOf(int latM, int lonM) {+ int64_t row = (int64_t)(latM - MIN_LAT_MICRO) / CELL_MICRO;+ int64_t col = (int64_t)(lonM - MIN_LON_MICRO) / CELL_MICRO;+ return row * COLS + col;+}++static std::string zstdCompress(const std::string& raw) {+ size_t bound = ZSTD_compressBound(raw.size());+ std::string c; c.resize(bound);+ size_t r = ZSTD_compress(&c[0], bound, raw.data(), raw.size(), ZSTD_LEVEL);+ if (ZSTD_isError(r)) die(std::string("zstd compress: ") + ZSTD_getErrorName(r));+ c.resize(r);+ return c;+}+static std::string zstdDecompress(const uint8_t* comp, size_t compLen, size_t rawLen) {+ std::string raw; raw.resize(rawLen);+ size_t r = ZSTD_decompress(&raw[0], rawLen, comp, compLen);+ if (ZSTD_isError(r) || r != rawLen) die(std::string("zstd decompress: ") + ZSTD_getErrorName(r));+ return raw;+}++// Decode UTF-8 -> UTF-16 units so we can sort exactly like Kotlin's String.compareTo.+static std::u16string toUtf16(const std::string& s) {+ std::u16string o; o.reserve(s.size());+ size_t i = 0, n = s.size();+ while (i < n) {+ uint32_t cp; unsigned char c = (unsigned char)s[i];+ if (c < 0x80) { cp = c; i += 1; }+ else if ((c >> 5) == 0x6 && i + 1 < n) { cp = (c & 0x1F); cp = (cp << 6) | (s[i + 1] & 0x3F); i += 2; }+ else if ((c >> 4) == 0xE && i + 2 < n) { cp = (c & 0x0F); cp = (cp << 6) | (s[i + 1] & 0x3F); cp = (cp << 6) | (s[i + 2] & 0x3F); i += 3; }+ else if ((c >> 3) == 0x1E && i + 3 < n) { cp = (c & 0x07); cp = (cp << 6) | (s[i + 1] & 0x3F); cp = (cp << 6) | (s[i + 2] & 0x3F); cp = (cp << 6) | (s[i + 3] & 0x3F); i += 4; }+ else { cp = 0xFFFD; i += 1; }+ if (cp <= 0xFFFF) o.push_back((char16_t)cp);+ else { cp -= 0x10000; o.push_back((char16_t)(0xD800 + (cp >> 10))); o.push_back((char16_t)(0xDC00 + (cp & 0x3FF))); }+ }+ return o;+}++// ------------------------------------------------------------------ record model+struct Rec {+ int32_t latM, lonM;+ uint32_t f[FIELDS]; // dict ids (provisional during parse, final after remap)+};++// Per-field string interner: value -> provisional id, plus the unique values in insertion order.+struct Interner {+ std::unordered_map<std::string, uint32_t> id;+ std::vector<std::string> vals;+ uint32_t intern(const std::string& s) {+ auto it = id.find(s);+ if (it != id.end()) return it->second;+ uint32_t v = (uint32_t)vals.size();+ id.emplace(s, v);+ vals.push_back(s);+ return v;+ }+};++// ------------------------------------------------------------------ column encoder+// Encode `values` as [int n][int blocks]([int rawLen][int compLen])*blocks [zstd block]*blocks.+static std::string encodeColumn(const std::vector<int32_t>& values, bool delta) {+ int n = (int)values.size();+ int blocks = (n + BLOCK - 1) / BLOCK;+ std::vector<std::string> comp(blocks);+ std::vector<int> rawLens(blocks), compLens(blocks);+#pragma omp parallel for schedule(dynamic, 16)+ for (int b = 0; b < blocks; b++) {+ int start = b * BLOCK;+ int end = std::min(start + BLOCK, n);+ std::string raw;+ int32_t prev = 0;+ for (int i = start; i < end; i++) {+ int32_t v = values[i];+ int32_t enc = delta ? (v - prev) : v;+ writeVarInt(raw, zigzag(enc));+ prev = v;+ }+ rawLens[b] = (int)raw.size();+ std::string c = zstdCompress(raw);+ compLens[b] = (int)c.size();+ comp[b] = std::move(c);+ }+ std::string head;+ be32(head, (uint32_t)n);+ be32(head, (uint32_t)blocks);+ for (int b = 0; b < blocks; b++) { be32(head, (uint32_t)rawLens[b]); be32(head, (uint32_t)compLens[b]); }+ std::string out = std::move(head);+ for (int b = 0; b < blocks; b++) out += comp[b];+ return out;+}++static std::string encodeDict(const std::vector<std::string>& sorted) {+ std::string raw;+ be32(raw, (uint32_t)sorted.size());+ for (const auto& s : sorted) { be32(raw, (uint32_t)s.size()); raw += s; }+ std::string comp = zstdCompress(raw);+ std::string out;+ be32(out, (uint32_t)raw.size());+ be32(out, (uint32_t)comp.size());+ out += comp;+ return out;+}++static void writeSection(FILE* f, const std::string& bytes) {+ std::string h; be32(h, (uint32_t)bytes.size());+ if (fwrite(h.data(), 1, 4, f) != 4) die("write section size");+ if (fwrite(bytes.data(), 1, bytes.size(), f) != bytes.size()) die("write section body");+}++// ------------------------------------------------------------------ GeoJSON field extraction+using namespace simdjson;++static std::string getStr(dom::element obj, const char* key) {+ dom::element v;+ if (obj[key].get(v) != SUCCESS) return {};+ std::string_view sv;+ if (v.get_string().get(sv) != SUCCESS) return {};+ return std::string(sv);+}+static bool getNum(dom::element e, double& out) {+ double d; if (e.get_double().get(d) == SUCCESS) { out = d; return true; }+ int64_t i; if (e.get_int64().get(i) == SUCCESS) { out = (double)i; return true; }+ uint64_t u; if (e.get_uint64().get(u) == SUCCESS) { out = (double)u; return true; }+ return false;+}+// Average of every [lon,lat] leaf (a cheap representative point for ways/areas), matching+// the old Kotlin averageCoord().+static void walkCoords(dom::element e, double& sumLon, double& sumLat, long& cnt) {+ dom::array a;+ if (e.get_array().get(a) != SUCCESS) return;+ auto it = a.begin();+ if (it == a.end()) return;+ dom::element first = *it;+ if (first.is_number()) {+ double lon, lat;+ if (!getNum(first, lon)) return;+ auto it2 = it; ++it2;+ if (it2 == a.end()) return;+ if (!getNum(*it2, lat)) return;+ sumLon += lon; sumLat += lat; cnt++;+ } else {+ for (dom::element child : a) walkCoords(child, sumLon, sumLat, cnt);+ }+}++static void generate(const char* inPath, const char* outPath);+static void verify(const char* dbPath);++// ------------------------------------------------------------------ generate+static void generate(const char* inPath, const char* outPath) {+ int fd = open(inPath, O_RDONLY);+ if (fd < 0) die(std::string("open input: ") + inPath);+ struct stat st{};+ if (fstat(fd, &st) != 0) die("fstat input");+ size_t fsize = (size_t)st.st_size;+ void* map = mmap(nullptr, fsize, PROT_READ, MAP_PRIVATE, fd, 0);+ if (map == MAP_FAILED) die("mmap input");+ madvise(map, fsize, MADV_SEQUENTIAL);+ const char* data = (const char*)map;++ fprintf(stderr, "Parsing %s (%.1f GB)...\n", inPath, fsize / 1e9);++ Interner interns[FIELDS];+ std::vector<Rec> recs;+ recs.reserve(240000000);++ dom::parser parser;++ auto isTrim = [](unsigned char c) {+ return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0x1e;+ };++ long long lines = 0, kept = 0, skipped = 0;+ size_t pos = 0;+ while (pos < fsize) {+ size_t nl = pos;+ while (nl < fsize && data[nl] != '\n') nl++;+ size_t s = pos, e = nl;+ pos = nl + 1;+ while (s < e && isTrim((unsigned char)data[s])) s++;+ while (e > s && isTrim((unsigned char)data[e - 1])) e--;+ if (s >= e || data[s] != '{') continue;+ lines++;++ dom::element doc;+ if (parser.parse(data + s, e - s, true).get(doc) != SUCCESS) { skipped++; goto progress; }+ {+ dom::element props;+ if (doc["properties"].get(props) != SUCCESS) { skipped++; goto progress; }+ std::string street = getStr(props, "addr:street");+ if (street.empty()) { skipped++; goto progress; } // require a street; drop house-only+ std::string house = getStr(props, "addr:housenumber");++ dom::element geom, coords;+ if (doc["geometry"].get(geom) != SUCCESS) { skipped++; goto progress; }+ if (geom["coordinates"].get(coords) != SUCCESS) { skipped++; goto progress; }+ double sumLon = 0, sumLat = 0; long cnt = 0;+ walkCoords(coords, sumLon, sumLat, cnt);+ if (cnt == 0) { skipped++; goto progress; }++ std::string city = getStr(props, "addr:city");+ std::string state = getStr(props, "addr:state");+ if (state.empty()) state = getStr(props, "addr:province");+ std::string country = getStr(props, "addr:country");+ std::string postcode = getStr(props, "addr:postcode");++ Rec r;+ r.latM = toMicro(sumLat / cnt);+ r.lonM = toMicro(sumLon / cnt);+ r.f[F_HOUSE] = interns[F_HOUSE].intern(house);+ r.f[F_STREET] = interns[F_STREET].intern(street);+ r.f[F_CITY] = interns[F_CITY].intern(city);+ r.f[F_STATE] = interns[F_STATE].intern(state);+ r.f[F_COUNTRY] = interns[F_COUNTRY].intern(country);+ r.f[F_POSTCODE] = interns[F_POSTCODE].intern(postcode);+ recs.push_back(r);+ kept++;+ }+ progress:+ if ((lines % 20000000) == 0 && lines > 0)+ fprintf(stderr, " ...parsed %lld lines, kept %lld\n", lines, kept);+ }+ munmap(map, fsize);+ close(fd);++ size_t n = recs.size();+ if (n == 0) die("no records kept");+ if (n > 0x7fffffffull) die("record count exceeds 2^31 (reader uses signed int)");+ fprintf(stderr, "Parsed %lld features; kept %lld; skipped %lld.\n", lines, kept, skipped);+ for (int fi = 0; fi < FIELDS; fi++)+ fprintf(stderr, " distinct[%d] = %zu\n", fi, interns[fi].vals.size());++ // Build sorted dictionaries (Kotlin String / UTF-16 order) and remap provisional->final ids.+ std::vector<std::vector<std::string>> dicts(FIELDS);+ std::vector<std::vector<uint32_t>> remap(FIELDS);+ for (int fi = 0; fi < FIELDS; fi++) {+ size_t m = interns[fi].vals.size();+ std::vector<uint32_t> ord(m);+ for (size_t i = 0; i < m; i++) ord[i] = (uint32_t)i;+ std::vector<std::u16string> keys(m);+ for (size_t i = 0; i < m; i++) keys[i] = toUtf16(interns[fi].vals[i]);+ std::sort(ord.begin(), ord.end(),+ [&](uint32_t a, uint32_t b) { return keys[a] < keys[b]; });+ dicts[fi].resize(m);+ remap[fi].resize(m);+ for (size_t rank = 0; rank < m; rank++) {+ uint32_t prov = ord[rank];+ dicts[fi][rank] = interns[fi].vals[prov];+ remap[fi][prov] = (uint32_t)rank;+ }+ std::vector<std::u16string>().swap(keys);+ std::unordered_map<std::string, uint32_t>().swap(interns[fi].id);+ std::vector<std::string>().swap(interns[fi].vals);+ }+ for (auto& r : recs)+ for (int fi = 0; fi < FIELDS; fi++) r.f[fi] = remap[fi][r.f[fi]];++ // Grid-primary order: sort record indices by cell id.+ std::vector<int64_t> cell(n);+ for (size_t i = 0; i < n; i++) cell[i] = cellIdOf(recs[i].latM, recs[i].lonM);+ std::vector<uint32_t> order(n);+ for (size_t i = 0; i < n; i++) order[i] = (uint32_t)i;+ std::sort(order.begin(), order.end(),+ [&](uint32_t a, uint32_t b) { return cell[a] < cell[b]; });++ fprintf(stderr, "Writing %s (%zu records)...\n", outPath, n);+ FILE* f = fopen(outPath, "wb");+ if (!f) die(std::string("open output: ") + outPath);+ setvbuf(f, nullptr, _IOFBF, 1 << 22);++ std::string hdr;+ be32(hdr, MAGIC); be32(hdr, VERSION); be32(hdr, (uint32_t)n);+ if (fwrite(hdr.data(), 1, hdr.size(), f) != hdr.size()) die("write header");++ for (int fi = 0; fi < FIELDS; fi++) writeSection(f, encodeDict(dicts[fi]));++ std::vector<int32_t> col(n);+ auto emitCol = [&](int which, bool delta) {+ for (size_t i = 0; i < n; i++) {+ const Rec& r = recs[order[i]];+ switch (which) {+ case 0: col[i] = r.latM; break;+ case 1: col[i] = r.lonM; break;+ default: col[i] = (int32_t)r.f[which - 2]; break; // house..postcode+ }+ }+ writeSection(f, encodeColumn(col, delta));+ };+ emitCol(0, true); emitCol(1, true); // lat, lon+ for (int c = 2; c < 8; c++) emitCol(c, false); // house..postcode++ { // Grid directory: (cellId, startRec) per non-empty cell, ascending cell order.+ std::string grid, body;+ uint32_t count = 0;+ int64_t prevCell = INT64_MIN;+ for (size_t i = 0; i < n; i++) {+ int64_t c = cell[order[i]];+ if (c != prevCell) { be64(body, (uint64_t)c); be32(body, (uint32_t)i); count++; prevCell = c; }+ }+ be32(grid, count);+ grid += body;+ writeSection(f, grid);+ }++ { // Forward ordering: positions sorted by (country,state,city,street,house), delta column.+ std::vector<int32_t> fwd(n);+ for (size_t i = 0; i < n; i++) fwd[i] = (int32_t)i;+ std::sort(fwd.begin(), fwd.end(), [&](int32_t a, int32_t b) {+ const Rec& ra = recs[order[a]];+ const Rec& rb = recs[order[b]];+ if (ra.f[F_COUNTRY] != rb.f[F_COUNTRY]) return ra.f[F_COUNTRY] < rb.f[F_COUNTRY];+ if (ra.f[F_STATE] != rb.f[F_STATE]) return ra.f[F_STATE] < rb.f[F_STATE];+ if (ra.f[F_CITY] != rb.f[F_CITY]) return ra.f[F_CITY] < rb.f[F_CITY];+ if (ra.f[F_STREET] != rb.f[F_STREET]) return ra.f[F_STREET] < rb.f[F_STREET];+ return ra.f[F_HOUSE] < rb.f[F_HOUSE];+ });+ writeSection(f, encodeColumn(fwd, true));+ }++ if (fclose(f) != 0) die("close output");++ struct stat ost{};+ stat(outPath, &ost);+ fprintf(stderr, "Done: %s = %lld bytes (%.3f GB), %.2f B/record.\n",+ outPath, (long long)ost.st_size, ost.st_size / (double)(1LL << 30),+ (double)ost.st_size / (double)n);++ fprintf(stderr, "Self-verifying...\n");+ verify(outPath);+}++// ------------------------------------------------------------------ verify (mirrors GeoDbReader)+struct MappedDb {+ const uint8_t* p = nullptr;+ size_t size = 0;+ int fd = -1;+ void openFile(const char* path) {+ fd = open(path, O_RDONLY);+ if (fd < 0) die(std::string("open db: ") + path);+ struct stat st{}; fstat(fd, &st); size = (size_t)st.st_size;+ void* m = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);+ if (m == MAP_FAILED) die("mmap db");+ p = (const uint8_t*)m;+ }+ ~MappedDb() { if (p) munmap((void*)p, size); if (fd >= 0) close(fd); }+};++// A single delta/raw column, decoding one block on demand (as GeoDbReader.Column does).+struct ColReader {+ const uint8_t* base = nullptr;+ int n = 0, blocks = 0;+ bool delta = false;+ std::vector<int> rawLens, compLens;+ std::vector<size_t> blockOff;+ int cachedBlock = -1;+ std::vector<int32_t> cachedVals;+ void init(const uint8_t* fileBase, size_t bodyOff, bool d) {+ delta = d;+ const uint8_t* q = fileBase + bodyOff;+ n = (int)rd32(q); q += 4;+ blocks = (int)rd32(q); q += 4;+ rawLens.resize(blocks); compLens.resize(blocks); blockOff.resize(blocks);+ for (int b = 0; b < blocks; b++) { rawLens[b] = (int)rd32(q); q += 4; compLens[b] = (int)rd32(q); q += 4; }+ size_t off = (size_t)(q - fileBase);+ for (int b = 0; b < blocks; b++) { blockOff[b] = off; off += compLens[b]; }+ base = fileBase;+ }+ void decode(int block) {+ std::string raw = zstdDecompress(base + blockOff[block], compLens[block], rawLens[block]);+ int count = std::min(BLOCK, n - block * BLOCK);+ cachedVals.assign(count, 0);+ const uint8_t* r = (const uint8_t*)raw.data();+ size_t rp = 0; int32_t prev = 0;+ for (int k = 0; k < count; k++) {+ uint32_t v = 0; int shift = 0;+ while (true) { uint8_t b = r[rp++]; v |= (uint32_t)(b & 0x7F) << shift; if (!(b & 0x80)) break; shift += 7; }+ int32_t dv = unzigzag(v);+ int32_t actual = delta ? prev + dv : dv;+ cachedVals[k] = actual; prev = actual;+ }+ cachedBlock = block;+ }+ int32_t get(int i) {+ int block = i / BLOCK;+ if (block != cachedBlock) decode(block);+ return cachedVals[i - block * BLOCK];+ }+};++static std::vector<std::string> decodeDict(const uint8_t* section) {+ uint32_t rawSize = rd32(section), compSize = rd32(section + 4);+ std::string raw = zstdDecompress(section + 8, compSize, rawSize);+ const uint8_t* r = (const uint8_t*)raw.data();+ uint32_t count = rd32(r); r += 4;+ std::vector<std::string> out; out.reserve(count);+ for (uint32_t i = 0; i < count; i++) { uint32_t len = rd32(r); r += 4; out.emplace_back((const char*)r, len); r += len; }+ return out;+}++static void verify(const char* dbPath) {+ MappedDb db; db.openFile(dbPath);+ const uint8_t* p = db.p;+ if (rd32(p) != MAGIC) die("verify: bad magic");+ if (rd32(p + 4) != VERSION) die("verify: bad version");+ int n = (int)rd32(p + 8);+ size_t cursor = 12;+ auto readSectionOff = [&](size_t& bodyOff) {+ uint32_t sz = rd32(p + cursor); cursor += 4; bodyOff = cursor; cursor += sz;+ };++ std::vector<std::vector<std::string>> dict(FIELDS);+ for (int fi = 0; fi < FIELDS; fi++) { size_t off; readSectionOff(off); dict[fi] = decodeDict(p + off); }+ ColReader cols[8];+ bool delta[8] = {true, true, false, false, false, false, false, false};+ for (int i = 0; i < 8; i++) { size_t off; readSectionOff(off); cols[i].init(p, off, delta[i]); }++ size_t gridOff; readSectionOff(gridOff);+ const uint8_t* g = p + gridOff;+ uint32_t cellCount = rd32(g); g += 4;+ std::vector<int64_t> cellIds(cellCount);+ std::vector<int32_t> cellStarts(cellCount);+ for (uint32_t i = 0; i < cellCount; i++) { cellIds[i] = (int64_t)rd64(g); g += 8; cellStarts[i] = (int32_t)rd32(g); g += 4; }++ size_t fwdOff; readSectionOff(fwdOff);+ ColReader fwd; fwd.init(p, fwdOff, true);+ if (cursor != db.size) die("verify: trailing bytes / size mismatch");++ // Force-decode every block of every column to catch any zstd/varint/framing error.+ for (int c = 0; c < 8; c++) for (int i = 0; i < n; i += BLOCK) (void)cols[c].get(i);+ for (int i = 0; i < n; i += BLOCK) (void)fwd.get(i);++ // Reverse: nearest stored record to a coordinate (mirrors GeoDbReader.reverse).+ auto reverse = [&](double lat, double lon) -> int {+ int qLatM = toMicro(lat), qLonM = toMicro(lon);+ int row = (qLatM - MIN_LAT_MICRO) / CELL_MICRO;+ int colc = (qLonM - MIN_LON_MICRO) / CELL_MICRO;+ double lonScale = cos(lat * M_PI / 180.0);+ int bestRec = -1; double bestDist = 1e300;+ for (int radius = 1; bestRec < 0 && radius <= 32; radius++) {+ for (int r = row - radius; r <= row + radius; r++) {+ if (r < 0) continue;+ for (int c = colc - radius; c <= colc + radius; c++) {+ if (radius > 1 && r > row - radius && r < row + radius && c > colc - radius && c < colc + radius) continue;+ int64_t cc = ((c % COLS) + COLS) % COLS;+ int64_t cellv = (int64_t)r * COLS + cc;+ int lo = 0, hi = (int)cellCount - 1, gi = -1;+ while (lo <= hi) { int mid = (lo + hi) >> 1; if (cellIds[mid] < cellv) lo = mid + 1; else if (cellIds[mid] > cellv) hi = mid - 1; else { gi = mid; break; } }+ if (gi < 0) continue;+ int start = cellStarts[gi];+ int end = (gi + 1 < (int)cellCount) ? cellStarts[gi + 1] : n;+ for (int i = start; i < end; i++) {+ double dLat = cols[0].get(i) - qLatM;+ double dLon = (cols[1].get(i) - qLonM) * lonScale;+ double d = dLat * dLat + dLon * dLon;+ if (d < bestDist) { bestDist = d; bestRec = i; }+ }+ }+ }+ }+ return bestRec;+ };+ auto compareKey = [&](int rec, int co, int stt, int ci, int str) {+ int c;+ c = cols[6].get(rec) - co; if (c) return c;+ c = cols[5].get(rec) - stt; if (c) return c;+ c = cols[4].get(rec) - ci; if (c) return c;+ return cols[3].get(rec) - str;+ };+ auto resolve = [&](int rec, const char* tag) {+ fprintf(stderr, " %s rec=%d %.6f,%.6f %s %s, %s, %s, %s %s\n", tag, rec,+ cols[0].get(rec) / 1e6, cols[1].get(rec) / 1e6,+ dict[F_HOUSE][cols[2].get(rec)].c_str(), dict[F_STREET][cols[3].get(rec)].c_str(),+ dict[F_CITY][cols[4].get(rec)].c_str(), dict[F_STATE][cols[5].get(rec)].c_str(),+ dict[F_COUNTRY][cols[6].get(rec)].c_str(), dict[F_POSTCODE][cols[7].get(rec)].c_str());+ };++ int samples[] = {0, n / 3, (2 * n) / 3, n - 1};+ int prev = -1;+ for (int s : samples) {+ if (s < 0 || s >= n || s == prev) continue;+ prev = s;+ resolve(s, "sample");+ // Forward round-trip: this record must be findable by its own key.+ int co = cols[6].get(s), stt = cols[5].get(s), ci = cols[4].get(s), str = cols[3].get(s);+ int lo = 0, hi = n;+ while (lo < hi) { int mid = (lo + hi) >> 1; if (compareKey(fwd.get(mid), co, stt, ci, str) < 0) lo = mid + 1; else hi = mid; }+ bool found = false;+ for (int k = lo; k < n; k++) { int rec = fwd.get(k); if (compareKey(rec, co, stt, ci, str) != 0) break; if (rec == s) { found = true; break; } }+ if (!found) die("verify: forward round-trip failed");+ // Reverse round-trip: nearest to the record's own coordinate is at that exact coordinate.+ double lat = cols[0].get(s) / 1e6, lon = cols[1].get(s) / 1e6;+ int rr = reverse(lat, lon);+ if (rr < 0) die("verify: reverse returned nothing");+ if (cols[0].get(rr) != toMicro(lat) || cols[1].get(rr) != toMicro(lon))+ die("verify: reverse nearest not at query coordinate");+ }++ fprintf(stderr, "Verify OK: n=%d, dicts[h/s/c/st/co/pc]=%zu/%zu/%zu/%zu/%zu/%zu, cells=%u, size=%zu bytes.\n",+ n, dict[0].size(), dict[1].size(), dict[2].size(), dict[3].size(), dict[4].size(), dict[5].size(),+ cellCount, db.size);+}++// ------------------------------------------------------------------ main+int main(int argc, char** argv) {+ if (argc >= 4 && strcmp(argv[1], "generate") == 0) { generate(argv[2], argv[3]); return 0; }+ if (argc >= 3 && strcmp(argv[1], "verify") == 0) { verify(argv[2]); return 0; }+ if (argc == 3) { generate(argv[1], argv[2]); return 0; } // shorthand: <in> <out>+ fprintf(stderr,+ "usage:\n"+ " %s generate <addr.geojsonseq> <geocoder.geodb>\n"+ " %s verify <geocoder.geodb>\n",+ argv[0], argv[0]);+ return 2;+}
scripts/geocoder_gen.sh
diff --git a/scripts/geocoder_gen.sh b/scripts/geocoder_gen.shnew file mode 100644index 0000000000..7f150b73ec--- /dev/null+++ b/scripts/geocoder_gen.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# Build and run the offline geocoder database generator (scripts/geocoder_gen.cpp).+#+# Pipeline:+# planet-latest.osm.pbf --osmium--> addr.geojsonseq --geocoder_gen--> geocoder.geodb+#+# The generator self-verifies its output (reverse + forward round-trip) before finishing.+# Nothing here is committed except this script and geocoder_gen.cpp; simdjson and the build+# artifacts live in a scratch dir. Intended to run under WSL/Linux on the build machine.+#+# Usage:+# scripts/geocoder_gen.sh # full run (extract if needed, build, generate)+# PBF=... GEOJSON=... OUT=... scripts/geocoder_gen.sh+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+SCRATCH="${SCRATCH:-$HOME/geocoder-scratch}"+BUILD="$SCRATCH/build"+PBF="${PBF:-$SCRATCH/planet-latest.osm.pbf}"+GEOJSON="${GEOJSON:-$SCRATCH/addr.geojsonseq}"+OUT="${OUT:-$SCRATCH/geocoder.geodb}"+SIMDJSON_TAG="${SIMDJSON_TAG:-v3.11.0}"++mkdir -p "$BUILD"++echo "==> Toolchain check (no sudo; libzstd is linked from the existing runtime .so)"+command -v g++ >/dev/null || { echo "g++ not found. Install: sudo apt-get install -y g++" >&2; exit 1; }+ZSTD_SO="$(ldconfig -p | awk '/libzstd\.so/{print $NF; exit}')"+[ -n "$ZSTD_SO" ] || { echo "libzstd runtime not found (libzstd.so*). Install: sudo apt-get install -y libzstd1" >&2; exit 1; }+echo " using libzstd: $ZSTD_SO"++echo "==> Headers: simdjson ($SIMDJSON_TAG) + zstd.h"+if [ ! -f "$BUILD/simdjson.cpp" ] || [ ! -f "$BUILD/simdjson.h" ]; then+ base="https://raw.githubusercontent.com/simdjson/simdjson/$SIMDJSON_TAG/singleheader"+ curl -fL --ipv4 -o "$BUILD/simdjson.h" "$base/simdjson.h"+ curl -fL --ipv4 -o "$BUILD/simdjson.cpp" "$base/simdjson.cpp"+fi+if [ ! -f "$BUILD/zstd.h" ]; then+ curl -fL --ipv4 -o "$BUILD/zstd.h" \+ "https://raw.githubusercontent.com/facebook/zstd/${ZSTD_TAG:-v1.5.5}/lib/zstd.h"+fi++echo "==> Compiling geocoder_gen"+g++ -O2 -fopenmp -std=c++17 -I"$BUILD" \+ "$HERE/geocoder_gen.cpp" "$BUILD/simdjson.cpp" \+ "$ZSTD_SO" -o "$BUILD/geocoder_gen"++if [ ! -f "$GEOJSON" ]; then+ echo "==> Extracting addresses from $PBF (osmium; multi-hour)"+ command -v osmium >/dev/null || { echo "osmium not found. Install: sudo apt-get install -y osmium-tool" >&2; exit 1; }+ [ -f "$PBF" ] || { echo "planet PBF not found: $PBF" >&2; exit 1; }+ osmium tags-filter "$PBF" \+ n/addr:housenumber w/addr:housenumber r/addr:housenumber \+ -o "$SCRATCH/filtered.osm.pbf" --overwrite+ osmium export "$SCRATCH/filtered.osm.pbf" -f geojsonseq -o "$GEOJSON" --overwrite+fi++echo "==> Generating $OUT from $GEOJSON"+"$BUILD/geocoder_gen" generate "$GEOJSON" "$OUT"++echo "==> Result"+ls -lh "$OUT"+sha256sum "$OUT"