networklocation: mmap geocoder, live location check, drop beacon cache
- Commit
4662bd657966f7252b8e88487b0f5323c3ca878e- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 17:23 UTC (1 month ago)
- Parents
79d0c15
Diff
networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsindex 7f71732ac1..51b7639931 100644--- a/networklocation/build.gradle.kts+++ b/networklocation/build.gradle.kts@@ -21,11 +21,11 @@ androidComponents { } // Native code for this module, loaded as libnetworklocation.so: RANSAC + EM multilateration-// device-position estimation over the cached beacon fixes, AND the offline geocoder-// search over geocoder.geodb. Both live in networklocation/src/main/rust/.+// device-position estimation over the resolved beacon fixes, AND the offline geocoder+// search over geocoder.db. Both live in networklocation/src/main/rust/. rustNativeLib("networklocation") -// The offline databases (geocoder.geodb ~1-1.5 GB, wifi.wpsdb up to ~2 GB, cells.wpsdb far+// The offline databases (geocoder.db, wifi.wpsdb up to ~2 GB, cells.wpsdb far // smaller) are NOT bundled. Shipping them as assets put a 3.5 GB APK in the MAOS system image, // which pushed the factory install zip past fastboot's 4 GiB zip limit. They are downloaded to // device-protected storage on request instead — see OfflineDatabases.kt. Until they arrive every@@ -36,16 +36,11 @@ 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. compileOnly(project(":library:locationprovider"))- // Beacon-location cache (in-memory TimedLruCache in front of a Room table).- // No SQLCipher here — the cache holds only public beacon coordinates, so it uses- // AndroidSQLiteDriver (platform SQLite), which Room 3 requires to be set explicitly.- implementRoom(libs)- implementation(libs.androidx.sqlite.framework) // Reporting loop + IO for the offline database fetch. implementation(libs.kotlinx.coroutines.android) // Resumable, checksummed, unmetered-only fetch of the offline databases, which are no // longer bundled (see OfflineDatabases). Also supplies the progress UI on the status screen. implementation(project(":library:downloadservice"))- // The offline geocoder search runs natively (Rust/ruzstd) over geocoder.geodb; there is no+ // The offline geocoder search runs natively (Rust/ruzstd) over geocoder.db; there is no // Kotlin-side DB code, so no zstd-jni / serialization deps are needed here. }
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.ktindex 24eab17ca4..1fdf8bff84 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt@@ -8,7 +8,7 @@ package com.vayunmathur.networklocation * forward queries entirely in Rust. * * Results are flat String arrays with [FIELDS_PER_RESULT] entries per result:- * `[lat, lon, name, house, street, city, state, country, postcode, kind]`, lat/lon to 7 dp.+ * `[lat, lon, name, house, street, city, state, country, postcode, kind]`, lat/lon to 5 dp. * * The fully-qualified name MUST stay `com.vayunmathur.networklocation.GeocoderNative` so the * JNI symbol mangling (`Java_com_vayunmathur_networklocation_GeocoderNative_*`) matches.
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.ktindex 3c40f85340..0f8bc1b6f1 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/MainActivity.kt@@ -1,53 +1,17 @@ package com.vayunmathur.networklocation -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.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.MaActivity-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); this screen just reports state and offers the- * offline-database download. It has no launcher entry — Settings links to it from+ * headless (two bound framework services); the UI only downloads the offline databases and then+ * shows a live check. It has no launcher entry — Settings links to it from * Location -> Location services. */ class MainActivity : MaActivity() { @Composable override fun Content() {- Surface(modifier = Modifier.fillMaxSize()) {- // Letterboxed on expanded windows so the status text keeps a readable measure.- DesktopMaxWidthContainer {- Column(- Modifier- .fillMaxSize()- .verticalScroll(rememberScrollState())- .padding(24.dp)- ) {- Text(- "Network Location & Geocoder",- style = MaterialTheme.typography.headlineSmall,- )- Text(- "Provides the system network-location provider and an " +- "on-device, offline geocoder. Both resolve entirely on " +- "device from the downloaded databases below — nothing is " +- "sent to a positioning service. Always on — there is no " +- "disable switch.",- modifier = Modifier.padding(top = 12.dp),- style = MaterialTheme.typography.bodyMedium,- )- OfflineDatabaseSection(Modifier.padding(top = 24.dp))- }- }- }+ Navigation() } }
networklocation/src/main/java/com/vayunmathur/networklocation/Navigation.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/Navigation.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/Navigation.ktnew file mode 100644index 0000000000..73aa5effa4--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/Navigation.kt@@ -0,0 +1,25 @@+package com.vayunmathur.networklocation++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.networklocation.ui.SetupScreen+import com.vayunmathur.networklocation.ui.StatusScreen++@Composable+fun Navigation() {+ val context = LocalContext.current+ val start = remember { if (OfflineDatabases.allPresent(context)) Route.Status else Route.Setup }+ val backStack = rememberNavBackStack<Route>(start)++ MainNavigation(backStack) {+ entry<Route.Setup> {+ // reset() rather than add(): once the databases are installed there is nothing to go+ // back to, and leaving Setup on the stack would let Back return to a finished download.+ SetupScreen(onReady = { backStack.reset(Route.Status) })+ }+ entry<Route.Status> { StatusScreen() }+ }+}
networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabaseSection.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabaseSection.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabaseSection.ktindex 60a8185a95..0f7a44753e 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabaseSection.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabaseSection.kt@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -32,15 +33,19 @@ import com.vayunmathur.library.util.DataStoreUtils * unavailable until the geocoder database arrives. */ @Composable-fun OfflineDatabaseSection(modifier: Modifier = Modifier) {+fun OfflineDatabaseSection(modifier: Modifier = Modifier, onReady: () -> Unit = {}) { val context = LocalContext.current val ds = remember { DataStoreUtils.getInstance(context) } - // Presence is read once per composition rather than observed: the files only appear when a- // download finishes, and the progress rows below already track that. val databases = remember { offlineDatabaseEntries() } var requested by remember { mutableStateOf(false) }- val allPresent = remember(requested) { OfflineDatabases.allPresent(context) }+ // Presence is re-read whenever a download's progress moves: the worker publishes 1.0 only+ // after the finished file has been renamed into place, so the last tick sees it on disk.+ val progress = databases.map { (name, _, _) -> ds.doubleFlow("progress_$name").collectAsState(0.0).value }+ val allPresent = remember(requested, progress) { OfflineDatabases.allPresent(context) }+ LaunchedEffect(allPresent) {+ if (allPresent) onReady()+ } Column(modifier) { Text("Offline databases", style = MaterialTheme.typography.titleMedium)
networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabases.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabases.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabases.ktindex 8314fcff2d..65062d401d 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabases.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/OfflineDatabases.kt@@ -4,6 +4,7 @@ import android.content.Context import android.os.ParcelFileDescriptor import java.io.File import java.io.IOException+import java.io.RandomAccessFile /** * The offline databases the provider reads, and where they live on disk.@@ -16,24 +17,37 @@ import java.io.IOException * Absence is a supported state, not an error: every reader treats a zero handle as "no data", * so beacon lookups miss and the geocoder reports itself unavailable. *- * ## Filenames carry the format version+ * ## Format versions *- * A new database format gets a new filename rather than a version field the readers negotiate.- * The files are a cache of a published artifact, not user data, so there is nothing to migrate- * — an old file is simply a name nobody asks for, and [pruneStale] reclaims its multiple- * gigabytes. This keeps exactly one format alive in each reader.+ * The beacon stores carry their format version in the filename: a new format gets a new name+ * rather than a version field the readers negotiate. The geocoder keeps one name and carries its+ * version in the file header; [isPresent] reads that header, so a geocoder in an old format+ * counts as absent and the download replaces it. Either way the files are a cache of a+ * published artifact, not user data, so there is nothing to migrate — an old file is simply a+ * name nobody asks for, and [pruneStale] reclaims its multiple gigabytes. */ object OfflineDatabases {- const val GEOCODER = "geocoder-v3.geodb"- const val WIFI = "wifi-v2.wpsdb"- const val CELL = "cells-v2.wpsdb"+ const val GEOCODER = "geocoder.db"+ const val WIFI = "wifi-v3.wpsdb"+ const val CELL = "cells-v3.wpsdb" /** Names shipped by earlier versions of the app, deleted on sight to reclaim space. */- private val SUPERSEDED = listOf("geocoder.geodb", "wifi.wpsdb", "cells.wpsdb")+ private val SUPERSEDED = listOf(+ "geocoder.geodb",+ "geocoder-v3.geodb",+ "wifi.wpsdb",+ "cells.wpsdb",+ "wifi-v2.wpsdb",+ "cells-v2.wpsdb",+ ) private const val GEOCODER_URL = "https://data.maproj.org/geocoder/$GEOCODER" private const val WPS_BASE_URL = "https://data.maproj.org/wps/" + /** `"MAGE"` and the format version `geocoder.rs` reads; must match `VERSION` there. */+ private const val GEOCODER_MAGIC = 0x4D414745+ private const val GEOCODER_VERSION = 5+ /** * Expected SHA-256 of each published database, verified by `:library:downloadservice` * after the transfer and refetched on mismatch.@@ -42,11 +56,15 @@ object OfflineDatabases { * chunks, and a truncated file is non-empty, so without a checksum it reads as installed * and then fails its magic check on every open, forever. *- * A null hash means the download is accepted unverified. The beacon stores stay null until- * a crawl has been run and published.+ * A null hash means the download is accepted unverified. Each stays null until its database+ * has been built and published. */ fun sha256For(name: String): String? = when (name) {- GEOCODER -> "97284c7a1f7d07db4c448ce62c6f3b86cbf4d38293e6c4d4d8157a04394e9593"+ GEOCODER -> "a9a3b21eba93fcf4549c077c8a2a74ae561570878c63988601505a5fe6a6f942"+ // A device that has a store counts it as installed and never refetches it, so new+ // content for a beacon store must ship under a new filename, not just a new hash.+ WIFI -> "c8aa83f577d90d250d76912df2adde8a8e0d0bc0dcb4c87fe9e9916a59e822db"+ CELL -> "3c7bf475e58f1c912aa45d47ac12d7cd7e76fc2c4d10c3b46859b1027e7660c3" else -> null } @@ -65,7 +83,18 @@ object OfflineDatabases { fun file(context: Context, name: String): File = File(dir(context), name) - fun isPresent(context: Context, name: String): Boolean = file(context, name).length() > 0+ fun isPresent(context: Context, name: String): Boolean {+ val f = file(context, name)+ if (f.length() <= 0) return false+ return name != GEOCODER || hasCurrentGeocoderHeader(f)+ }++ /** Header is big-endian, which is what [RandomAccessFile.readInt] reads. */+ private fun hasCurrentGeocoderHeader(f: File): Boolean = try {+ RandomAccessFile(f, "r").use { it.readInt() == GEOCODER_MAGIC && it.readInt() == GEOCODER_VERSION }+ } catch (_: IOException) {+ false+ } fun allPresent(context: Context): Boolean = listOf(GEOCODER, WIFI, CELL).all { isPresent(context, it) }
networklocation/src/main/java/com/vayunmathur/networklocation/Route.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/Route.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/Route.ktnew file mode 100644index 0000000000..f2987d39ef--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/Route.kt@@ -0,0 +1,15 @@+package com.vayunmathur.networklocation++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ /** Offline-database download. Shown until every database is on disk. */+ @Serializable+ data object Setup : Route++ /** Live GPS, network-location and geocoder check, once the databases are installed. */+ @Serializable+ data object Status : Route+}
networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.ktdeleted file mode 100644index 249815ad9a..0000000000--- a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt+++ /dev/null@@ -1,105 +0,0 @@-package com.vayunmathur.networklocation.cache--import android.content.Context-import androidx.room3.Dao-import androidx.room3.Database-import androidx.room3.Entity-import androidx.room3.PrimaryKey-import androidx.room3.Query-import androidx.room3.Room-import androidx.room3.RoomDatabase-import androidx.room3.Upsert-import androidx.sqlite.driver.AndroidSQLiteDriver-import com.vayunmathur.networklocation.BeaconFix-import com.vayunmathur.networklocation.BeaconId--/**- * Stable string key for a beacon, used as the cache primary key.- *- * The radio type is part of a cell's key for the same reason it is part of its store key: an- * LTE ECI and a GSM CID are the same number in the same network and area code, so leaving it- * out would let one tower's cached fix answer for the other.- */-fun BeaconId.key(): String = when (this) {- is BeaconId.Wifi -> "wifi:${bssid.lowercase()}"- is BeaconId.Cell -> "cell:${radio.wire}:$mcc:$mnc:$cellId:$tacOrLac"-}--@Entity(tableName = "beacon")-data class CachedBeaconEntity(- @PrimaryKey val key: String,- val latitude: Double,- val longitude: Double,- val accuracyMeters: Double,- val updatedAt: Long,-)--@Dao-interface BeaconDao {- @Query("SELECT * FROM beacon WHERE key IN (:keys)")- suspend fun byKeys(keys: List<String>): List<CachedBeaconEntity>-- @Upsert- suspend fun upsertAll(rows: List<CachedBeaconEntity>)-- @Query("DELETE FROM beacon WHERE updatedAt < :cutoff")- suspend fun deleteOlderThan(cutoff: Long)-}--@Database(entities = [CachedBeaconEntity::class], version = 1, exportSchema = false)-abstract class BeaconDatabase : RoomDatabase() {- abstract fun beaconDao(): BeaconDao-}--/**- * Two-tier beacon-location cache: an in-memory [TimedLruCache] in front of a Room- * table. Beacon coordinates are effectively static, so caching them locally is the- * whole point - it means a given AP/tower is looked up in the offline store once,- * then served from memory (until the TTL sweep). The cache holds only public beacon- * coordinates, so it is stored unencrypted.- */-class BeaconCache(- context: Context,- private val memory: TimedLruCache<String, BeaconFix> =- TimedLruCache(maxSize = 4096, ttlMillis = 24L * 60 * 60 * 1000),-) {- private val dao: BeaconDao =- Room.databaseBuilder(- context.applicationContext,- BeaconDatabase::class.java,- "networklocation-beacons",- ).setDriver(AndroidSQLiteDriver()).build().beaconDao()-- /** Fetch cached fixes for [ids], checking memory first then the DB. */- suspend fun get(ids: List<BeaconId>): Map<BeaconId, BeaconFix> {- if (ids.isEmpty()) return emptyMap()- val out = HashMap<BeaconId, BeaconFix>(ids.size)- val misses = ArrayList<BeaconId>()- for (id in ids) {- val hit = memory.get(id.key())- if (hit != null) out[id] = hit else misses.add(id)- }- if (misses.isNotEmpty()) {- val byKey = misses.associateBy { it.key() }- for (row in dao.byKeys(misses.map { it.key() })) {- val id = byKey[row.key] ?: continue- val fix = BeaconFix(id, row.latitude, row.longitude, row.accuracyMeters)- memory.put(row.key, fix)- out[id] = fix- }- }- return out- }-- /** Persist newly-resolved [fixes] into both tiers. */- suspend fun put(fixes: List<BeaconFix>) {- if (fixes.isEmpty()) return- val now = System.currentTimeMillis()- for (f in fixes) memory.put(f.id.key(), f)- dao.upsertAll(- fixes.map {- CachedBeaconEntity(it.id.key(), it.latitude, it.longitude, it.accuracyMeters, now)- },- )- }-}
networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.ktdeleted file mode 100644index 944650ab2c..0000000000--- a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt+++ /dev/null@@ -1,42 +0,0 @@-package com.vayunmathur.networklocation.cache--/**- * A size- and time-bounded LRU cache. Entries older than [ttlMillis] are treated- * as absent; once [maxSize] is exceeded the least-recently-used live entry is- * evicted. Used as the in-memory front of the persistent beacon cache so repeat- * scans in one session never touch the DB (or the network).- *- * Not thread-safe on its own; callers synchronize (the reporting loop is- * single-threaded, but [get]/[put] are `@Synchronized` for safety).- */-class TimedLruCache<K, V>(- private val maxSize: Int,- private val ttlMillis: Long,- private val clock: () -> Long = System::currentTimeMillis,-) {- private data class Timed<V>(val value: V, val insertedAt: Long)-- // accessOrder=true makes this a genuine LRU: get() moves the entry to the tail.- private val map = object : LinkedHashMap<K, Timed<V>>(16, 0.75f, true) {- override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, Timed<V>>): Boolean =- size > maxSize- }-- @Synchronized- fun get(key: K): V? {- val entry = map[key] ?: return null- if (clock() - entry.insertedAt > ttlMillis) {- map.remove(key)- return null- }- return entry.value- }-- @Synchronized- fun put(key: K, value: V) {- map[key] = Timed(value, clock())- }-- @Synchronized- fun clear() = map.clear()-}
networklocation/src/main/java/com/vayunmathur/networklocation/platform/LocationFeeds.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/platform/LocationFeeds.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/platform/LocationFeeds.ktnew file mode 100644index 0000000000..51b581db14--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/platform/LocationFeeds.kt@@ -0,0 +1,71 @@+package com.vayunmathur.networklocation.platform++import android.Manifest+import android.annotation.SuppressLint+import android.content.Context+import android.content.pm.PackageManager+import android.location.Address+import android.location.Geocoder+import android.location.Location+import android.location.LocationListener+import android.location.LocationManager+import android.os.Build+import android.os.Looper+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import java.util.Locale+import kotlin.coroutines.resume++private const val UPDATE_INTERVAL_MS = 1_000L++fun hasFineLocation(context: Context): Boolean =+ context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) ==+ PackageManager.PERMISSION_GRANTED++/**+ * Fixes from one system provider, starting with its last known fix. Emits nothing if the+ * provider does not exist on this device or location permission is missing.+ */+@SuppressLint("MissingPermission")+fun locationUpdates(context: Context, provider: String): Flow<Location> = callbackFlow {+ val lm = context.getSystemService(LocationManager::class.java)+ if (lm == null || !lm.hasProvider(provider) || !hasFineLocation(context)) {+ awaitClose { }+ return@callbackFlow+ }+ lm.getLastKnownLocation(provider)?.let { trySend(it) }+ val listener = LocationListener { trySend(it) }+ lm.requestLocationUpdates(provider, UPDATE_INTERVAL_MS, 0f, listener, Looper.getMainLooper())+ awaitClose { lm.removeUpdates(listener) }+}++/**+ * Reverse-geocode through the system [Geocoder], i.e. through this app's own+ * `GeocodeService` exactly as any other app would reach it. Calling the native reader directly+ * would open a second copy of the multi-gigabyte database in this process.+ */+suspend fun reverseGeocode(context: Context, lat: Double, lon: Double): Result<Address?> {+ val geocoder = Geocoder(context, Locale.getDefault())+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ suspendCancellableCoroutine { cont ->+ geocoder.getFromLocation(lat, lon, 1, object : Geocoder.GeocodeListener {+ override fun onGeocode(addresses: MutableList<Address>) {+ cont.resume(Result.success(addresses.firstOrNull()))+ }++ override fun onError(errorMessage: String?) {+ cont.resume(Result.failure(IllegalStateException(errorMessage ?: "geocoder error")))+ }+ })+ }+ } else {+ withContext(Dispatchers.IO) {+ @Suppress("DEPRECATION")+ runCatching { geocoder.getFromLocation(lat, lon, 1)?.firstOrNull() }+ }+ }+}
networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.ktindex af3a2776ac..b14a200709 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt@@ -4,11 +4,11 @@ import android.content.Context import android.location.Location import android.location.LocationManager import android.os.SystemClock+import com.vayunmathur.library.log.Log import com.vayunmathur.networklocation.BeaconFix import com.vayunmathur.networklocation.BeaconId import com.vayunmathur.networklocation.DevicePosition import com.vayunmathur.networklocation.NetworkLocationNative-import com.vayunmathur.networklocation.cache.BeaconCache import com.vayunmathur.networklocation.cell.NearbyCells import com.vayunmathur.networklocation.wifi.NearbyWifi import kotlinx.coroutines.CoroutineScope@@ -18,16 +18,17 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext /**- * The periodic fix loop: scan nearby radios, resolve them to coordinates against the- * cache and the offline WPSDB stores, and estimate the device position with the native- * solver. Reconstructs GrapheneOS's LocationReportingTask.+ * The periodic fix loop: scan nearby radios, resolve them to coordinates against the offline+ * WPSDB stores, and estimate the device position with the native solver. Reconstructs+ * GrapheneOS's LocationReportingTask. *- * Resolution is entirely on-device. Beacons absent from both tiers are dropped, so a- * fix is produced only from what the downloaded stores know; if they have not been- * downloaded yet, no fix is produced at all.+ * Resolution is entirely on-device. A store lookup is a few probes into a memory-mapped file,+ * so beacons are resolved fresh on every scan rather than cached: a cache would only hold a+ * second copy of coordinates the mapping already serves, in heap instead of reclaimable page+ * cache. Beacons absent from the stores are dropped, so a fix is produced only from what the+ * downloaded stores know; if they have not been downloaded yet, no fix is produced at all. */ class LocationReportingTask( context: Context,@@ -36,7 +37,6 @@ class LocationReportingTask( private val appContext = context.applicationContext private val wifi = NearbyWifi(appContext) private val cells = NearbyCells(appContext)- private val cache = BeaconCache(appContext) private val offlineStore = OfflineBeaconStore(appContext) private var scope: CoroutineScope? = null@@ -47,7 +47,7 @@ class LocationReportingTask( scope = newScope newScope.launch { while (isActive) {- runCatching { reportOnce() }+ runCatching { reportOnce() }.onFailure { Log.error(TAG, "fix attempt failed", it) } delay(intervalMillis.coerceAtLeast(MIN_INTERVAL_MS)) } }@@ -59,20 +59,25 @@ class LocationReportingTask( offlineStore.close() } - private suspend fun reportOnce() {+ private fun reportOnce() { val position = estimate() ?: return onFix(position.toLocation()) } /** Full pipeline for a single fix; null when there are no usable beacons. */- private suspend fun estimate(): DevicePosition? {+ private fun estimate(): DevicePosition? { val wifiIds = wifi.scan() val cellIds = cells.scan()- val allIds: List<BeaconId> = wifiIds + cellIds- if (allIds.isEmpty()) return null+ if (wifiIds.isEmpty() && cellIds.isEmpty()) {+ trace("no beacons scanned")+ return null+ } - val fixes = resolveFixes(wifiIds, cellIds, allIds)- if (fixes.isEmpty()) return null+ val fixes = resolveFixes(wifiIds, cellIds)+ if (fixes.isEmpty()) {+ trace("wifi=${wifiIds.size} cell=${cellIds.size} resolved=0 ${offlineStore.describe()}")+ return null+ } val interleaved = DoubleArray(fixes.size * COORDS_PER_FIX) for ((i, f) in fixes.withIndex()) {@@ -80,39 +85,30 @@ class LocationReportingTask( interleaved[i * COORDS_PER_FIX + 1] = f.longitude interleaved[i * COORDS_PER_FIX + 2] = f.accuracyMeters }- val out = NetworkLocationNative.estimatePosition(interleaved) ?: return null- return DevicePosition(out[0], out[1], out[2])+ val out = NetworkLocationNative.estimatePosition(interleaved)+ trace(+ "wifi=${wifiIds.size} cell=${cellIds.size} resolved=${fixes.size} " ++ "solver=${if (out == null) "no fix" else "fix"}",+ )+ return out?.let { DevicePosition(it[0], it[1], it[2]) } } - private suspend fun resolveFixes(- wifiIds: List<BeaconId.Wifi>,- cellIds: List<BeaconId.Cell>,- allIds: List<BeaconId>,- ): List<BeaconFix> {- val cached = cache.get(allIds)- val resolved = ArrayList(cached.values)+ private var lastTrace: String? = null - val missingWifi = wifiIds.filter { it !in cached }- val missingCell = cellIds.filter { it !in cached }-- // Offline store tier: the only source of new beacon coordinates. Hits are written- // back into BeaconCache so the in-memory/Room tier front-runs later scans. Beacons- // absent from the stores stay unresolved and are simply left out of the solve.- if (missingWifi.isNotEmpty() || missingCell.isNotEmpty()) {- val offline = withContext(Dispatchers.Default) {- buildList {- if (missingWifi.isNotEmpty()) addAll(offlineStore.resolveWifi(missingWifi).values)- if (missingCell.isNotEmpty()) addAll(offlineStore.resolveCell(missingCell).values)- }- }- if (offline.isNotEmpty()) {- cache.put(offline)- resolved.addAll(offline)- }- }- return resolved+ /**+ * One status line whenever the pipeline's outcome changes, so a provider that never+ * reports says why. Counts only: beacon identities and positions are never logged.+ */+ private fun trace(summary: String) {+ if (summary == lastTrace) return+ lastTrace = summary+ Log.status(TAG, summary) } + /** Store hits for this scan; beacons the stores do not know are left out of the solve. */+ private fun resolveFixes(wifiIds: List<BeaconId.Wifi>, cellIds: List<BeaconId.Cell>): List<BeaconFix> =+ offlineStore.resolveWifi(wifiIds).values + offlineStore.resolveCell(cellIds).values+ private fun DevicePosition.toLocation(): Location = Location(LocationManager.NETWORK_PROVIDER).apply { latitude = [email protected]@@ -123,6 +119,7 @@ class LocationReportingTask( } private companion object {+ const val TAG = "NetworkLocationFix" const val MIN_INTERVAL_MS = 1_000L /** Coordinates per fix in the interleaved native array (lat, lon, accuracy). */
networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.ktindex 35567ada6c..43889dad9c 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/OfflineBeaconStore.kt@@ -119,6 +119,12 @@ class OfflineBeaconStore(context: Context) { } } + /** Which stores are open, for the fix loop's status line. */+ fun describe(): String = synchronized(lock) {+ "stores[wifi=${if (wifiHandle != 0L) "open" else "closed"} " ++ "cell=${if (cellHandle != 0L) "open" else "closed"} native=${WpsStoreNative.available}]"+ }+ /** * Release both handles and their descriptors. Idempotent. Serialized with the resolvers so * it never frees a native reader that a concurrent lookup is still dereferencing.
networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.ktnew file mode 100644index 0000000000..175da72d1a--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt@@ -0,0 +1,175 @@+package com.vayunmathur.networklocation.ui++import android.location.Address+import android.location.Location+import android.location.LocationManager+import android.os.SystemClock+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.networklocation.platform.hasFineLocation+import com.vayunmathur.networklocation.platform.locationUpdates+import com.vayunmathur.networklocation.platform.reverseGeocode+import kotlinx.coroutines.delay+import java.util.Locale++/** Re-geocode only after the GPS fix has moved this far, not on every one-second fix. */+private const val REGEOCODE_DISTANCE_M = 25f+private const val NANOS_PER_SECOND = 1_000_000_000L+private const val TICK_MS = 1_000L++private sealed interface GeocodeState {+ data object WaitingForGps : GeocodeState+ data object Looking : GeocodeState+ data class Found(val address: Address, val from: Location) : GeocodeState+ data object NoMatch : GeocodeState+ data class Failed(val message: String) : GeocodeState+}++/**+ * Live check of both halves of the app: the GPS fix, this app's own network-location fix, and+ * the GPS fix run through the offline geocoder. GPS rather than the network fix is geocoded so+ * the geocoder is judged against a position that does not depend on the beacon stores.+ */+@Composable+fun LiveLocationSection(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ if (!hasFineLocation(context)) {+ Text(+ "Location permission is not granted, so live positions cannot be shown.",+ modifier = modifier,+ style = MaterialTheme.typography.bodyMedium,+ )+ return+ }++ val gpsFlow = remember { locationUpdates(context, LocationManager.GPS_PROVIDER) }+ val networkFlow = remember { locationUpdates(context, LocationManager.NETWORK_PROVIDER) }+ val gps by gpsFlow.collectAsState(initial = null)+ val network by networkFlow.collectAsState(initial = null)++ // Fix ages are shown live, so recompose once a second.+ var now by remember { mutableLongStateOf(SystemClock.elapsedRealtimeNanos()) }+ LaunchedEffect(Unit) {+ while (true) {+ delay(TICK_MS)+ now = SystemClock.elapsedRealtimeNanos()+ }+ }++ var anchor by remember { mutableStateOf<Location?>(null) }+ LaunchedEffect(gps) {+ val fix = gps ?: return@LaunchedEffect+ if (anchor?.let { it.distanceTo(fix) > REGEOCODE_DISTANCE_M } != false) anchor = fix+ }+ var geocode by remember { mutableStateOf<GeocodeState>(GeocodeState.WaitingForGps) }+ LaunchedEffect(anchor) {+ val fix = anchor ?: return@LaunchedEffect+ geocode = GeocodeState.Looking+ geocode = reverseGeocode(context, fix.latitude, fix.longitude).fold(+ onSuccess = { a -> a?.let { GeocodeState.Found(it, fix) } ?: GeocodeState.NoMatch },+ onFailure = { GeocodeState.Failed(it.message ?: it.javaClass.simpleName) },+ )+ }++ Column(modifier) {+ Text("Live check", style = MaterialTheme.typography.titleMedium)+ FixCard("GPS", gps, now, emptyText = "Waiting for a GPS fix… (go outside or near a window)")+ FixCard(+ "Network location (this app)",+ network,+ now,+ emptyText = "No network fix yet. Cell and Wi-Fi scans resolve against the offline stores.",+ comparedTo = gps,+ )+ GeocodeCard(geocode)+ }+}++@Composable+private fun FixCard(+ title: String,+ fix: Location?,+ now: Long,+ emptyText: String,+ comparedTo: Location? = null,+) {+ Card(Modifier.fillMaxWidth().padding(top = 12.dp)) {+ Column(Modifier.padding(16.dp)) {+ Text(title, style = MaterialTheme.typography.titleSmall)+ if (fix == null) {+ Text(emptyText, Modifier.padding(top = 4.dp), style = MaterialTheme.typography.bodyMedium)+ return@Column+ }+ Text(+ coords(fix.latitude, fix.longitude),+ Modifier.padding(top = 4.dp),+ style = MaterialTheme.typography.bodyLarge,+ )+ val details = buildList {+ if (fix.hasAccuracy()) add("±%.0f m".format(Locale.US, fix.accuracy))+ add("${(now - fix.elapsedRealtimeNanos).coerceAtLeast(0) / NANOS_PER_SECOND} s ago")+ comparedTo?.let { add("%.0f m from GPS".format(Locale.US, it.distanceTo(fix))) }+ }+ Text(details.joinToString(" · "), style = MaterialTheme.typography.bodySmall)+ }+ }+}++@Composable+private fun GeocodeCard(state: GeocodeState) {+ Card(Modifier.fillMaxWidth().padding(top = 12.dp)) {+ Column(Modifier.padding(16.dp)) {+ Text("Offline geocoder (GPS position)", style = MaterialTheme.typography.titleSmall)+ val body = Modifier.padding(top = 4.dp)+ when (state) {+ GeocodeState.WaitingForGps ->+ Text("Waiting for a GPS fix to look up.", body, style = MaterialTheme.typography.bodyMedium)+ GeocodeState.Looking -> Text(+ "Looking up… the first lookup after the service starts can take a while " ++ "while the database opens.",+ body,+ style = MaterialTheme.typography.bodyMedium,+ )+ GeocodeState.NoMatch ->+ Text("No nearby record in the database.", body, style = MaterialTheme.typography.bodyMedium)+ is GeocodeState.Failed ->+ Text("Lookup failed: ${state.message}", body, style = MaterialTheme.typography.bodyMedium)+ is GeocodeState.Found -> FoundAddress(state.address, state.from)+ }+ }+ }+}++@Composable+private fun FoundAddress(a: Address, from: Location) {+ Text(+ a.getAddressLine(0) ?: a.featureName ?: "(unnamed)",+ Modifier.padding(top = 4.dp),+ style = MaterialTheme.typography.bodyLarge,+ )+ val parts = listOfNotNull(a.thoroughfare, a.locality, a.adminArea, a.postalCode, a.countryCode)+ if (parts.isNotEmpty()) Text(parts.joinToString(", "), style = MaterialTheme.typography.bodyMedium)+ val match = FloatArray(1)+ Location.distanceBetween(from.latitude, from.longitude, a.latitude, a.longitude, match)+ Text(+ "Record at ${coords(a.latitude, a.longitude)} · %.0f m from the GPS fix".format(Locale.US, match[0]),+ style = MaterialTheme.typography.bodySmall,+ )+}++private fun coords(lat: Double, lon: Double) = "%.6f, %.6f".format(Locale.US, lat, lon)
networklocation/src/main/java/com/vayunmathur/networklocation/ui/SetupScreen.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/ui/SetupScreen.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/SetupScreen.ktnew file mode 100644index 0000000000..806ddd08e2--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/SetupScreen.kt@@ -0,0 +1,41 @@+package com.vayunmathur.networklocation.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.networklocation.OfflineDatabaseSection++/** First-run screen: what the app does, and the offline-database download it cannot work without. */+@Composable+fun SetupScreen(onReady: () -> Unit) {+ AppScaffold(title = "Network Location", scrollBehavior = appBarScrollBehavior()) { padding ->+ // Letterboxed on expanded windows so the status text keeps a readable measure.+ DesktopMaxWidthContainer(Modifier.padding(padding)) {+ Column(+ Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(24.dp)+ ) {+ Text(+ "Provides the system network-location provider and an on-device, offline " ++ "geocoder. Both resolve entirely on device from the downloaded databases " ++ "below — nothing is sent to a positioning service. Always on — there is no " ++ "disable switch.",+ style = MaterialTheme.typography.bodyMedium,+ )+ OfflineDatabaseSection(Modifier.padding(top = 24.dp), onReady = onReady)+ }+ }+ }+}
networklocation/src/main/java/com/vayunmathur/networklocation/ui/StatusScreen.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/ui/StatusScreen.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/StatusScreen.ktnew file mode 100644index 0000000000..72086b4062--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/StatusScreen.kt@@ -0,0 +1,32 @@+package com.vayunmathur.networklocation.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.networklocation.OfflineDatabaseSection++/** Home once the databases are installed: the live GPS / network-location / geocoder check. */+@Composable+fun StatusScreen() {+ AppScaffold(title = "Network Location", scrollBehavior = appBarScrollBehavior()) { padding ->+ DesktopMaxWidthContainer(Modifier.padding(padding)) {+ Column(+ Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(24.dp)+ ) {+ LiveLocationSection()+ OfflineDatabaseSection(Modifier.padding(top = 24.dp))+ }+ }+ }+}
networklocation/src/main/rust/src/geocoder.rs
diff --git a/networklocation/src/main/rust/src/geocoder.rs b/networklocation/src/main/rust/src/geocoder.rsindex 417328a4f0..988d01f07b 100644--- a/networklocation/src/main/rust/src/geocoder.rs+++ b/networklocation/src/main/rust/src/geocoder.rs@@ -1,22 +1,30 @@-//! Offline reverse/forward geocoding over the packed `geocoder-v3.geodb`, exposed via JNI.+//! Offline reverse/forward geocoding over the packed `geocoder.db`, exposed via JNI. //! //! The on-disk format is produced by `scripts/networklocation/geodb_build`: grid-primary record //! order for cheap reverse lookup, dictionary-indexed fields, delta+zigzag+varint columns in //! per-4096-record Zstandard blocks, plus two sorted indexes for structured and by-name lookup. //! All ints/longs are big-endian. //!-//! Columns are read block-by-block straight from the file (positional `pread`, no copy), 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.+//! ## Memory //!-//! ## v3+//! The whole file is memory-mapped and nothing is decoded at open. Columns and dictionaries are+//! both stored as small independent zstd blocks, each with a one-block cache here, so a lookup+//! decompresses a few kilobytes and the process holds only mapped file pages, which the kernel+//! can reclaim at will. v4 inflated every dictionary on open: about 2 GB of heap for the planet,+//! and over a minute before the first answer. Runtime is decompress-only, so we use the+//! pure-Rust `ruzstd` decoder — no NDK C toolchain needed. //!-//! v2 held **only** postal addresses, at e6 coordinates. v3 also carries named streets, points-//! of interest and populated places, each tagged with a `kind`, and stores coordinates at e7 —-//! the precision OSM itself uses, so nothing is thrown away in the conversion.+//! ## v5+//!+//! v2 held **only** postal addresses, at e6 coordinates. v3 added named streets, points of+//! interest and populated places, each tagged with a `kind`. v4 cut that down for size: e5+//! coordinates, a forward index of records with a street only, and one name-index entry per+//! street name per grid cell. v5 keeps v4's content and lays it out to be read from a mapping:+//! blocked dictionaries behind an uncompressed first-string table, and column directories that+//! store end offsets. //! //! JNI result layout: each result is 10 consecutive strings-//! `[lat, lon, name, house, street, city, state, country, postcode, kind]`, lat/lon to 7dp.+//! `[lat, lon, name, house, street, city, state, country, postcode, kind]`, lat/lon to 5dp. //! `reverse` returns one result or null; `forward` and `searchName` return 10*k strings. use std::cmp::Ordering;@@ -28,25 +36,29 @@ use std::io::{Cursor, Read}; use std::os::unix::io::FromRawFd; use std::sync::Mutex; -use jni::objects::{JByteArray, JClass, JObjectArray, JString};+use jni::objects::{JClass, JObjectArray, JString}; use jni::sys::{jdouble, jint, jlong, jobjectArray};-use jni::{Env, EnvUnowned, jni_str};+use jni::{Env, EnvUnowned};++use crate::mmap::Map; const MAGIC: u32 = 0x4D41_4745;-const VERSION: u32 = 3;+const VERSION: u32 = 5; const BLOCK: i32 = 4096; -// Grid geometry, in e7 units. A cell is 0.05 degrees, about 5.5 km of latitude.-const CELL_E7: i64 = 500_000;-const COLS: i64 = 3_600_000_000 / CELL_E7; // 7200-const MIN_LAT_E7: i32 = -900_000_000;-const MIN_LON_E7: i32 = -1_800_000_000;+// Grid geometry, in e5 units. A cell is 0.05 degrees, about 5.5 km of latitude.+const CELL: i64 = 5_000;+const COLS: i64 = 36_000_000 / CELL; // 7200+const MIN_LAT: i32 = -9_000_000;+const MIN_LON: i32 = -18_000_000; /// How far the reverse search will expand before giving up, in cells. const MAX_RADIUS: i64 = 32; const DICTS: usize = 7; const COLUMNS: usize = 10;+/// Sections after the header: dictionaries, columns, grid, fwd, nm_name, nm_rec.+const SECTIONS: usize = DICTS + COLUMNS + 4; const C_LAT: usize = 0; const C_LON: usize = 1;@@ -59,6 +71,9 @@ const C_COUNTRY: usize = 7; const C_POSTCODE: usize = 8; const C_KIND: usize = 9; +/// Which columns are delta-encoded against the previous value in their block.+const DELTA: [bool; COLUMNS] = [true, true, false, false, false, false, false, false, false, false];+ /// Dictionary slot backing column `c`. Columns 0 and 1 are coordinates and column 9 is a small /// integer, so only 2..=8 are dictionary-indexed. const fn dict_of(col: usize) -> usize {@@ -68,183 +83,273 @@ const fn dict_of(col: usize) -> usize { /// Strings per result in the JNI array. const FIELDS: usize = 10; -// --------------------------------------------------------------------------- byte source-/// Positional reader over a region of a file (the APK asset), starting at `base`.-struct Src {- file: File,- base: u64,-}-impl Src {- /// Positional read that never moves the file cursor, so shared readers stay- /// thread-safe. `pread` on unix/Android, `seek_read` (same semantics) on- /// Windows hosts, a `try_clone` + seek fallback anywhere else. Only the host- /// `cargo check` smoke test exercises the non-unix paths.- fn read(&self, pos: u64, len: usize) -> Option<Vec<u8>> {- let mut b = vec![0u8; len];- #[cfg(unix)]- {- use std::os::unix::fs::FileExt;- self.file.read_exact_at(&mut b, self.base + pos).ok()?;- }- #[cfg(windows)]- {- use std::os::windows::fs::FileExt;- self.file.seek_read(&mut b, self.base + pos).ok()?;- }- #[cfg(not(any(unix, windows)))]- {- use std::io::{Read, Seek, SeekFrom};- let mut f = self.file.try_clone().ok()?;- f.seek(SeekFrom::Start(self.base + pos)).ok()?;- f.read_exact(&mut b).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)- }-}+/// Grid entries are `[i64 cell, u32 start]`, uncompressed.+const GRID_ENTRY: usize = 12; -fn be32(b: &[u8]) -> u32 {- ((b[0] as u32) << 24) | ((b[1] as u32) << 16) | ((b[2] as u32) << 8) | (b[3] as u32)+// --------------------------------------------------------------------------- byte helpers+fn be32(d: &[u8], p: usize) -> Option<u32> {+ Some(u32::from_be_bytes(d.get(p..p + 4)?.try_into().ok()?)) }-fn be64(b: &[u8]) -> i64 {- let mut v: i64 = 0;- for i in 0..8 {- v = (v << 8) | (b[i] as i64);- }- v+fn be64(d: &[u8], p: usize) -> Option<i64> {+ Some(i64::from_be_bytes(d.get(p..p + 8)?.try_into().ok()?)) } fn unzigzag(v: u32) -> i32 { ((v >> 1) as i32) ^ -((v & 1) as i32) }-fn read_varint(a: &[u8], p: &mut usize) -> u32 {+fn read_varint(a: &[u8], p: &mut usize) -> Option<u32> { let mut v: u32 = 0; let mut shift = 0; loop {- let b = a[*p];+ let b = *a.get(*p)?; *p += 1; v |= ((b & 0x7F) as u32) << shift; if b & 0x80 == 0 {- break;+ return Some(v); } shift += 7; }- v }-fn zstd_decompress(comp: &[u8], raw_len: usize) -> Option<Vec<u8>> {+fn zstd_decompress(comp: &[u8], size_hint: usize) -> Option<Vec<u8>> { let mut dec = ruzstd::decoding::StreamingDecoder::new(Cursor::new(comp)).ok()?;- let mut out = Vec::with_capacity(raw_len);+ let mut out = Vec::with_capacity(size_hint); 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 searchable dictionaries-/// (street/city/state/country) are sorted that way, so the binary search must match. The+/// (name/street/city/state/country) are sorted that way, so the binary search must match. The /// house/postcode dictionaries are frequency-ordered and only ever indexed for display. 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`).+/// One column. The directory is read from the mapping on demand; only the most recently+/// decoded block is held. struct Column { n: i32,+ blocks: usize, delta: bool,- comp_lens: Vec<i32>,- raw_lens: Vec<i32>,- block_off: Vec<u64>,+ /// `[u32 raw_len, u32 end]` per block.+ dir: usize,+ /// Start of the compressed blocks.+ data: usize, 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;+ fn new(d: &[u8], body: usize, delta: bool) -> Option<Column> {+ let n = be32(d, body)? as i32;+ let blocks = be32(d, body + 4)? as usize;+ let dir = body + 8;+ let data = dir.checked_add(blocks.checked_mul(8)?)?;+ if data > d.len() || (n > 0 && blocks < (n as usize).div_ceil(BLOCK as usize)) {+ return None; }- Some(Column { n, delta, comp_lens, raw_lens, block_off, cached_block: -1, cached: Vec::new() })+ Some(Column { n, blocks, delta, dir, data, cached_block: -1, cached: Vec::new() }) }- fn ensure(&mut self, src: &Src, block: i32) -> bool {++ fn ensure(&mut self, d: &[u8], 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;+ let b = block as usize;+ if b >= self.blocks {+ return false;+ }+ let decoded = (|| {+ let raw_len = be32(d, self.dir + b * 8)? as usize;+ let end = be32(d, self.dir + b * 8 + 4)? as usize;+ let start = if b == 0 { 0 } else { be32(d, self.dir + (b - 1) * 8 + 4)? as usize };+ let raw = zstd_decompress(d.get(self.data + start..self.data + end)?, raw_len)?;+ let count = std::cmp::min(BLOCK, self.n - block * BLOCK) as usize;+ let mut vals = Vec::with_capacity(count);+ let (mut rp, mut prev) = (0usize, 0i32);+ for _ in 0..count {+ let dv = unzigzag(read_varint(&raw, &mut rp)?);+ let actual = if self.delta { prev.wrapping_add(dv) } else { dv };+ vals.push(actual);+ prev = actual;+ }+ Some(vals)+ })();+ match decoded {+ Some(vals) => {+ self.cached = vals;+ self.cached_block = block;+ true+ }+ None => false, }- self.cached = vals;- self.cached_block = block;- true }- fn get(&mut self, src: &Src, i: i32) -> i32 {++ fn get(&mut self, d: &[u8], i: i32) -> i32 {+ if i < 0 || i >= self.n {+ return 0;+ } let block = i / BLOCK;- if !self.ensure(src, block) {+ if !self.ensure(d, 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;+// --------------------------------------------------------------------------- dictionary reader+/// One blocked dictionary (`codec::encode_dict` in the builder). Searches binary-search the+/// uncompressed first-string table in the mapping, then decode one block; only that block is+/// held.+struct Dict {+ count: usize,+ per: usize,+ blocks: usize,+ first_dir: usize,+ firsts: usize,+ block_dir: usize,+ data: usize,+ cached_block: usize,+ raw: Vec<u8>,+ /// `(start, len)` of each string of the cached block within `raw`.+ spans: Vec<(u32, u32)>,+}+impl Dict {+ fn new(d: &[u8], body: usize, end: usize) -> Option<Dict> {+ let count = be32(d, body)? as usize;+ let per = be32(d, body + 4)? as usize;+ let blocks = be32(d, body + 8)? as usize;+ if per == 0 || blocks != count.div_ceil(per) {+ return None;+ }+ let first_dir = body + 12;+ let firsts = first_dir.checked_add(blocks.checked_mul(4)?)?;+ let firsts_len = if blocks == 0 { 0 } else { be32(d, firsts - 4)? as usize };+ let block_dir = firsts.checked_add(firsts_len)?;+ let data = block_dir.checked_add(blocks.checked_mul(4)?)?;+ let data_len = if blocks == 0 { 0 } else { be32(d, data - 4)? as usize };+ if data.checked_add(data_len)? > end {+ return None;+ }+ Some(Dict {+ count,+ per,+ blocks,+ first_dir,+ firsts,+ block_dir,+ data,+ cached_block: usize::MAX,+ raw: Vec::new(),+ spans: Vec::new(),+ })+ }++ /// First string of block `b`, straight from the mapping.+ fn first<'a>(&self, d: &'a [u8], b: usize) -> &'a str {+ let range = (|| {+ let start = if b == 0 { 0 } else { be32(d, self.first_dir + (b - 1) * 4)? as usize };+ let end = be32(d, self.first_dir + b * 4)? as usize;+ std::str::from_utf8(d.get(self.firsts + start..self.firsts + end)?).ok()+ })();+ range.unwrap_or("")+ }++ fn ensure(&mut self, d: &[u8], b: usize) -> bool {+ if b == self.cached_block {+ return true;+ }+ if b >= self.blocks {+ return false;+ }+ let decoded = (|| {+ let start = if b == 0 { 0 } else { be32(d, self.block_dir + (b - 1) * 4)? as usize };+ let end = be32(d, self.block_dir + b * 4)? as usize;+ let raw = zstd_decompress(d.get(self.data + start..self.data + end)?, 0)?;+ let want = self.per.min(self.count - b * self.per);+ let mut spans = Vec::with_capacity(want);+ let mut p = 0usize;+ for _ in 0..want {+ let len = be32(&raw, p)? as usize;+ p += 4;+ raw.get(p..p + len)?;+ spans.push((p as u32, len as u32));+ p += len;+ }+ Some((raw, spans))+ })();+ match decoded {+ Some((raw, spans)) => {+ self.raw = raw;+ self.spans = spans;+ self.cached_block = b;+ true+ }+ None => false,+ }+ }++ /// String `k` of the cached block.+ fn cached_str(&self, k: usize) -> &str {+ let (s, l) = self.spans[k];+ std::str::from_utf8(&self.raw[s as usize..(s + l) as usize]).unwrap_or("")+ }++ /// String `i`, or empty if out of range or unreadable.+ fn get(&mut self, d: &[u8], i: usize) -> String {+ if i >= self.count || !self.ensure(d, i / self.per) {+ return String::new();+ }+ self.cached_str(i % self.per).to_owned()+ }++ /// Number of leading strings for which `pred` holds, given that it holds for a prefix of+ /// the (sorted) dictionary and then never again. One binary search over the first-string+ /// table picks the only block the boundary can be in; one more inside that block finds it.+ fn partition_point(&mut self, d: &[u8], pred: impl Fn(&str) -> bool) -> usize {+ let (mut lo, mut hi) = (0usize, self.blocks);+ while lo < hi {+ let mid = (lo + hi) / 2;+ if pred(self.first(d, mid)) {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ if lo == 0 {+ return 0;+ }+ let b = lo - 1;+ if !self.ensure(d, b) {+ return b * self.per;+ }+ let (mut l, mut h) = (0usize, self.spans.len());+ while l < h {+ let m = (l + h) / 2;+ if pred(self.cached_str(m)) {+ l = m + 1;+ } else {+ h = m;+ }+ }+ b * self.per + l+ }++ /// Id of exactly `key` in a UTF-16-sorted dictionary.+ fn index_of(&mut self, d: &[u8], key: &str) -> Option<usize> {+ let i = self.partition_point(d, |s| cmp_utf16(s, key) == Ordering::Less);+ (i < self.count && self.get(d, i) == key).then_some(i) }- Some(out) } // --------------------------------------------------------------------------- reader pub struct Reader {- src: Src,+ map: Map, n: i32, /// name, house, street, city, state, country, postcode.- dicts: Vec<Vec<String>>,- cell_ids: Vec<i64>,- cell_starts: Vec<i32>,+ dicts: Vec<Dict>,+ /// Start of the grid's `[i64 cell, u32 start]` entries.+ grid: usize,+ grid_count: usize, cols: Vec<Column>,+ /// Records that carry a street, by structured address. fwd: Column, /// Name ids, ascending; parallel to [`Reader::nm_rec`]. nm_name: Column,@@ -252,20 +357,5 @@ pub struct Reader { nm_rec: 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)-}- include!("geocoder_part1.rs");-include!("geocoder_part2.rs");\ No newline at end of file+include!("geocoder_part2.rs");
networklocation/src/main/rust/src/geocoder_part1.rs
diff --git a/networklocation/src/main/rust/src/geocoder_part1.rs b/networklocation/src/main/rust/src/geocoder_part1.rsindex 80cf2be3fa..a467e07468 100644--- a/networklocation/src/main/rust/src/geocoder_part1.rs+++ b/networklocation/src/main/rust/src/geocoder_part1.rs@@ -5,95 +5,97 @@ impl Reader { if dupfd < 0 { return None; }+ // The mapping outlives the descriptor, so the dup'd fd is closed as soon as it is made. let file = unsafe { File::from_raw_fd(dupfd) };- Reader::from_src(Src { file, base: offset as u64 })+ Reader::map_file(&file, offset.max(0) as u64) } - /// Host fallback: `fd` is an APK asset descriptor, meaningless off-device.+ /// Host fallback: `fd` is an Android descriptor, meaningless off-device. #[cfg(not(unix))] fn open(_fd: i32, _offset: i64) -> Option<Reader> { None } - /// Open a `.geodb` straight from a filesystem path (base offset 0). Test-only: the- /// production path receives an APK asset fd + offset via `open`.+ /// Open a database straight from a filesystem path. Test-only: the production path+ /// receives a descriptor via `open`. #[cfg(test)] fn open_path<P: AsRef<std::path::Path>>(path: P) -> Option<Reader> {- let file = File::open(path).ok()?;- Reader::from_src(Src { file, base: 0 })+ Reader::map_file(&File::open(path).ok()?, 0) } - fn from_src(src: Src) -> Option<Reader> {- if src.rd_u32(0)? != MAGIC || src.rd_u32(4)? != VERSION {+ fn map_file(file: &File, offset: u64) -> Option<Reader> {+ let len = file.metadata().ok()?.len().checked_sub(offset)?;+ let map = Map::new(file, offset, usize::try_from(len).ok()?)?;+ Reader::from_map(map)+ }++ /// Walk the section headers and remember where each section starts. Nothing is decoded and+ /// nothing proportional to the database is allocated.+ fn from_map(map: Map) -> Option<Reader> {+ let d = map.as_slice();+ if be32(d, 0)? != MAGIC || be32(d, 4)? != VERSION { return None; }- let n = src.rd_i32(8)?;- let mut cursor: u64 = 12;+ let n = be32(d, 8)? as i32; - let mut dicts = Vec::with_capacity(DICTS);- for _ in 0..DICTS {- dicts.push(decode_dict(§_bytes(&src, &mut cursor)?)?);+ // (body offset, body end) of every section.+ let mut bodies = Vec::with_capacity(SECTIONS);+ let mut cursor = 12usize;+ for _ in 0..SECTIONS {+ let size = be32(d, cursor)? as usize;+ let body = cursor + 4;+ let end = body.checked_add(size)?;+ if end > d.len() {+ return None;+ }+ bodies.push((body, end));+ cursor = end; } - let delta = [true, true, false, false, false, false, false, false, false, false];+ let mut dicts = Vec::with_capacity(DICTS);+ for &(body, end) in &bodies[..DICTS] {+ dicts.push(Dict::new(d, body, end)?);+ } let mut cols = Vec::with_capacity(COLUMNS);- for i in 0..COLUMNS {- let off = sect_body(&src, &mut cursor)?;- cols.push(Column::new(&src, off, delta[i])?);+ for (c, &(body, _)) in bodies[DICTS..DICTS + COLUMNS].iter().enumerate() {+ cols.push(Column::new(d, body, DELTA[c])?); }-- 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 (grid_body, grid_end) = bodies[DICTS + COLUMNS];+ let grid_count = be32(d, grid_body)? as usize;+ let grid = grid_body + 4;+ if grid.checked_add(grid_count.checked_mul(GRID_ENTRY)?)? > grid_end {+ return None; }+ let fwd = Column::new(d, bodies[DICTS + COLUMNS + 1].0, true)?;+ let nm_name = Column::new(d, bodies[DICTS + COLUMNS + 2].0, true)?;+ let nm_rec = Column::new(d, bodies[DICTS + COLUMNS + 3].0, false)?; - let fwd_off = sect_body(&src, &mut cursor)?;- let fwd = Column::new(&src, fwd_off, true)?;-- let nm_name_off = sect_body(&src, &mut cursor)?;- let nm_name = Column::new(&src, nm_name_off, true)?;- let nm_rec_off = sect_body(&src, &mut cursor)?;- let nm_rec = Column::new(&src, nm_rec_off, false)?;+ Some(Reader { map, n, dicts, grid, grid_count, cols, fwd, nm_name, nm_rec })+ } - Some(Reader { src, n, dicts, cell_ids, cell_starts, cols, fwd, nm_name, nm_rec })+ fn grid_cell(&self, gi: usize) -> i64 {+ be64(self.map.as_slice(), self.grid + gi * GRID_ENTRY).unwrap_or(i64::MAX) } - 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 grid_start(&self, gi: usize) -> i32 {+ be32(self.map.as_slice(), self.grid + gi * GRID_ENTRY + 8).map_or(self.n, |v| v as i32) } - 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) {+ fn grid_index(&self, cell: i64) -> Option<usize> {+ let (mut lo, mut hi) = (0usize, self.grid_count);+ while lo < hi {+ let mid = (lo + hi) / 2;+ match self.grid_cell(mid).cmp(&cell) { Ordering::Less => lo = mid + 1,- Ordering::Greater => hi = mid - 1,- Ordering::Equal => return mid,+ Ordering::Greater => hi = mid,+ Ordering::Equal => return Some(mid), } }- -1+ None+ }++ fn col(&mut self, c: usize, i: i32) -> i32 {+ self.cols[c].get(self.map.as_slice(), i) } /// Nearest record to `(lat, lon)`, or `None` if nothing is within [`MAX_RADIUS`] cells.@@ -106,102 +108,88 @@ impl Reader { if self.n == 0 { return None; }- let q_lat = to_e7(lat);- let q_lon = to_e7(lon);- let row = (q_lat as i64 - MIN_LAT_E7 as i64) / CELL_E7;- let col = (q_lon as i64 - MIN_LON_E7 as i64) / CELL_E7;+ let q_lat = to_e5(lat);+ let q_lon = to_e5(lon);+ let row = (q_lat as i64 - MIN_LAT as i64) / CELL;+ let col = (q_lon as i64 - MIN_LON as i64) / CELL; let lon_scale = lat.to_radians().cos(); let mut best_rec = -1i32; let mut best_dist = f64::MAX; let mut radius = 1i64; while radius <= MAX_RADIUS {- 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;- }- }- }+ for r in (row - radius)..=(row + radius) {+ if r < 0 {+ continue;+ }+ for c in (col - radius)..=(col + radius) {+ let on_edge = !(radius > 1+ && r > row - radius+ && r < row + radius+ && c > col - radius+ && c < col + radius);+ if !on_edge {+ continue;+ }+ let cc = ((c % COLS) + COLS) % COLS;+ let Some(gi) = self.grid_index(r * COLS + cc) else { continue };+ let start = self.grid_start(gi);+ let end = if gi + 1 < self.grid_count { self.grid_start(gi + 1) } else { self.n };+ for i in start..end {+ let d_lat = (self.col(C_LAT, i) - q_lat) as f64;+ let d_lon = (self.col(C_LON, 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; } // Anything on the next ring is at least `radius` whole cells away along one axis, // because the query sits somewhere inside ring 0's cell. Once that floor exceeds // the best distance found, no further ring can improve on it. if best_rec >= 0 {- let floor = radius as f64 * CELL_E7 as f64 * lon_scale.abs().min(1.0);+ let floor = radius as f64 * CELL as f64 * lon_scale.abs().min(1.0); if floor * floor > best_dist { break; } } radius += 1; }- if best_rec < 0 {- None- } else {- Some(best_rec)- }+ (best_rec >= 0).then_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;+ for (c, t) in [(C_COUNTRY, target[0]), (C_STATE, target[1]), (C_CITY, target[2])] {+ let v = self.col(c, rec) - t;+ if v != 0 {+ return v;+ } }- self.cols[C_STREET].get(&self.src, rec) - target[3]+ self.col(C_STREET, rec) - target[3]+ }++ fn dict_index(&mut self, field: usize, key: &str) -> Option<i32> {+ self.dicts[field].index_of(self.map.as_slice(), key).map(|i| i as i32) } fn forward(&mut self, country: &str, state: &str, city: &str, street: &str, limit: i32) -> Vec<i32> {- let k_country = self.dict_index(dict_of(C_COUNTRY), country);- let k_state = self.dict_index(dict_of(C_STATE), state);- let k_city = self.dict_index(dict_of(C_CITY), city);- let k_street = self.dict_index(dict_of(C_STREET), street);- if k_country < 0 || k_state < 0 || k_city < 0 || k_street < 0 {+ let keys = (+ self.dict_index(dict_of(C_COUNTRY), country),+ self.dict_index(dict_of(C_STATE), state),+ self.dict_index(dict_of(C_CITY), city),+ self.dict_index(dict_of(C_STREET), street),+ );+ let (Some(k_country), Some(k_state), Some(k_city), Some(k_street)) = keys else { return Vec::new();- }+ }; let target = [k_country, k_state, k_city, k_street];- let mut lo = 0i32;- let mut hi = self.n;+ let total = self.fwd.n;+ let (mut lo, mut hi) = (0i32, total); while lo < hi { let mid = (lo + hi) >> 1;- let rec = self.fwd.get(&self.src, mid);+ let rec = self.fwd.get(self.map.as_slice(), mid); if self.compare_key(rec, target) < 0 { lo = mid + 1; } else {@@ -210,8 +198,8 @@ impl Reader { } 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);+ while k < total && (out.len() as i32) < limit {+ let rec = self.fwd.get(self.map.as_slice(), k); if self.compare_key(rec, target) != 0 { break; }@@ -227,31 +215,14 @@ impl Reader { /// contiguous run and both ends are a binary search. Matching is case-sensitive: the /// dictionary is ordered by the names as they appear in OpenStreetMap, and a case-folded /// run would not be contiguous in that ordering.- fn name_prefix_range(&self, prefix: &str) -> (i32, i32) {- let dict = &self.dicts[dict_of(C_NAME)];- let len = dict.len() as i32;- let mut lo = 0i32;- let mut hi = len;- while lo < hi {- let mid = (lo + hi) >> 1;- if cmp_utf16(&dict[mid as usize], prefix) == Ordering::Less {- lo = mid + 1;- } else {- hi = mid;- }- }- let start = lo;- let mut lo2 = start;- let mut hi2 = len;- while lo2 < hi2 {- let mid = (lo2 + hi2) >> 1;- if dict[mid as usize].starts_with(prefix) {- lo2 = mid + 1;- } else {- hi2 = mid;- }- }- (start, lo2)+ fn name_prefix_range(&mut self, prefix: &str) -> (i32, i32) {+ let d = self.map.as_slice();+ let dict = &mut self.dicts[dict_of(C_NAME)];+ let start = dict.partition_point(d, |s| cmp_utf16(s, prefix) == Ordering::Less);+ let end = dict.partition_point(d, |s| {+ cmp_utf16(s, prefix) == Ordering::Less || s.starts_with(prefix)+ });+ (start as i32, end as i32) } /// Records whose name begins with `prefix`, up to `limit`.@@ -263,12 +234,12 @@ impl Reader { if id_lo >= id_hi { return Vec::new(); }+ let d = self.map.as_slice(); let total = self.nm_name.n;- let mut lo = 0i32;- let mut hi = total;+ let (mut lo, mut hi) = (0i32, total); while lo < hi { let mid = (lo + hi) >> 1;- if self.nm_name.get(&self.src, mid) < id_lo {+ if self.nm_name.get(d, mid) < id_lo { lo = mid + 1; } else { hi = mid;@@ -277,10 +248,10 @@ impl Reader { let mut out = Vec::new(); let mut k = lo; while k < total && (out.len() as i32) < limit {- if self.nm_name.get(&self.src, k) >= id_hi {+ if self.nm_name.get(d, k) >= id_hi { break; }- out.push(self.nm_rec.get(&self.src, k));+ out.push(self.nm_rec.get(d, k)); k += 1; } out@@ -289,16 +260,19 @@ impl Reader { /// `[lat, lon, name, house, street, city, state, country, postcode, kind]` for a /// grid-ordered record. fn resolve(&mut self, rec: i32) -> [String; FIELDS] {- let lat = self.cols[C_LAT].get(&self.src, rec) as f64 / 1e7;- let lon = self.cols[C_LON].get(&self.src, rec) as f64 / 1e7;- let kind = self.cols[C_KIND].get(&self.src, rec);- let mut text = |col: usize| -> String {- let id = self.cols[col].get(&self.src, rec);- self.dicts[dict_of(col)].get(id as usize).cloned().unwrap_or_default()+ let lat = self.col(C_LAT, rec) as f64 / 1e5;+ let lon = self.col(C_LON, rec) as f64 / 1e5;+ let kind = self.col(C_KIND, rec);+ let mut text = |c: usize| -> String {+ let id = self.cols[c].get(self.map.as_slice(), rec);+ if id < 0 {+ return String::new();+ }+ self.dicts[dict_of(c)].get(self.map.as_slice(), id as usize) }; [- format!("{lat:.7}"),- format!("{lon:.7}"),+ format!("{lat:.5}"),+ format!("{lon:.5}"), text(C_NAME), text(C_HOUSE), text(C_STREET),@@ -311,9 +285,9 @@ impl Reader { } } -/// Degrees to e7, the precision OSM itself stores and this database keeps.-fn to_e7(deg: f64) -> i32 {- (deg * 10_000_000.0 + 0.5).floor() as i32+/// Degrees to e5 (about 1.1 m), the precision this database stores.+fn to_e5(deg: f64) -> i32 {+ (deg * 100_000.0 + 0.5).floor() as i32 } // --------------------------------------------------------------------------- JNI@@ -340,8 +314,8 @@ fn build_string_array(env: &mut Env, reader: &mut Reader, recs: &[i32]) -> jobje 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.+/// `open(fd, offset, length) -> handle` (0 on failure). `length` is unused: the reader maps+/// the file from `offset` to its end and the section framing bounds every read. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_networklocation_GeocoderNative_open<'l>( _env: EnvUnowned<'l>,
networklocation/src/main/rust/src/geocoder_part2.rs
diff --git a/networklocation/src/main/rust/src/geocoder_part2.rs b/networklocation/src/main/rust/src/geocoder_part2.rsindex 383ac2efd4..1817db078a 100644--- a/networklocation/src/main/rust/src/geocoder_part2.rs+++ b/networklocation/src/main/rust/src/geocoder_part2.rs@@ -32,7 +32,7 @@ mod tests { if let Ok(p) = std::env::var("GEOCODER_DB") { return Some(p); }- let bundled = concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/geocoder-v3.geodb");+ let bundled = concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/geocoder.db"); if std::path::Path::new(bundled).exists() { Some(bundled.to_string()) } else {@@ -64,25 +64,62 @@ mod tests { assert_eq!(r.cols.len(), COLUMNS, "wrong column count"); assert_eq!(r.nm_name.n, r.nm_rec.n, "name index halves must match in length"); assert!(r.nm_name.n <= r.n, "name index cannot exceed the record count");- assert_eq!(r.fwd.n, r.n, "forward index must cover every record");- assert_eq!(- r.cell_ids.len(),- r.cell_starts.len(),- "grid cell_ids/cell_starts length mismatch"- );+ assert!(r.fwd.n > 0 && r.fwd.n <= r.n, "forward index holds addresses, so 0 < fwd <= n"); for (i, d) in r.dicts.iter().enumerate() {- assert!(!d.is_empty(), "dictionary {i} is empty");+ assert!(d.count > 0, "dictionary {i} is empty");+ }+ // grid_index() binary-searches the grid's cell ids, so they must be strictly ascending,+ // and the record starts must be non-decreasing and within [0, n].+ let mut prev_cell = i64::MIN;+ let mut prev_start = 0i32;+ for gi in 0..r.grid_count {+ let (cell, s) = (r.grid_cell(gi), r.grid_start(gi));+ assert!(cell > prev_cell, "grid cells not strictly ascending at {gi}");+ assert!(s >= prev_start && s <= r.n, "grid start {s} out of range (prev {prev_start}, n {})", r.n);+ prev_cell = cell;+ prev_start = s; }- // grid_index() binary-searches cell_ids, so they must be strictly ascending.- for w in r.cell_ids.windows(2) {- assert!(w[0] < w[1], "cell_ids not strictly ascending");+ }++ /// Every dictionary's first-string table must agree with its blocks, or a binary search+ /// lands in the wrong block and silently misses. Checked for every block of every+ /// searchable dictionary.+ #[test]+ fn first_string_tables_match_their_blocks() {+ let mut r = match open_db() {+ Some(r) => r,+ None => return,+ };+ for field in [dict_of(C_NAME), dict_of(C_STREET), dict_of(C_CITY), dict_of(C_STATE), dict_of(C_COUNTRY)] {+ let d = r.map.as_slice();+ let dict = &mut r.dicts[field];+ for b in 0..dict.blocks {+ let first = dict.first(d, b).to_owned();+ assert_eq!(dict.get(d, b * dict.per), first, "dictionary {field} block {b}");+ if b > 0 {+ assert_eq!(cmp_utf16(dict.first(d, b - 1), &first), Ordering::Less);+ }+ } }- // cell_starts index into records: non-decreasing and within [0, n].- let mut prev = 0i32;- for &s in &r.cell_starts {- assert!(s >= prev && s <= r.n, "cell_start {s} out of range (prev {prev}, n {})", r.n);- prev = s;+ }++ /// `index_of` must find every string at its own id, across block boundaries.+ #[test]+ fn dictionary_lookup_finds_strings_at_their_own_ids() {+ let mut r = match open_db() {+ Some(r) => r,+ None => return,+ };+ let d = r.map.as_slice();+ let dict = &mut r.dicts[dict_of(C_STREET)];+ let step = (dict.count / 500).max(1);+ let mut i = 0;+ while i < dict.count {+ let s = dict.get(d, i);+ assert_eq!(dict.index_of(d, &s), Some(i), "street {s:?}");+ i += step; }+ assert_eq!(dict.index_of(d, "\u{10FFFF} no such street"), None); } /// Reverse geocoding a coordinate that is definitely inside the database's coverage@@ -199,7 +236,7 @@ mod tests { } i += step; }- assert!(kinds.len() > 1, "a v3 database should hold more than addresses: {kinds:?}");+ assert!(kinds.len() > 1, "the database should hold more than addresses: {kinds:?}"); } /// A name taken from the database is findable by its own prefix, and the result really@@ -215,7 +252,7 @@ mod tests { return; } // Pick a name that actually exists, from the middle of the name index.- let seed = r.nm_rec.get(&r.src, r.nm_name.n / 2);+ let seed = r.nm_rec.get(r.map.as_slice(), r.nm_name.n / 2); let name = r.resolve(seed)[F_NAME].clone(); assert!(!name.is_empty(), "the name index must point at a named record"); @@ -285,7 +322,7 @@ mod tests { } /// Micro-benchmark (opt-in). Run with:- /// GEOCODER_DB=/path/geocoder.geodb cargo test -p network_location_position_estimation_rust \+ /// GEOCODER_DB=/path/geocoder.db cargo test -p network_location_position_estimation_rust \ /// geocoder::tests::bench_ops -- --ignored --nocapture #[test] #[ignore]
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 e1f3bbfb7f..744851ae82 100644--- a/networklocation/src/main/rust/src/lib.rs+++ b/networklocation/src/main/rust/src/lib.rs@@ -19,6 +19,7 @@ pub mod coordinate; pub mod geocoder; mod jni; pub mod measurement;+mod mmap; pub mod multilateration; pub mod position; pub mod wpsdb;
networklocation/src/main/rust/src/mmap.rs
diff --git a/networklocation/src/main/rust/src/mmap.rs b/networklocation/src/main/rust/src/mmap.rsnew file mode 100644index 0000000000..f9bea640f1--- /dev/null+++ b/networklocation/src/main/rust/src/mmap.rs@@ -0,0 +1,101 @@+//! A read-only memory mapping of one region of a file, shared by the store and geocoder+//! readers. Mapped pages are file-backed, so the kernel can drop them under memory pressure and+//! re-read them on demand; that is what lets both readers hold multi-gigabyte files without+//! putting them on the heap.++use std::fs::File;++#[cfg(unix)]+pub(crate) struct Map {+ /// Page-aligned mapping base, as returned by `mmap`.+ addr: *mut libc::c_void,+ /// Length of the mapping, including the alignment slack before `offset`.+ len: usize,+ /// Where the requested region starts within the mapping.+ slack: usize,+}++/// Host fallback: plain heap buffer. A multi-hundred-MB host test store is not+/// the deployment target (the service is Android-only), so resident memory is+/// acceptable here; on-device this code never runs.+#[cfg(not(unix))]+pub(crate) struct Map {+ buf: Vec<u8>,+}++// The mapping is read-only and never mutated after construction.+unsafe impl Send for Map {}+unsafe impl Sync for Map {}++#[cfg(unix)]+impl Map {+ pub(crate) fn new(file: &File, offset: u64, len: usize) -> Option<Map> {+ if len == 0 {+ return None;+ }+ let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };+ if page <= 0 {+ return None;+ }+ let page = page as u64;+ let aligned = offset - (offset % page);+ let slack = (offset - aligned) as usize;+ let maplen = slack.checked_add(len)?;+ let addr = unsafe {+ libc::mmap(+ std::ptr::null_mut(),+ maplen,+ libc::PROT_READ,+ libc::MAP_PRIVATE,+ {+ use std::os::unix::io::AsRawFd;+ file.as_raw_fd()+ },+ aligned as libc::off_t,+ )+ };+ if addr == libc::MAP_FAILED {+ return None;+ }+ // Probes are scattered single-bit tests, so readahead is wasted IO.+ unsafe { libc::madvise(addr, maplen, libc::MADV_RANDOM) };+ Some(Map { addr, len: maplen, slack })+ }++ #[inline]+ pub(crate) fn as_slice(&self) -> &[u8] {+ unsafe {+ std::slice::from_raw_parts(+ (self.addr as *const u8).add(self.slack),+ self.len - self.slack,+ )+ }+ }+}++#[cfg(not(unix))]+impl Map {+ pub(crate) fn new(file: &File, offset: u64, len: usize) -> Option<Map> {+ if len == 0 {+ return None;+ }+ let mut f = file.try_clone().ok()?;+ use std::io::{Read, Seek, SeekFrom};+ f.seek(SeekFrom::Start(offset)).ok()?;+ let mut buf = vec![0u8; len];+ f.read_exact(&mut buf).ok()?;+ Some(Map { buf })+ }++ #[inline]+ pub(crate) fn as_slice(&self) -> &[u8] {+ &self.buf+ }+}++#[cfg(unix)]+impl Drop for Map {+ fn drop(&mut self) {+ unsafe { libc::munmap(self.addr, self.len) };+ }+}
networklocation/src/main/rust/src/wpsdb.rs
diff --git a/networklocation/src/main/rust/src/wpsdb.rs b/networklocation/src/main/rust/src/wpsdb.rsindex 532c53a429..e4088e2324 100644--- a/networklocation/src/main/rust/src/wpsdb.rs+++ b/networklocation/src/main/rust/src/wpsdb.rs@@ -117,105 +117,11 @@ impl Src { } } -// --------------------------------------------------------------------------- mmap-/// A read-only mapping of one region of the store. Only `high` uses this: it is the one-/// section with unpredictable access that is too large to hold resident.-#[cfg(unix)]-struct Map {- /// Page-aligned mapping base, as returned by `mmap`.- addr: *mut libc::c_void,- /// Length of the mapping, including the alignment slack before `offset`.- len: usize,- /// Where the requested region starts within the mapping.- slack: usize,-}--/// Host fallback: plain heap buffer. A multi-hundred-MB host test store is not-/// the deployment target (the service is Android-only), so resident memory is-/// acceptable here; on-device this code never runs.-#[cfg(not(unix))]-struct Map {- buf: Vec<u8>,-}--// The mapping is read-only and never mutated after construction.-unsafe impl Send for Map {}-unsafe impl Sync for Map {}--#[cfg(unix)]-impl Map {- fn new(file: &File, offset: u64, len: usize) -> Option<Map> {- if len == 0 {- return None;- }- let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };- if page <= 0 {- return None;- }- let page = page as u64;- let aligned = offset - (offset % page);- let slack = (offset - aligned) as usize;- let maplen = slack.checked_add(len)?;- let addr = unsafe {- libc::mmap(- std::ptr::null_mut(),- maplen,- libc::PROT_READ,- libc::MAP_PRIVATE,- {- use std::os::unix::io::AsRawFd;- file.as_raw_fd()- },- aligned as libc::off_t,- )- };- if addr == libc::MAP_FAILED {- return None;- }- // Probes are scattered single-bit tests, so readahead is wasted IO.- unsafe { libc::madvise(addr, maplen, libc::MADV_RANDOM) };- Some(Map { addr, len: maplen, slack })- }-- #[inline]- fn as_slice(&self) -> &[u8] {- unsafe {- std::slice::from_raw_parts(- (self.addr as *const u8).add(self.slack),- self.len - self.slack,- )- }- }-}--#[cfg(not(unix))]-impl Map {- fn new(file: &File, offset: u64, len: usize) -> Option<Map> {- if len == 0 {- return None;- }- let mut f = file.try_clone().ok()?;- use std::io::{Read, Seek, SeekFrom};- f.seek(SeekFrom::Start(offset)).ok()?;- let mut buf = vec![0u8; len];- f.read_exact(&mut buf).ok()?;- Some(Map { buf })- }-- #[inline]- fn as_slice(&self) -> &[u8] {- &self.buf- }-}--#[cfg(unix)]-impl Drop for Map {- fn drop(&mut self) {- unsafe { libc::munmap(self.addr, self.len) };- }-}- // --------------------------------------------------------------------------- reader+// `high` is read through a `crate::mmap::Map`: it is the one section with unpredictable access+// that is too large to hold resident.+use crate::mmap::Map;+ pub struct Reader { src: Src, n: u64,