networklocation: add offline planet geocoder core (packed format + reader + tests)
- Commit
d4931a7afb409616942f7aa5f4acc3011fc0ff6a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-09 20:44 UTC (3 months ago)
- Parents
ea767ed
Diff
networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsnew file mode 100644index 0000000000..b81f9f9c2d--- /dev/null+++ b/networklocation/build.gradle.kts@@ -0,0 +1,18 @@+plugins {+ id("common-conventions-app")+}++launcherIcon {+ symbol = "my_location"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.networklocation"+ }+}++dependencies {+ // Geocoder DB is a self-contained mmap'd binary (see geocoder/). Block compression uses+ // java.util.zip (Deflate) โ no external dependency needed for the core.+}
networklocation/src/main/AndroidManifest.xml
diff --git a/networklocation/src/main/AndroidManifest.xml b/networklocation/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7b1bdd3177--- /dev/null+++ b/networklocation/src/main/AndroidManifest.xml@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application+ android:allowBackup="false"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">++ <!-- Status/info screen. The geocoder + network-location provider services (which bind+ to the framework via com.android.location.provider) are added in a follow-up once+ the compile-only provider stubs + priv-app allowlist are in place. -->+ <activity+ android:name=".MainActivity"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>++</manifest>
networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.ktnew file mode 100644index 0000000000..cb9e9d2ffb--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.kt@@ -0,0 +1,52 @@+package com.vayunmathur.networklocation++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text++/**+ * Status screen for the system network-location + geocoder provider. This app is primarily+ * headless (two bound framework services); the launcher entry just reports state.+ */+class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ Surface(modifier = Modifier.fillMaxSize()) {+ Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(24.dp)+ ) {+ Text(+ "Network Location & Geocoder",+ style = MaterialTheme.typography.headlineSmall,+ )+ Text(+ "Provides the system network-location provider (via the " ++ "GrapheneOS proxy) and an on-device, offline geocoder. " ++ "Always on โ there is no disable switch.",+ modifier = Modifier.padding(top = 12.dp),+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ }+ }+ }+ }+}
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.ktnew file mode 100644index 0000000000..6eccdb9a7d--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDb.kt@@ -0,0 +1,293 @@+package com.vayunmathur.networklocation.geocoder++import java.io.ByteArrayOutputStream+import java.io.DataOutputStream+import java.io.File+import java.util.zip.Deflater+import java.util.zip.Inflater+import kotlin.math.max+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+ * Deflate-compressed blocks so the reader mmaps the file and inflates 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 = 1+ 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+ }+ }+}++private fun deflate(data: ByteArray): ByteArray {+ val d = Deflater(Deflater.BEST_COMPRESSION, true)+ d.setInput(data); d.finish()+ val out = ByteArrayOutputStream(max(64, data.size / 2))+ val buf = ByteArray(8192)+ while (!d.finished()) out.write(buf, 0, d.deflate(buf))+ d.end()+ return out.toByteArray()+}++internal fun inflate(data: ByteArray, expected: Int): ByteArray {+ val inf = Inflater(true)+ inf.setInput(data)+ val out = ByteArray(expected)+ var off = 0+ while (off < expected && !inf.finished()) off += inf.inflate(out, off, expected - off)+ inf.end()+ return out+}++// ---------------------------------------------------------------------------------------------+// Writer.+// ---------------------------------------------------------------------------------------------++/** Column encoded as delta+zigzag+varint per block, each block Deflate-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 = deflate(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 = deflate(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, deflated 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/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.ktnew file mode 100644index 0000000000..27de389377--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/geocoder/GeoDbReader.kt@@ -0,0 +1,287 @@+package com.vayunmathur.networklocation.geocoder++import java.io.DataInputStream+import java.io.File+import java.io.RandomAccessFile+import kotlin.math.cos+import kotlin.math.min++/**+ * Reader for a [GeoDb] file. Dictionaries and the grid directory are held in memory; address+ * columns are read block-by-block from the file on demand (seek + inflate one block), so the+ * bulk of the database is never resident. Supports reverse (coord -> address) and structured+ * forward (country/state/city/street -> addresses) geocoding.+ */+class GeoDbReader(file: File) : AutoCloseable {+ private val raf = RandomAccessFile(file, "r")+ 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 {+ raf.seek(0)+ require(raf.readInt() == GeoDb.MAGIC) { "bad magic" }+ require(raf.readInt() == GeoDb.VERSION) { "bad version" }+ n = raf.readInt()++ fun readSectionBytes(): ByteArray {+ val size = raf.readInt()+ val b = ByteArray(size)+ raf.readFully(b)+ return b+ }+ fun sectionOffset(): Pair<Long, Int> {+ val size = raf.readInt()+ val off = raf.filePointer+ raf.seek(off + size) // skip body; we'll seek back for block reads+ return off to size+ }++ dictHouse = decodeDict(readSectionBytes())+ dictStreet = decodeDict(readSectionBytes())+ dictCity = decodeDict(readSectionBytes())+ dictState = decodeDict(readSectionBytes())+ dictCountry = decodeDict(readSectionBytes())+ dictPostcode = decodeDict(readSectionBytes())++ // Phase 1: record column offsets by skipping their bodies (do NOT build Column yet โ+ // Column construction seeks, which would corrupt this sequential scan).+ val colOffsets = LongArray(GeoDb.COLUMN_COUNT)+ for (i in 0 until GeoDb.COLUMN_COUNT) colOffsets[i] = sectionOffset().first++ // Grid directory.+ 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 = sectionOffset().first++ // Phase 2: now that the sequential scan is done, build the on-demand column readers.+ val delta = booleanArrayOf(true, true, false, false, false, false, false, false)+ columns = Array(GeoDb.COLUMN_COUNT) { i -> Column(raf, colOffsets[i], delta[i]) }+ fwd = Column(raf, 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)) {+ // Only scan the ring edge on expansions after the first.+ 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 (case-insensitive exact on each 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)+ // Lower bound over the forward ordering.+ 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 {+ // Dictionaries are stored sorted (lexical), so binary search matches the stored order.+ 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() = raf.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 = inflate(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 inflates and+ * decodes a single block per access, caching the most recently used block.+ */+private class Column(+ private val raf: RandomAccessFile,+ 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 {+ synchronized(raf) {+ raf.seek(sectionOffset)+ n = raf.readInt()+ blockCount = raf.readInt()+ rawLens = IntArray(blockCount)+ compLens = IntArray(blockCount)+ for (b in 0 until blockCount) { rawLens[b] = raf.readInt(); compLens[b] = raf.readInt() }+ val bodyStart = raf.filePointer+ blockFileOffset = LongArray(blockCount)+ var off = bodyStart+ for (b in 0 until blockCount) { blockFileOffset[b] = off; off += compLens[b] }+ }+ }++ 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 = ByteArray(compLens[block])+ synchronized(raf) {+ raf.seek(blockFileOffset[block])+ raf.readFully(comp)+ }+ val raw = inflate(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/res/values/strings.xml
diff --git a/networklocation/src/main/res/values/strings.xml b/networklocation/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..07b0225a7f--- /dev/null+++ b/networklocation/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Network Location</string>+</resources>
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.ktnew file mode 100644index 0000000000..13bdd0f3ed--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeoDbTest.kt@@ -0,0 +1,74 @@+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")+ }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex a79b4ccf91..2d816392cd 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -87,6 +87,7 @@ include(":speech") include(":vpn") include(":web") include(":appstore")+include(":networklocation") include(":fooddelivery") include(":musicbrainz") include(":measure")