Modern Apps git

← Modern-Apps.git

maps: name search reads ~300 pages instead of ~70k per query (#mapsearch)

Commit
801e028f117b94d7f36e355f0d41604f2229c6a1
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:21 UTC (22 days ago)
Parents
397a3d0
Symptom: "searching for a place takes forever". Root cause, measured
against the real planet archive (world.mamaps, 30.9 M POIs, 69.6 M
word-index entries) with a page-touch tracer around every mapped read:

  query (SF)    distinct 4 KiB pages   128 KiB windows   warm (host)
  pizza            72,501 (283 MB)        5,995           125 ms
  hotel            92,541 (361 MB)        6,390           228 ms
  cafe             85,746 (335 MB)        6,480           156 ms
  starbucks        14,901 ( 58 MB)        2,178            29 ms

Typing "pizza" key by key from a cold start touched 93 k pages. On a
phone every one of those windows is a random flash read (~0.1-0.2 ms
each), i.e. seconds per keystroke, and the warm CPU cost alone was
100-230 ms on a server core.

Where it went (old searchByWordIndex):
* rarestTokenMatches walked the rarest token's WHOLE word range (up to
  200 k entries) and verified every entry against its record's name.
  The names pool is in first-seen OSM order, so each entry was a
  scattered read: "pizza" = 80 k random name reads.
* shortlist() sorted up to 80 k candidates with a comparator that
  computed cos() per comparison (~70 ms warm for "pizza"), then decoded
  5,000 names.
* localWordMatches read the name of up to 40,000 records around the
  user, and the fuzzy pass did ~10 binary searches plus 50-entry
  name-verified walks per token even when exact hits abounded.

New engine (PoiSearchEngine.kt, PoiSearchHits.kt):
* Each token's prefix range is scanned as the index's parallel entry
  arrays (ordinal + word position): sequential, no names. The rarest
  token is materialised in an open-addressing HitTable and the other
  tokens are intersected against it, keeping per-token word-position
  masks, so "phrase" vs "every word" is known without decoding.
* Survivors are joined against the spatial grid in growing boxes
  (1.5 / 6 / 25 km) around the bias point; coordinates are read only
  for rows that are near. Only if that leaves fewer than `limit` rows
  are the remaining survivors placed: all of them when there are
  <= 1,500 ("british museum", "mcdonalds"), else a window of 1,500
  nearest the bias point in Morton (= file) order.
* Very common tokens (2-letter tails, > 250 k entries) are not read
  whole: they drive a per-box join with an ordinal-range pre-filter,
  or are checked against the names of the few candidates.
* Fallbacks only when short of results: a name scan of up to 5,000
  records within 0.8 km (mid-word substrings, typos, punctuation via
  PoiSearch.matchTier), then the index-wide typo lookup.
* Names are decoded only for the 30-row shortlist (+ nearest
  phrase-matching place labels). The ranking order itself is unchanged
  in this commit (rank, exact place/local name, boost, distance).
* Every scan polls the cancel token from the previous commit.
* PoiIndexSpatial gains forEachGridOrdinal (cell ordinals, no per-row
  coordinate test or sort) and walks a box row by row; nearest() and
  inViewport() return identical results (verified on the planet).

After (same tracer, same queries, SF):

  query (SF)    pages   128 KiB windows   warm (host)
  pizza           299        122            2.5 ms
  hotel           376        116            3.9 ms
  cafe            340        119            3.3 ms
  starbucks       179         97            3.7 ms
  st (2 letters) 1,217       171            3.4 ms
  typing "pizza" from cold: 903 pages (was 93,364)

Verified: PoiIndexTest, PoiIndexSmartTest, PoiArchiveTest and
PoiArchiveRealFileTest (MAMAPS_REAL_ARCHIVE=world.mamaps: Golden Gate
Bridge, Empire State Building, British Museum, Oakland/Brooklyn/Camden
Town place labels all still found) pass when compiled standalone
against these sources; full module build/tests/lint/detekt in the
container.

Diff

maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex 9d69d147ff..744ff7e6c7 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -632,9 +632,11 @@ object PoiIndex {      *      * Two implementations, picked by whether `poi_name_index.bin` was mapped:      *-     *  * **Indexed** — binary search to the query's place in a word-sorted index, then a-     *    walk of the matching range, so the cost is the number of matches. Because every-     *    word of a name is indexed, "pizza" still finds "Joe's Pizza".+     *  * **Indexed** — binary search to each token's range in the word-sorted index, then+     *    sequential scans of those ranges' ordinal arrays joined against the spatial grid+     *    around the bias point, so the cost is a few hundred page reads and names are+     *    decoded only for the rows returned (see PoiSearchEngine.kt). Because every word+     *    of a name is indexed, "pizza" still finds "Joe's Pizza".      *  * **Scan** — the name pool, then every record. Two passes whose cost is the whole      *    dataset, kept only because the side file is optional.      *@@ -666,7 +668,7 @@ object PoiIndex {         // Fully-qualified: the package-level search lives in PoiIndexWords.kt.         if (m.nameIdx != null) {             return com.vayunmathur.maps.util.searchByWordIndex(-                m, query, SearchBias(nearLat, nearLon, limit, boost), CANDIDATE_CAP, cancelled,+                m, query, SearchBias(nearLat, nearLon, limit, boost), cancelled,             )         }         return searchByScan(m, query, nearLat, nearLon, limit, boost)
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.ktindex d0a9050982..4b9e061e45 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt@@ -26,18 +26,73 @@ private fun PoiIndex.Mapped.axis(value: Int, origin: Int): Int { private fun PoiIndex.Mapped.row(latE7: Int): Int = axis(latE7, lat0E7) private fun PoiIndex.Mapped.col(lonE7: Int): Int = axis(lonE7, lon0E7).coerceAtMost(cols - 1) -/** Index of [cellId] in the ascending cell-id array, or -1 when unpopulated. */-private fun PoiIndex.Mapped.cellIndexOf(cellId: Int): Int {-    val buf = spatial ?: return -1+/** The [i]th entry of the ascending populated-cell-id array. */+private fun PoiIndex.Mapped.cellIdAt(i: Int): Int =+    spatial!!.getInt(PoiIndex.SPATIAL_HEADER_BYTES + CELL_SLOT_BYTES * i)++/** Index of the first populated cell whose id is >= [cellId], or [PoiIndex.Mapped.cellCount]. */+private fun PoiIndex.Mapped.cellLowerBound(cellId: Int): Int {     var lo = 0     var hi = cellCount     while (lo < hi) {         val mid = (lo + hi) ushr 1-        val v = buf.getInt(PoiIndex.SPATIAL_HEADER_BYTES + CELL_SLOT_BYTES * mid)-        if (v == cellId) return mid-        if (v < cellId) lo = mid + 1 else hi = mid+        if (cellIdAt(mid) < cellId) lo = mid + 1 else hi = mid+    }+    return lo+}++/**+ * Visit the populated cells overlapping the box, as indices into the cell arrays, stopping+ * when [onCell] returns false.+ *+ * One binary search per grid ROW, then a forward walk of the ascending cell-id array across+ * the row (a row's populated cells are adjacent in that array), rather than one binary+ * search per cell of the box.+ */+internal fun PoiIndex.Mapped.forEachCellInBox(+    minLatE7: Int,+    maxLatE7: Int,+    minLonE7: Int,+    maxLonE7: Int,+    onCell: (cellIndex: Int) -> Boolean,+) {+    if (spatial == null || cellCount <= 0 || cols <= 0 || cellE7 <= 0) return+    val c0 = col(minLonE7)+    val c1 = col(maxLonE7)+    for (r in row(minLatE7)..row(maxLatE7)) {+        val last = r.toLong() * cols + c1+        var ci = cellLowerBound((r.toLong() * cols + c0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt())+        while (ci < cellCount && cellIdAt(ci) <= last) {+            if (!onCell(ci)) return+            ci+++        }+    }+}++/**+ * Every ordinal filed under the populated cells overlapping the box, cell by cell, with no+ * per-record coordinate test and no sort: for callers that compute each hit's distance+ * themselves anyway (name search), the cell granularity (~2 km) is the whole filter they+ * need. Stops when [visit] returns false.+ */+internal fun PoiIndex.Mapped.forEachGridOrdinal(+    minLatE7: Int,+    maxLatE7: Int,+    minLonE7: Int,+    maxLonE7: Int,+    visit: (ordinal: Int) -> Boolean,+) {+    forEachCellInBox(minLatE7, maxLatE7, minLonE7, maxLonE7) { ci ->+        var k = cellOff(ci)+        val end = cellOff(ci + 1)+        var go = true+        while (go && k < end) {+            val ordinal = gridOrdinal(k)+            if (ordinal in 0 until count) go = visit(ordinal)+            k+++        }+        go     }-    return -1 }  /** CSR prefix entry [i], i.e. where cell `i`'s ordinals begin. */@@ -60,20 +115,11 @@ internal fun PoiIndex.Mapped.forEachInCells(     onHit: (ordinal: Int, latE7: Int, lonE7: Int) -> Boolean, ) {     val hits = ArrayList<Int>()-    for (r in row(minLatE7)..row(maxLatE7)) {-        for (c in col(minLonE7)..col(maxLonE7)) {-            val ci = cellIndexOf(r * cols + c)-            if (ci < 0) continue-            for (k in cellOff(ci) until cellOff(ci + 1)) {-                val ordinal = gridOrdinal(k)-                if (ordinal < 0 || ordinal >= count) continue-                if (latE7(ordinal) in minLatE7..maxLatE7 &&-                    lonE7(ordinal) in minLonE7..maxLonE7-                ) {-                    hits.add(ordinal)-                }-            }+    forEachGridOrdinal(minLatE7, maxLatE7, minLonE7, maxLonE7) { ordinal ->+        if (latE7(ordinal) in minLatE7..maxLatE7 && lonE7(ordinal) in minLonE7..maxLonE7) {+            hits.add(ordinal)         }+        true     }     hits.sort()     for (ordinal in hits) {
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.ktindex 3a4d650bd9..c61b920d8d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt@@ -1,51 +1,42 @@ package com.vayunmathur.maps.util  /**- * Planet-scale halves of the indexed name search ([searchByWordIndex]).+ * Query tokens against `poi_name_index.bin`: each token's sort-key variants, their prefix+ * ranges, and sequential scans of those ranges.  *- * The word index was designed against state-sized archives, where walking the first- * [PoiIndex.CANDIDATE_CAP] entries of a word's prefix range saw every match. A planet- * (planet4: 30.9 M records, 69.6 M word entries) breaks that: a range is sorted by word and- * then by ordinal, ordinals are Morton-sorted, so a capped walk sees one arbitrary corner of- * the world. Two fixes, both bounded:- *- *  * [rarestTokenMatches] — measure every token's range (two binary searches each), walk the- *    smallest one whole, and check the other tokens against each candidate's own name.- *  * [localWordMatches] — scan the spatial grid around the search centre in growing rings,- *    under a visit budget, so a common word ("cafe") still finds what is near the user. It- *    reads each name anyway, so it also answers mid-word substrings ("izza" → "Pizza") the- *    way the scan path does, which a sorted word index cannot.+ * A range is read as two parallel arrays — `ordinals[i]` (4 bytes) and `word_idx[i]`+ * (1 byte) — which sit contiguously in the section, so scanning even a large range is a+ * sequential read of a few hundred KiB and never touches a name. That is the whole point:+ * the previous search verified every entry of a range against its record's NAME, and the+ * names pool is ordered by first appearance in the OSM file, so a range of 80 k "pizza"+ * entries meant ~70 k scattered 4 KiB reads (283 MB of distinct pages on the planet) before+ * a single result could be ranked. The search engine ([searchByWordIndex]) works on+ * ordinals and word positions from these scans and decodes names only for the rows it is+ * about to return.  */ -/** Rank of a name that starts with the whole phrase (tokens on its first words, in order). */-private const val RANK_PHRASE = 0--/** Rank of a name where every token starts some word. */-private const val RANK_WORDS = 1--/** No match. */-private const val RANK_NONE = -1- private const val BYTE_MASK = 0xFF -/** Rings the local pass grows through, in metres from the search centre. */-private val LOCAL_RADII_M = doubleArrayOf(2_000.0, 10_000.0, 40_000.0, 150_000.0)--/** Records the local pass checks at most, across all rings. */-private const val LOCAL_VISIT_BUDGET = 40_000--private const val METERS_PER_DEGREE_LAT = 111_320.0-private const val MIN_COS_LAT = 1e-6-private const val E7_PER_DEGREE = 1e7+/** How often (in entries) a long scan polls its cancel token. */+private const val SCAN_POLL_MASK = 0xFFFF  /** Entries `[first, last]` whose word starts with [key]; empty when none. */ internal fun PoiIndex.Mapped.prefixRange(key: ByteArray): IntRange {-    if (nameIdx == null || entryCount == 0) return IntRange.EMPTY+    if (nameIdx == null || entryCount == 0 || key.isEmpty()) return IntRange.EMPTY     val lo = lowerBoundWord(key)+    // Most variants (an accented spelling nobody uses) are empty: one probe settles it+    // instead of a second binary search.+    if (lo >= entryCount || !wordStartsWithAt(lo, key)) return IntRange.EMPTY     val hi = nextPrefix(key)?.let { lowerBoundWord(it) } ?: entryCount     return lo until hi } +/** Whether entry [i]'s word starts with [key] (an unresolvable word does not). */+private fun PoiIndex.Mapped.wordStartsWithAt(i: Int, key: ByteArray): Boolean {+    val range = wordRange(nameOff(entryOrdinal(i)), entryWordIdx(i)) ?: return false+    return wordStartsWith(range, key)+}+ /**  * The smallest key strictly greater than every key starting with [key] (its last  * non-0xFF byte incremented, the rest dropped), or null when no such key exists.@@ -58,176 +49,63 @@ private fun nextPrefix(key: ByteArray): ByteArray? { }  /**- * Ordinal → rank for every record whose name matches all [keys], found by walking the- * rarest key's whole prefix range; null when even that range is longer than [walkCap]- * (the caller then falls back to capped walks plus the local pass).+ * One query token: the text the user typed, every sort-key spelling it should match+ * ([tokenKeyVariants]) and the word-index ranges of those spellings.  */-internal fun PoiIndex.Mapped.rarestTokenMatches(keys: List<ByteArray>, walkCap: Int): Map<Int, Int>? {-    if (keys.isEmpty() || nameIdx == null) return null-    val ranges = keys.map { prefixRange(it) }-    val rarest = ranges.minBy { it.last - it.first + 1 }-    val size = rarest.last - rarest.first + 1-    if (size <= 0) return emptyMap()-    if (size > walkCap) return null-    val out = HashMap<Int, Int>()-    for (i in rarest) {-        val ordinal = entryOrdinal(i)-        if (ordinal < 0 || ordinal >= count || ordinal in out) continue-        val rank = nameTokenRank(ordinal, keys)-        if (rank != RANK_NONE) out[ordinal] = rank-    }-    return out+internal class QueryToken(val text: String, val ranges: List<IntRange>) {+    /** Entries across all of this token's ranges. */+    val size: Int = ranges.sumOf { it.last - it.first + 1 } } -/**- * The pre-planet exact pass: per-token walks capped at [cap] entries, intersected on the- * ordinal, each survivor re-ranked from its own name. Only used when every token is too- * common to walk whole.- */-internal fun cappedExactMatches(m: PoiIndex.Mapped, keys: List<ByteArray>, cap: Int): Map<Int, Int> {-    var ordinals: Set<Int>? = null-    for (key in keys) {-        val hits = m.wordPrefixMatches(key, cap).mapTo(HashSet()) { it[0] }-        ordinals = ordinals?.intersect(hits) ?: hits+/** The tokens of [query], each with its key variants resolved to ranges. */+internal fun PoiIndex.Mapped.queryTokens(query: String): List<QueryToken> =+    splitTokens(query.trim()).map { token ->+        val ranges = tokenKeyVariants(token).map { prefixRange(it) }.filterNot { it.isEmpty() }+        QueryToken(token, disjoint(ranges))     }-    val out = HashMap<Int, Int>()-    for (o in ordinals.orEmpty()) {-        val rank = m.nameTokenRank(o, keys)-        if (rank != RANK_NONE) out[o] = rank-    }-    return out++/** [ranges] with duplicates and any range nested inside another dropped, so no entry counts twice. */+private fun disjoint(ranges: List<IntRange>): List<IntRange> {+    val unique = ranges.distinct()+    return unique.filter { r -> unique.none { o -> o != r && o.first <= r.first && r.last <= o.last } } } +/** Every index sort key the token is looked up under: its ASCII-folded bytes. */+internal fun tokenKeyVariants(token: String): List<ByteArray> = listOf(poiQueryKey(token))+ /**- * Ordinal → rank for records near ([lat],[lon]) whose name matches all [keys]: rings of- * [LOCAL_RADII_M] through the spatial index, nearest ring first, stopping once [want]- * matches are in hand or [LOCAL_VISIT_BUDGET] records were checked.+ * Visit every entry of [token]'s ranges, in index order, as (ordinal, entry index); the+ * visitor reads the entry's word position ([entryWordIdx]) only when it wants it. Reads+ * only the entry arrays, sequentially. Returns false when [cancelled] fired mid-scan.  */-internal fun PoiIndex.Mapped.localWordMatches(-    keys: List<ByteArray>,-    lat: Double,-    lon: Double,-    want: Int,-): Map<Int, Int> {-    if (keys.isEmpty() || count == 0) return emptyMap()-    val out = HashMap<Int, Int>()-    val seen = HashSet<Int>()-    var visited = 0-    val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(MIN_COS_LAT)-    for (radius in LOCAL_RADII_M) {-        val dLat = radius / METERS_PER_DEGREE_LAT-        val dLon = radius / (METERS_PER_DEGREE_LAT * cosLat)-        forEachInBbox(-            ((lat - dLat) * E7_PER_DEGREE).toInt(),-            ((lat + dLat) * E7_PER_DEGREE).toInt(),-            ((lon - dLon) * E7_PER_DEGREE).toInt(),-            ((lon + dLon) * E7_PER_DEGREE).toInt(),-        ) { ordinal, _, _ ->-            if (seen.add(ordinal)) {-                visited++-                var rank = nameTokenRank(ordinal, keys)-                if (rank == RANK_NONE && nameContainsAll(ordinal, keys)) rank = RANK_WORDS-                if (rank != RANK_NONE) out[ordinal] = rank-            }-            visited < LOCAL_VISIT_BUDGET+internal inline fun PoiIndex.Mapped.scanToken(+    token: QueryToken,+    cancelled: () -> Boolean,+    visit: (ordinal: Int, entry: Int) -> Unit,+): Boolean {+    for (range in token.ranges) {+        for (i in range) {+            if (i and SCAN_POLL_MASK == 0 && cancelled()) return false+            val ordinal = entryOrdinal(i)+            if (ordinal in 0 until count) visit(ordinal, i)         }-        if (out.size >= want || visited >= LOCAL_VISIT_BUDGET) break     }-    return out+    return true }  /**- * How record [ordinal]'s name matches [keys]: [RANK_PHRASE] when word `t` starts with key- * `t` for every token, [RANK_WORDS] when every key starts some word, else [RANK_NONE].- * Same word split and ASCII case fold as the index itself (`poi_side.rs`).+ * Whether some word of record [ordinal]'s name starts with one of [token]'s spellings —+ * the name-side check for a token too common to scan (a one- or two-letter tail such as+ * "golden g"). Same word split and ASCII fold as the index itself.  */-internal fun PoiIndex.Mapped.nameTokenRank(ordinal: Int, keys: List<ByteArray>): Int {+internal fun PoiIndex.Mapped.nameHasWordPrefix(ordinal: Int, keys: List<ByteArray>): Boolean {     val off = nameOff(ordinal)-    val matched = BooleanArray(keys.size)-    var phrase = true     var w = 0-    while (true) {+    var found = false+    while (!found) {         val range = wordRange(off, w) ?: break-        for (t in keys.indices) {-            val hit = wordStartsWith(range, keys[t])-            if (hit) matched[t] = true-            if (w == t && !hit) phrase = false-        }+        found = keys.any { wordStartsWith(range, it) }         w++     }-    if (w < keys.size) phrase = false-    return when {-        matched.any { !it } -> RANK_NONE-        phrase -> RANK_PHRASE-        else -> RANK_WORDS-    }-}--/** Whether every key occurs somewhere in record [ordinal]'s name (ASCII case-folded bytes). */-private fun PoiIndex.Mapped.nameContainsAll(ordinal: Int, keys: List<ByteArray>): Boolean {-    val off = nameOff(ordinal)-    if (off < 0 || off >= namesLen) return false-    var end = off-    while (end < namesLen && names.get(end).toInt() != 0) end++-    val folded = ByteArray(end - off) { asciiLowerW(names.get(off + it)).toByte() }-    return keys.all { key -> indexOf(folded, key) >= 0 }-}--/** First index of [needle] in [hay], or -1. Names are short; a naive scan is enough. */-private fun indexOf(hay: ByteArray, needle: ByteArray): Int {-    if (needle.isEmpty()) return 0-    outer@ for (i in 0..hay.size - needle.size) {-        for (j in needle.indices) if (hay[i + j] != needle[j]) continue@outer-        return i-    }-    return -1+    return found }--/** Candidates whose names are decoded and boost-ranked; the rest lose on (rank, distance). */-private const val DECODE_SHORTLIST = 5_000--/**- * Fuzzy pass: ordinal → rank 2 for names where every token matches exactly or within one- * edit, minus the exact [ordinals]. Runs even when the exact pass hit — a typo'd name- * ("Piza Kitchen" for "pizza") should surface below the exact hits, not vanish. Tokens under- * [MIN_TYPO_TOKEN_LEN] chars are all typo-noise and contribute their exact matches only.- */-internal fun fuzzyMatches(-    m: PoiIndex.Mapped,-    tokens: List<String>,-    exact: List<Map<Int, Int>>,-    ordinals: Set<Int>,-    candidateCap: Int,-): Map<Int, Int> {-    var fuzzyOrdinals: Set<Int>? = null-    for (t in tokens.indices) {-        val set = HashSet(exact[t].keys)-        set.addAll(ordinals)-        if (tokens[t].length >= MIN_TYPO_TOKEN_LEN) {-            set.addAll(m.fuzzyWordMatches(tokens[t], candidateCap).keys)-        }-        fuzzyOrdinals = fuzzyOrdinals?.intersect(set) ?: set-    }-    return fuzzyOrdinals.orEmpty().filter { it !in ordinals }.associateWith { 2 }-}--/**- * At most [DECODE_SHORTLIST] of [candidates] (ordinal, rank), best (rank, distance) first.- * A whole-range walk can hand back tens of thousands of matches; decoding every name (for- * the record and the boost) would dominate the search, so the cut uses only the index's- * coordinates.- */-internal fun PoiIndex.Mapped.shortlist(-    candidates: List<Pair<Int, Int>>,-    lat: Double,-    lon: Double,-): List<Pair<Int, Int>> {-    if (candidates.size <= DECODE_SHORTLIST) return candidates-    return candidates.sortedWith(-        compareBy<Pair<Int, Int>> { it.second }.thenBy { (o, _) -> distanceSqTo(o, lat, lon) },-    ).take(DECODE_SHORTLIST)-}--/** Squared degree distance from record [ordinal] to ([lat],[lon]), straight from the index. */-private fun PoiIndex.Mapped.distanceSqTo(ordinal: Int, lat: Double, lon: Double): Double =-    PoiIndex.distanceSq(lat, lon, latE7(ordinal) * PoiIndex.E7_TO_DEGREES, lonE7(ordinal) * PoiIndex.E7_TO_DEGREES)
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.ktindex a99ebd1ac4..1fa6e2b240 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt@@ -161,13 +161,6 @@ internal class SearchBias(     val boost: Map<String, Double> = emptyMap(), ) -private class WordRanked(-    val record: PoiIndex.PoiRecord,-    val boost: Double,-    val rank: Int,-    val distSq: Double,-)- private class Ranked(     val record: PoiIndex.PoiRecord,     val boost: Double,@@ -176,7 +169,7 @@ private class Ranked( )  /** Whitespace-separated, non-empty query tokens; callers fold case first. */-private fun splitTokens(q: String): List<String> =+internal fun splitTokens(q: String): List<String> =     q.split(' ', '\t', '\n', '\r', '', '').filter { it.isNotEmpty() }  /**@@ -340,111 +333,6 @@ private fun scanMatchAt(     ) } -/**- * Ordinals whose name matches every query token, each paired with its rank:- * 0 = the name starts with the whole phrase ("blue bottle" → "Blue Bottle- * Coffee"), 1 = every token starts a word, 2 = every token starts a word or- * is a one-edit typo of one.- *- * Single-token queries behave exactly as before. Multi-token queries used to- * look up the whole spaced string as one key and always miss; fuzzy matches- * are new. The fuzzy pass only runs per token (deletion variants of the token- * as prefix lookups, verified by edit distance), so its cost stays in the- * number of near-matches rather than the size of the word pool.- */-internal fun searchByWordIndex(-    m: PoiIndex.Mapped,-    query: String,-    bias: SearchBias,-    candidateCap: Int,-    cancelled: () -> Boolean = { false },-): List<PoiIndex.PoiRecord> {-    val nearLat = bias.lat-    val nearLon = bias.lon-    val limit = bias.limit-    val boost = bias.boost-    val tokens = splitTokens(query.trim())-    if (tokens.isEmpty()) return emptyList()-    val keys = tokens.map { poiQueryKey(it) }--    // Exact pass, planet-safe: walk the RAREST token's whole prefix range and verify the-    // other tokens against each candidate's own name ([rarestTokenMatches]). The old-    // per-token walks stopped at [candidateCap] entries in word order, which at planet scale-    // (30.9 M records, 69.6 M word entries in planet4) is an arbitrary Morton slice of the-    // world: "golden" alone has tens of thousands of entries, so "Golden Gate Bridge" from-    // SF intersected to a Lego model in Carlsbad and "British Museum" to nothing. When even-    // the rarest token is too common to walk whole ("cafe"), fall back to the capped walks;-    // the local pass below then supplies the nearby hits.-    val exactRanks: Map<Int, Int> = m.rarestTokenMatches(keys, FULL_WALK_CAP)-        ?: cappedExactMatches(m, keys, candidateCap)-    val exact = keys.map { key ->-        if (keys.size == 1) {-            emptyMap()-        } else {-            m.wordPrefixMatches(key, FUZZY_EXACT_SEED_CAP).associate { it[0] to it[1] }-        }-    }-    if (cancelled()) return emptyList()-    val local = m.localWordMatches(keys, nearLat, nearLon, limit)-    if (cancelled()) return emptyList()-    val ordinals: Set<Int> = exactRanks.keys + local.keys-    fun isPhrasePrefix(o: Int): Boolean = (exactRanks[o] ?: local[o]) == 0--    val fuzzy = fuzzyMatches(m, tokens, exact, ordinals, candidateCap)-    if (cancelled()) return emptyList()-    val shortlist = m.shortlist(-        ordinals.map { it to if (isPhrasePrefix(it)) 0 else 1 } + fuzzy.toList(),-        nearLat,-        nearLon,-    )-    val out = ArrayList<WordRanked>(shortlist.size)-    for ((o, rank) in shortlist) {-        out.add(wordRanked(m, o, rank, nearLat, nearLon, boost))-    }-    // Within a rank, a name that IS the query comes first when it is a place label (type 51:-    // "Oakland" the city, among hundreds of "Oakland …" businesses nearer the centre — a city-    // is searched for from anywhere) or is local (a same-named bar on another continent must-    // not beat the "Tokyo Station Cafe" next to the user); then the user's signal; then-    // distance.-    val whole = query.trim()-    fun exactTier(r: WordRanked): Boolean =-        r.record.name.equals(whole, ignoreCase = true) &&-            (r.record.type == PoiCategories.TYPE_PLACE || r.distSq <= EXACT_LOCAL_DEG_SQ)-    out.sortWith(-        compareBy<WordRanked> { it.rank }-            .thenBy { !exactTier(it) }-            .thenByDescending { it.boost }-            .thenBy { it.distSq },-    )-    return out.take(limit).map { it.record }-}--/** "Local" for the exact-name tier: ~0.5° (≈55 km) from the centre, squared. */-private const val EXACT_LOCAL_DEG_SQ = 0.25---private fun wordRanked(-    m: PoiIndex.Mapped,-    ordinal: Int,-    rank: Int,-    nearLat: Double,-    nearLon: Double,-    boost: Map<String, Double>,-): WordRanked {-    val record = m.record(ordinal)-    return WordRanked(-        record,-        boostWeight(boost, record.name),-        rank,-        PoiIndex.distanceSq(-            nearLat,-            nearLon,-            m.latE7(ordinal) * PoiIndex.E7_TO_DEGREES,-            m.lonE7(ordinal) * PoiIndex.E7_TO_DEGREES,-        ),-    )-}- /**  * Ordinals with a word within one edit of the query [token], as  * ordinal → word index.@@ -496,16 +384,6 @@ private fun PoiIndex.Mapped.wordWithinOneEdit(ordinal: Int, wordIdx: Int, token:     return editDistanceLE1(token, String(word)) } -/**- * Entries the exact pass will walk for the rarest query token before it falls back to the- * capped walks: a planet's rare words ("tartine", "golden") are well under this, its common- * ones ("cafe", "street") well over.- */-private const val FULL_WALK_CAP = 200_000--/** Per-token exact seed for the fuzzy intersection (its exact half), kept small. */-private const val FUZZY_EXACT_SEED_CAP = 2_000- /** Shortest token the typo passes consider (shorter ones are all typo-noise). */ internal const val MIN_TYPO_TOKEN_LEN = 3 
maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.ktnew file mode 100644index 0000000000..a98df7fde5--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt@@ -0,0 +1,364 @@+package com.vayunmathur.maps.util++/**+ * The indexed name search: [searchByWordIndex] and the candidate collection behind it.+ *+ * Built around what a cold planet archive costs on a phone. The old search was correct but+ * read far too much: for every query it walked the rarest token's whole word range+ * checking each entry against its record's name, decoded and distance-sorted up to 5,000+ * of the matches, then also scanned up to 40,000 records around the user by name. "pizza"+ * from San Francisco touched 72 k distinct 4 KiB pages (283 MB) of the archive; "hotel"+ * 92 k. On flash that is seconds per keystroke, which is what "searching takes forever"+ * was. This version keeps the same answer shape while reading a few hundred pages:+ *+ *  1. **Tokens -> word ranges** (two binary searches per spelling, [queryTokens]).+ *  2. **Candidates from ordinals only.** The rarest token's range is scanned sequentially+ *     into a [HitTable]; every other token's range is scanned and marked against it, so a+ *     multi-word query is an intersection of entry arrays — no names read. Word positions+ *     ride along, so "phrase" vs "every word" is known without the name too.+ *  3. **Where.** A small survivor set is placed in full (it is the whole world's answer:+ *     "british museum", "ferry building"). A large one ("pizza", 81 k entries) is joined+ *     against the spatial grid in growing boxes around the bias point, then — only when+ *     those boxes yield too little — against a window of survivors nearest the bias point+ *     in Morton (= file) order. Coordinates are read only for rows that are actually+ *     near.+ *  4. **Fallbacks only when short of results:** a name scan of the few thousand records+ *     closest to the bias point (mid-word substrings, typos, punctuation), then the+ *     index-wide typo lookup.+ *  5. **Rank and decode** at most [SHORTLIST] names.+ *+ * Every scan polls the caller's cancel token, so a superseded keystroke stops promptly.+ */++/** Longest token range that is scanned at all; longer ones (one- or two-letter+ *  prefixes like "s") are checked against candidates' names instead. */+private const val STREAM_CAP = 1_500_000++/** Largest driver range materialised into a table (the others are joined ring by ring). */+private const val MATERIALIZE_CAP = 250_000++/** Survivor sets up to this size are placed whole: their coordinates are all read. */+private const val GLOBAL_ALL_CAP = 1_500++/** Half-sizes of the boxes around the bias point the grid join grows through. */+private val RING_HALF_KM = doubleArrayOf(1.5, 6.0, 25.0)++/** Survivors nearest the bias point in file order read when the boxes come up short. */+private const val REGIONAL_WINDOW = 1_500++/** The name-scan fallback's box half-size and record budget. */+private const val NAME_SCAN_HALF_KM = 0.8+private const val NAME_SCAN_BUDGET = 5_000++/** Candidates whose names are decoded for the final ranking. */+private const val SHORTLIST = 30++/** Place-label candidates decoded besides the shortlist (a city's exact name is wanted+ *  from anywhere). */+private const val PLACE_SHORTLIST = 20++/** Shortest token allowed to drive the candidate scan. */+private const val MIN_DRIVER_LEN = 2++private const val KM_PER_DEGREE = 111.32+private const val E7_PER_DEGREE = 1e7+private const val MIN_COS_LAT = 1e-6+private const val POLL_EVERY = 4_096++/** One candidate row: where it is and how its name matched (a [PoiSearch] tier). */+internal class Candidate(+    val ordinal: Int,+    val latE7: Int,+    val lonE7: Int,+    val type: Int,+    var tier: Int,+    val distKm: Double,+)++/**+ * Name search over the word index. See the file comment for the phases; ranking is+ * [rankCandidates].+ */+internal fun searchByWordIndex(+    m: PoiIndex.Mapped,+    query: String,+    bias: SearchBias,+    cancelled: () -> Boolean = { false },+): List<PoiIndex.PoiRecord> {+    val tokens = m.queryTokens(query)+    if (tokens.isEmpty()) return emptyList()+    val search = CandidateSearch(m, query, tokens, bias, cancelled)+    search.collectIndexed()+    if (search.size < bias.limit) search.collectNearbyNames(acceptLoose = true)+    if (search.size < bias.limit / 2) search.collectIndexTypos()+    if (cancelled()) return emptyList()+    return rankCandidates(m, query, search.candidates(), bias)+}++/** Mutable state of one search: the tokens, the bias point and the candidates so far. */+internal class CandidateSearch(+    private val m: PoiIndex.Mapped,+    query: String,+    private val tokens: List<QueryToken>,+    private val bias: SearchBias,+    private val cancelled: () -> Boolean,+) {+    private val found = LinkedHashMap<Int, Candidate>()+    private val queryNorm = PoiSearch.normalize(query)+    private val queryWords = PoiSearch.tokens(query)+    private val cosLat = Math.cos(Math.toRadians(bias.lat)).coerceAtLeast(MIN_COS_LAT)++    /** The rarest token long enough to drive the scan, or null when none is. */+    private val driver: Int? = tokens.indices+        .filter { tokens[it].text.length >= MIN_DRIVER_LEN && tokens[it].size <= STREAM_CAP }+        .minByOrNull { tokens[it].size }++    /**+     * Tokens whose ranges are scanned: the driver, and every other token whose range is no+     * bigger than [MATERIALIZE_CAP] or the driver's own. A two-letter tail ("st" in "123+     * market st": a million entries against a few thousand) is checked against the names+     * of the few candidates instead of being read whole.+     */+    private val scanned: List<Int> = driver?.let { d ->+        val cap = maxOf(MATERIALIZE_CAP, tokens[d].size)+        tokens.indices.filter {+            it == d || (tokens[it].text.length >= MIN_DRIVER_LEN && tokens[it].size <= cap)+        }+    }.orEmpty()+    private val unscannedKeys: List<List<ByteArray>> = tokens.indices.filter { it !in scanned }+        .map { tokenKeyVariants(tokens[it].text) }++    val size: Int get() = found.size++    fun candidates(): Collection<Candidate> = found.values++    /** Phases 2-3: candidates from the word index, placed near the bias point first. */+    fun collectIndexed() {+        val driver = driver+        when {+            // Every token is one letter or matches millions of words: nothing to scan.+            driver == null -> collectNearbyNames(acceptLoose = false)+            tokens[driver].size == 0 -> Unit+            tokens[driver].size <= MATERIALIZE_CAP -> collectMaterialized(driver)+            else -> collectStreaming(driver)+        }+    }++    /** The driver's whole range in a table, intersected with the other scanned tokens. */+    private fun collectMaterialized(driver: Int) {+        val table = HitTable(tokens.size, tokens[driver].size)+        if (!m.scanToken(tokens[driver], cancelled) { o, e -> table.mark(table.add(o), driver, m.entryWordIdx(e)) }) return+        for (t in scanned) {+            if (t == driver) continue+            val ok = m.scanToken(tokens[t], cancelled) { o, e ->+                val i = table.indexOf(o)+                if (i >= 0) table.mark(i, t, m.entryWordIdx(e))+            }+            if (!ok) return+        }+        val survivors = BooleanArray(table.size) { i -> scanned.all { table.mask(i, it) != 0L } }+        val count = survivors.count { it }+        if (count == 0) return+        // Near first: the grid's ordinals are a sequential read, a survivor's coordinates a+        // random one, so even a small survivor set is only placed whole when the boxes+        // around the bias point did not already fill the page.+        for (half in RING_HALF_KM) {+            forEachOrdinalNear(half) { o ->+                val i = table.indexOf(o)+                if (i >= 0 && survivors[i]) addIndexed(o, table, i)+                true+            }+            if (found.size >= bias.limit || cancelled()) return+        }+        if (count <= GLOBAL_ALL_CAP) {+            for (i in 0 until table.size) if (survivors[i]) addIndexed(table.ordinals[i], table, i)+        } else {+            collectRegional(table, survivors)+        }+    }++    /**+     * A driver too common to materialise (a two- or three-letter prefix): each box's+     * records go into a small table and the token ranges are scanned against it.+     */+    private fun collectStreaming(driver: Int) {+        for (half in RING_HALF_KM) {+            val local = HitTable(tokens.size, POLL_EVERY)+            var lo = Int.MAX_VALUE+            var hi = Int.MIN_VALUE+            forEachOrdinalNear(half) { o ->+                local.add(o)+                if (o < lo) lo = o+                if (o > hi) hi = o+                true+            }+            if (local.size == 0) continue+            for (t in listOf(driver) + scanned.filter { it != driver }) {+                // The box's ordinals span a narrow slice of the Morton-ordered file, so most of+                // a two-letter prefix's million entries are rejected by one compare.+                val ok = m.scanToken(tokens[t], cancelled) { o, e ->+                    if (o in lo..hi) {+                        val i = local.indexOf(o)+                        if (i >= 0) local.mark(i, t, m.entryWordIdx(e))+                    }+                }+                if (!ok) return+            }+            for (i in 0 until local.size) {+                if (scanned.all { local.mask(i, it) != 0L }) addIndexed(local.ordinals[i], local, i)+            }+            if (found.size >= bias.limit) return+        }+    }++    /**+     * Survivors nearest the bias point in Morton order — the file's order, so a window of+     * them around the bias point's own position is mostly the region around it — for when+     * even the largest box came up short (a rare chain, a small town).+     */+    private fun collectRegional(table: HitTable, survivors: BooleanArray) {+        var n = 0+        val packed = LongArray(survivors.count { it })+        for (i in 0 until table.size) {+            if (survivors[i]) packed[n++] = (table.ordinals[i].toLong() shl Int.SIZE_BITS) or i.toLong()+        }+        packed.sort()+        val centre = m.lowerBound(spatialFromE7(toE7(bias.lat), toE7(bias.lon)))+        var hi = lowerBoundPacked(packed, centre)+        var lo = hi - 1+        var taken = 0+        while (taken < REGIONAL_WINDOW && (lo >= 0 || hi < packed.size)) {+            val pickLow = hi >= packed.size ||+                (lo >= 0 && centre - (packed[lo] ushr Int.SIZE_BITS) <= (packed[hi] ushr Int.SIZE_BITS) - centre)+            val p = if (pickLow) packed[lo--] else packed[hi++]+            addIndexed((p ushr Int.SIZE_BITS).toInt(), table, p.toInt())+            taken+++        }+    }++    /**+     * Phase 4a: names of the records closest to the bias point, matched leniently+     * ([acceptLoose]: mid-word substrings and typos too) or by word prefix only.+     */+    fun collectNearbyNames(acceptLoose: Boolean) {+        if (queryWords.isEmpty()) return+        var visited = 0+        val halves = if (acceptLoose) doubleArrayOf(NAME_SCAN_HALF_KM) else RING_HALF_KM.copyOf(2)+        for (half in halves) {+            forEachOrdinalNear(half) { o ->+                if (o !in found) {+                    visited+++                    val name = m.nameAt(m.nameOff(o))+                    val tier = if (name == null) PoiSearch.NO_MATCH else PoiSearch.matchTier(name, queryNorm, queryWords)+                    val accept = tier != PoiSearch.NO_MATCH && (acceptLoose || tier <= PoiSearch.TIER_TOKENS)+                    if (accept) add(o, tier)+                }+                visited < NAME_SCAN_BUDGET && !(visited % POLL_EVERY == 0 && cancelled())+            }+            if (found.size >= bias.limit || visited >= NAME_SCAN_BUDGET) return+        }+    }++    /**+     * Phase 4b: index-wide typo lookup ([fuzzyWordMatches]), intersected across the tokens+     * long enough to have a typo budget. Last resort: it costs a binary search per+     * single-deletion spelling.+     */+    fun collectIndexTypos() {+        val words = tokens.map { it.text }.filter { it.length >= MIN_TYPO_TOKEN_LEN }+        if (words.isEmpty() || words.size != tokens.size) return+        var common: Map<Int, Int>? = null+        for (w in words) {+            if (cancelled()) return+            val hits = m.fuzzyWordMatches(w, PoiIndex.CANDIDATE_CAP)+            common = common?.filterKeys { it in hits } ?: hits+        }+        common.orEmpty().keys.forEach { o -> if (o !in found) add(o, PoiSearch.TIER_FUZZY) }+    }++    /** Add an index candidate whose scanned tokens all matched; checks the rest by name. */+    private fun addIndexed(ordinal: Int, table: HitTable, index: Int) {+        if (ordinal in found) return+        if (unscannedKeys.isNotEmpty() && unscannedKeys.any { !m.nameHasWordPrefix(ordinal, it) }) return+        // Phrase: token t starts word t, for every scanned token.+        val phrase = scanned.all { t -> table.mask(index, t) and (1L shl t) != 0L }+        add(ordinal, if (phrase) PoiSearch.TIER_PREFIX else PoiSearch.TIER_TOKENS)+    }++    private fun add(ordinal: Int, tier: Int) {+        val lat = m.latE7(ordinal)+        val lon = m.lonE7(ordinal)+        found[ordinal] = Candidate(ordinal, lat, lon, m.type(ordinal), tier, distanceKm(lat, lon))+    }++    private fun distanceKm(latE7: Int, lonE7: Int): Double =+        Math.sqrt(PoiIndex.distanceSq(bias.lat, bias.lon, latE7 / E7_PER_DEGREE, lonE7 / E7_PER_DEGREE)) *+            KM_PER_DEGREE++    /** Ordinals filed under the grid cells of the box of half-size [halfKm] around the bias point. */+    private fun forEachOrdinalNear(halfKm: Double, visit: (Int) -> Boolean) {+        val dLat = halfKm / KM_PER_DEGREE+        val dLon = halfKm / (KM_PER_DEGREE * cosLat)+        m.forEachGridOrdinal(+            toE7(bias.lat - dLat), toE7(bias.lat + dLat), toE7(bias.lon - dLon), toE7(bias.lon + dLon), visit,+        )+    }+}++private fun toE7(deg: Double): Int = (deg * E7_PER_DEGREE).toInt()++/** First index in [packed] (ordinal in the high half, ascending) whose ordinal is >= [ordinal]. */+private fun lowerBoundPacked(packed: LongArray, ordinal: Int): Int {+    var lo = 0+    var hi = packed.size+    while (lo < hi) {+        val mid = (lo + hi) ushr 1+        if ((packed[mid] ushr Int.SIZE_BITS) < ordinal) lo = mid + 1 else hi = mid+    }+    return lo+}++private class RankedRow(+    val record: PoiIndex.PoiRecord,+    val rank: Int,+    val exact: Boolean,+    val boost: Double,+    val distKm: Double,+)++/** "Local" for the exact-name tier: ~0.5° (≈55 km) from the centre. */+private const val EXACT_LOCAL_KM = 55.0++/** The pre-planet rank buckets: phrase, every word (or a substring), typo. */+private fun rankOf(tier: Int): Int = when (tier) {+    PoiSearch.TIER_EXACT, PoiSearch.TIER_PREFIX -> 0+    PoiSearch.TIER_TOKENS, PoiSearch.TIER_SUBSTRING, PoiSearch.TIER_CATEGORY -> 1+    else -> 2+}++/**+ * Rank, then decode only the rows that can be returned: the [SHORTLIST] best by (rank,+ * distance) plus the nearest phrase-matching place labels. Within a rank a name that IS+ * the query comes first when it is a place label or local, then the user's signal, then+ * distance.+ */+internal fun rankCandidates(+    m: PoiIndex.Mapped,+    query: String,+    candidates: Collection<Candidate>,+    bias: SearchBias,+): List<PoiIndex.PoiRecord> {+    val byRank = candidates.sortedWith(compareBy<Candidate> { rankOf(it.tier) }.thenBy { it.distKm })+    val places = byRank.filter { it.type == PoiCategories.TYPE_PLACE && rankOf(it.tier) == 0 }.take(PLACE_SHORTLIST)+    val shortlist = (byRank.take(SHORTLIST) + places).distinctBy { it.ordinal }+    val whole = query.trim()+    val out = shortlist.map { c ->+        val record = m.record(c.ordinal)+        val exact = record.name.equals(whole, ignoreCase = true) &&+            (record.type == PoiCategories.TYPE_PLACE || c.distKm <= EXACT_LOCAL_KM)+        RankedRow(record, rankOf(c.tier), exact, boostWeight(bias.boost, record.name), c.distKm)+    }+    return out.sortedWith(+        compareBy<RankedRow> { it.rank }.thenBy { !it.exact }.thenByDescending { it.boost }.thenBy { it.distKm },+    ).take(bias.limit).map { it.record }+}
maps/src/main/java/com/vayunmathur/maps/util/PoiSearchHits.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchHits.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchHits.ktnew file mode 100644index 0000000000..4113d83fc1--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchHits.kt@@ -0,0 +1,91 @@+package com.vayunmathur.maps.util++/**+ * Ordinal -> dense slot table for the name search, with one word-position mask per query+ * token: bit `w` of token `t`'s mask is set when word `w` of the record's name starts with+ * token `t`. Open addressing over primitive arrays, so a table of a few hundred thousand+ * ordinals (a common word's whole range) costs a few MB and no boxing.+ */+internal class HitTable(private val tokenCount: Int, expected: Int) {+    private var slots = IntArray(capacityFor(expected)) { EMPTY }+    private var slotMask = slots.size - 1++    /** Ordinal of each dense index, in insertion order. */+    var ordinals = IntArray(maxOf(expected, MIN_DENSE))+        private set+    private var masks = LongArray(ordinals.size * tokenCount)++    /** Number of distinct ordinals added. */+    var size = 0+        private set++    /** Dense index of [ordinal], or -1. */+    fun indexOf(ordinal: Int): Int {+        var i = mix(ordinal) and slotMask+        var s = slots[i]+        while (s != EMPTY && ordinals[s] != ordinal) {+            i = (i + 1) and slotMask+            s = slots[i]+        }+        return s+    }++    /** Dense index of [ordinal], adding it first when absent. */+    fun add(ordinal: Int): Int {+        if ((size + 1) * 2 > slots.size) rehash(slots.size * 2)+        var i = mix(ordinal) and slotMask+        var s = slots[i]+        while (s != EMPTY && ordinals[s] != ordinal) {+            i = (i + 1) and slotMask+            s = slots[i]+        }+        if (s != EMPTY) return s+        if (size == ordinals.size) growDense()+        ordinals[size] = ordinal+        slots[i] = size+        return size+++    }++    /** Record that word [wordIdx] of entry [index]'s name starts with token [token]. */+    fun mark(index: Int, token: Int, wordIdx: Int) {+        val at = index * tokenCount + token+        masks[at] = masks[at] or wordBit(wordIdx)+    }++    /** Token [token]'s word-position mask for entry [index] (0: the token did not match). */+    fun mask(index: Int, token: Int): Long = masks[index * tokenCount + token]++    private fun growDense() {+        ordinals = ordinals.copyOf(ordinals.size * 2)+        masks = masks.copyOf(ordinals.size * tokenCount)+    }++    private fun rehash(capacity: Int) {+        slots = IntArray(capacity) { EMPTY }+        slotMask = capacity - 1+        for (d in 0 until size) {+            var i = mix(ordinals[d]) and slotMask+            while (slots[i] != EMPTY) i = (i + 1) and slotMask+            slots[i] = d+        }+    }++    private companion object {+        const val EMPTY = -1+        const val MIN_DENSE = 16+        const val MAX_WORD_BIT = 63++        /** Fibonacci hashing: ordinals are dense and clustered, so spread them first. */+        @Suppress("MagicNumber")+        fun mix(x: Int): Int = (x * -0x61c88647).let { it xor (it ushr 16) }++        fun capacityFor(expected: Int): Int {+            var c = MIN_DENSE+            while (c < expected * 2) c = c shl 1+            return c+        }++        /** Word positions past 63 share the top bit: still a match, never a phrase position. */+        fun wordBit(wordIdx: Int): Long = 1L shl minOf(wordIdx, MAX_WORD_BIT)+    }+}