gridpin 0.10.0

Offline geocoder: addresses to coordinates from a country sheet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Rules-in-data: curated tables (commune/city aliases, abbreviations, street-type
//! words, capital anchors, stop lists) can be embedded in the data file
//! (SEC_RULES section); the constants below are the built-in defaults used when
//! a file carries no rules. Updating a rule means rebuilding the data, not
//! releasing a new engine. When both exist, the section wins.
//!
//! Rules belong to the data file that carries them, not to the process: opening
//! two files built from different rule tables (say a current sheet and an older
//! one) must not make either answer with the other's rules. Each index therefore
//! owns its rule set and makes it current for the thread while it serves a query.

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::OnceLock;

// section entry classes (u8) and their TSV file names
pub const CLASSES: &[(u8, &str)] = &[
    (26, "municipality_guard"), // optional municipality/region vocabulary
    (23, "city_tail"),          // optional tail grammar and exact-city guard
    (27, "commune_regions"), // optional city -> "REGION lat lon;…" (homonyms held by the tail's region)
    (28, "known_houses"), // optional "street|commune" -> house numbers an Overture place stands at (prep/known_houses.py)
    (29, "unfolded_words"), // optional query word written without "ł" -> the sheet's word (prep/unfolded_words.py)
    (1, "commune_alias"),   // key → value
    (2, "city_alias"),      // key → value
    (3, "abbrev2"),         // key="a b" → full word
    (4, "capitals"),        // list
    (5, "street_types_cyr"), // list (type padding/rotation — Cyrillic)
    (16, "street_types_latin"), // list (type padding — Latin)
    (17, "street_types_extra"), // list (type recognition only: nl/rs/uz…)
    (6, "affix_extra"),     // list
    (7, "noise"),           // list
    (8, "noise_after"),     // list
    (9, "region_markers"),  // list
    (10, "countries_mid"),  // list
    (11, "countries_tail"), // list
    (12, "place_junk"),     // list
    (13, "place_prefix"),   // list
    (14, "fr_ord_cities"),  // list
    (15, "place_type_strip"), // list
];

pub struct Rules {
    pub municipality_guard: HashMap<String, String>,
    pub city_tail: HashMap<String, String>,
    /// Normalized city name -> "REGION lat lon;REGION lat lon…": where a city of that name lies in
    /// each region, so a tail naming the region can hold its homonyms (US, 21.10.2026).
    pub commune_regions: HashMap<String, String>,
    /// Normalized "street|commune" -> the house numbers an Overture place stands at, space-separated: a cityless
    /// homonym with a known house goes first (Poland, 14.11.2026; prep/known_houses.py). Older engines skip class 28.
    pub known_houses: HashMap<String, String>,
    /// The same table by street: normalized street -> its known houses, for a cityless query whose known house lies
    /// in another commune than its top answer.
    pub known_by_street: HashMap<String, Vec<KnownHouse>>,
    /// A query word written without a letter normalization does not fold ("lodz") -> the sheet's word ("łodz"); read
    /// before the query is parsed (Poland, 14.11.2026; prep/unfolded_words.py). Older engines skip class 29.
    pub unfolded_words: HashMap<String, String>,
    pub recipient_prefixes: HashSet<String>,
    pub commune_alias: HashMap<String, String>,
    pub city_alias: Vec<(String, String)>,
    pub street_rewrites: Vec<(String, String)>, // street keys only
    pub abbrev2: Vec<(String, String)>,         // ("a b", "full")
    pub capitals: Vec<String>,
    pub types_cyr: Vec<String>,
    pub types_latin: Vec<String>,
    pub types_extra: HashSet<String>,
    pub affix_extra: HashSet<String>,
    pub noise: HashSet<String>,
    pub noise_after: HashSet<String>,
    pub region_markers: HashSet<String>,
    pub countries_mid: HashSet<String>,
    pub countries_tail: HashSet<String>,
    pub place_junk: HashSet<String>,
    pub place_prefix: HashSet<String>,
    pub fr_ord_cities: HashSet<String>,
    pub place_type_strip: HashSet<String>,
    pub de_city_alias: Vec<(String, String)>,
    pub de_abbrev2: Vec<(String, String)>,
    pub de_street_types: Vec<String>,
    pub de_countries: HashSet<String>,
    pub de_admin_tail: HashSet<String>,
}

impl Rules {
    pub fn is_street_type(&self, w: &str) -> bool {
        self.types_extra.contains(w)
            || self.types_cyr.iter().any(|t| t == w)
            || self.types_latin.iter().any(|t| t == w)
    }
    pub fn is_affix(&self, w: &str) -> bool {
        self.is_street_type(w) || self.affix_extra.contains(w)
    }
    pub fn commune_alias(&self, name: &str) -> Option<&str> {
        self.commune_alias.get(name).map(|s| s.as_str())
    }

    fn add(&mut self, class: u8, key: String, val: String) {
        match class {
            26 => {
                self.municipality_guard.insert(key, val);
            }
            25 => {
                self.recipient_prefixes.insert(key);
            }
            23 => {
                self.city_tail.insert(key, val);
            }
            27 => {
                self.commune_regions.insert(key, val);
            }
            28 => {
                if let Some((street, commune)) = key.split_once('|') {
                    // by the street and by each of its endings ("aleje jerozolimskie" -> also "jerozolimskie";
                    // "legionów józefa piłsudskiego" -> also "józefa piłsudskiego", "piłsudskiego"): a query loses
                    // the type word to the type rules and often writes the surname alone. An ending is taken when its
                    // last word is longer than three letters.
                    let words: Vec<&str> = street.split(' ').collect();
                    let endings = (1..words.len())
                        .map(|i| words[i..].join(" "))
                        .filter(|e| e.rsplit(' ').next().is_some_and(|w| w.chars().count() > 3));
                    let mut names: Vec<String> = vec![street.to_string()];
                    names.extend(endings);
                    for name in &names {
                        let houses = self.known_by_street.entry(name.clone()).or_default();
                        for item in val.split(' ').filter(|v| !v.is_empty()) {
                            let (number, places, notable, near) = known_item(item);
                            houses.push(KnownHouse {
                                commune: commune.to_string(),
                                number: number.to_string(),
                                places,
                                notable,
                                near,
                            });
                        }
                    }
                }
                self.known_houses.insert(key, val);
            }
            29 => {
                self.unfolded_words.insert(key, val);
            }
            1 => {
                self.commune_alias.insert(key, val);
            }
            2 => self.city_alias.push((key, val)),
            24 => self.street_rewrites.push((key, val)),
            3 => self.abbrev2.push((key, val)),
            4 => self.capitals.push(key),
            5 => self.types_cyr.push(key),
            16 => self.types_latin.push(key),
            17 => {
                self.types_extra.insert(key);
            }
            6 => {
                self.affix_extra.insert(key);
            }
            7 => {
                self.noise.insert(key);
            }
            8 => {
                self.noise_after.insert(key);
            }
            9 => {
                self.region_markers.insert(key);
            }
            10 => {
                self.countries_mid.insert(key);
            }
            11 => {
                self.countries_tail.insert(key);
            }
            12 => {
                self.place_junk.insert(key);
            }
            13 => {
                self.place_prefix.insert(key);
            }
            14 => {
                self.fr_ord_cities.insert(key);
            }
            15 => {
                self.place_type_strip.insert(key);
            }
            18 => self.de_city_alias.push((key, val)),
            19 => self.de_abbrev2.push((key, val)),
            20 => self.de_street_types.push(key),
            21 => {
                self.de_countries.insert(key);
            }
            22 => {
                self.de_admin_tail.insert(key);
            }
            _ => {}
        }
    }
}

// ===== built-in defaults (fallback used when no index carries a SEC_RULES section) =====

const D_COMMUNE_ALIAS: &[(&str, &str)] = &[
    ("den haag", "s gravenhage"),
    ("den bosch", "s hertogenbosch"),
    ("reggio emilia", "reggio nell emilia"),
];

const D_CITY_ALIASES: &[(&str, &str)] = &[
    ("спб", "санкт петербург"),
    ("мск", "москва"),
    ("екб", "екатеринбург"),
    ("нск", "новосибирск"),
    ("питер", "санкт петербург"),
    ("bg", "beograd"),
    ("ns", "novi sad"),
    ("amsterdam zo", "amsterdam"),
    ("moscow", "москва"),
    ("saint petersburg", "санкт петербург"),
    ("st petersburg", "санкт петербург"),
    ("rome", "roma"),
    ("milan", "milano"),
    ("naples", "napoli"),
    ("turin", "torino"),
    ("florence", "firenze"),
    ("venice", "venezia"),
    ("genoa", "genova"),
    ("padua", "padova"),
];

const D_ABBREV2: &[(&str, &str)] = &[
    ("p zza", "piazza"),
    ("c so", "corso"),
    ("v le", "viale"),
    ("пр кт", "проспект"),
    ("б р", "бульвар"),
    ("пр т", "проспект"),
];

const D_CAPITALS: &[&str] = &[
    "москва",
    "paris",
    "roma",
    "amsterdam",
    "beograd",
    "toshkent",
    "ташкент",
    "s gravenhage",
    "санкт петербург",
];

const D_TYPES_CYR: &[&str] = &[
    "улица",
    "проспект",
    "переулок",
    "набережная",
    "шоссе",
    "бульвар",
    "площадь",
    "проезд",
    "аллея",
    "тупик",
    "квартал",
    "микрорайон",
];
const D_TYPES_LATIN: &[&str] = &[
    // fr
    "rue",
    "avenue",
    "boulevard",
    "place",
    "impasse",
    "allee",
    "chemin",
    "route",
    "cours",
    "quai",
    "passage",
    "square",
    // it
    "via",
    "viale",
    "corso",
    "piazza",
    "largo",
    "vicolo",
    "strada",
];
const D_TYPES_EXTRA: &[&str] = &[
    // nl
    "straat",
    "laan",
    "weg",
    "plein",
    "gracht",
    "dijk",
    "kade",
    "steeg",
    "singel",
    "hof",
    // rs
    "ulica",
    "bulevar",
    "trg",
    "put",
    // uz (apostrophe removed by normalization: ko'chasi→kochasi)
    "kochasi",
    "kocha",
    "kuchasi",
    "mavze",
    "mavzesi",
    "dahasi",
    "daha",
    "prospekti",
    // it extras
    "piazzale",
    "salita",
];

const D_AFFIX_EXTRA: &[&str] = &[
    "массив",
    "massiv",
    "мкр",
    "микрорайон",
    "квартал",
    "kvartal",
    "жилой",
    "residential",
    "комплекс",
    "complex",
    "жк",
];

const D_NOISE: &[&str] = &["г", "гор", "город", "gorod", "shahri", "sh"];
const D_NOISE_AFTER: &[&str] = &["город", "grad", "sh"];

const D_REGION_MARKERS: &[&str] = &[
    "обл",
    "область",
    "области",
    "край",
    "края",
    "респ",
    "республика",
    "район",
    "района",
    "р н",
    "tumani",
    "tuman",
    "viloyat",
    "viloyati",
];

const D_COUNTRIES_MID: &[&str] = &[
    "france",
    "francia",
    "frankrijk",
    "франция",
    "italia",
    "italy",
    "italie",
    "италия",
    "srbija",
    "serbia",
    "сербия",
    "србија",
    "россия",
    "russia",
    "рф",
    "узбекистан",
    "uzbekistan",
    "ozbekiston",
    "nederland",
    "netherlands",
    "holland",
    "нидерланды",
];

const D_COUNTRIES_TAIL: &[&str] = &[
    "france",
    "francia",
    "франция",
    "nederland",
    "netherlands",
    "holland",
    "нидерланды",
    "italia",
    "italy",
    "italie",
    "италия",
    "srbija",
    "serbia",
    "сербия",
    "србија",
    "россия",
    "russia",
    "рф",
    "федерация",
    "российская",
    "uzbekistan",
    "узбекистан",
    "ozbekiston",
    "europe",
    "европа",
];

const D_PLACE_JUNK: &[&str] = &[
    "территория",
    "тер",
    "муниципальный",
    "округ",
    "поселение",
    "городской",
    "деревня",
    "дер",
    "село",
    "поселок",
    "пос",
    "рп",
    "пгт",
    "аул",
    "кишлак",
];

const D_PLACE_PREFIX: &[&str] = &[
    "снт",
    "днп",
    "тсн",
    "сдт",
    "ст",
    "садовое",
    "дачное",
    "некоммерческое",
    "товарищество",
    "массив",
    "микрорайон",
    "мкр",
    "квартал",
    "город",
    "обл",
    "область",
    "край",
    "район",
];

const D_FR_ORD_CITIES: &[&str] = &["paris", "lyon", "marseille"];

const D_PLACE_TYPE_STRIP: &[&str] = &[
    "квартал",
    "kvartal",
    "mavze",
    "mavzesi",
    "даха",
    "daha",
    "dahasi",
    "массив",
    "massiv",
    "мкр",
    "микрорайон",
];

fn defaults() -> Rules {
    let mut r = Rules {
        municipality_guard: HashMap::new(),
        city_tail: HashMap::new(),
        commune_regions: HashMap::new(),
        known_houses: HashMap::new(),
        known_by_street: HashMap::new(),
        unfolded_words: HashMap::new(),
        recipient_prefixes: HashSet::new(),
        commune_alias: HashMap::new(),
        city_alias: Vec::new(),
        street_rewrites: Vec::new(),
        abbrev2: Vec::new(),
        capitals: Vec::new(),
        types_cyr: Vec::new(),
        types_latin: Vec::new(),
        types_extra: HashSet::new(),
        affix_extra: HashSet::new(),
        noise: HashSet::new(),
        noise_after: HashSet::new(),
        region_markers: HashSet::new(),
        countries_mid: HashSet::new(),
        countries_tail: HashSet::new(),
        place_junk: HashSet::new(),
        place_prefix: HashSet::new(),
        fr_ord_cities: HashSet::new(),
        place_type_strip: HashSet::new(),
        de_city_alias: Vec::new(),
        de_abbrev2: Vec::new(),
        de_street_types: Vec::new(),
        de_countries: HashSet::new(),
        de_admin_tail: HashSet::new(),
    };
    for (k, v) in D_COMMUNE_ALIAS {
        r.add(1, k.to_string(), v.to_string());
    }
    for (k, v) in D_CITY_ALIASES {
        r.add(2, k.to_string(), v.to_string());
    }
    for (k, v) in D_ABBREV2 {
        r.add(3, k.to_string(), v.to_string());
    }
    let lists: &[(u8, &[&str])] = &[
        (4, D_CAPITALS),
        (5, D_TYPES_CYR),
        (16, D_TYPES_LATIN),
        (17, D_TYPES_EXTRA),
        (6, D_AFFIX_EXTRA),
        (7, D_NOISE),
        (8, D_NOISE_AFTER),
        (9, D_REGION_MARKERS),
        (10, D_COUNTRIES_MID),
        (11, D_COUNTRIES_TAIL),
        (12, D_PLACE_JUNK),
        (13, D_PLACE_PREFIX),
        (14, D_FR_ORD_CITIES),
        (15, D_PLACE_TYPE_STRIP),
    ];
    for (class, words) in lists {
        for w in *words {
            r.add(*class, w.to_string(), String::new());
        }
    }
    r
}

static FALLBACK: OnceLock<Rules> = OnceLock::new();

thread_local! {
    /// The rule set serving the query currently running on this thread.
    static CURRENT: Cell<Option<&'static Rules>> = const { Cell::new(None) };
}

/// Built-in defaults, used by files that carry no rule section.
pub fn defaults_static() -> &'static Rules {
    FALLBACK.get_or_init(defaults)
}

/// Restores the previously current rule set when dropped.
pub struct Scope(Option<&'static Rules>);

impl Drop for Scope {
    fn drop(&mut self) {
        CURRENT.with(|c| c.set(self.0));
    }
}

/// Make `r` the current rule set for this thread until the guard is dropped.
/// Nested scopes (a cascade querying a second index) restore correctly.
#[must_use]
pub fn scope(r: &'static Rules) -> Scope {
    CURRENT.with(|c| Scope(c.replace(Some(r))))
}

/// Rules serving the running query: the current index's own set, else the defaults.
pub fn rules() -> &'static Rules {
    CURRENT.with(|c| c.get()).unwrap_or_else(defaults_static)
}

/// The rule set carried by one index section. A file whose section is absent, empty or
/// truncated falls back to the built-in defaults rather than to a partial rule set.
/// The returned reference lives as long as the process, like the index's mapping.
/// A known house of a street (rules class 28): its commune, its number, the Overture places at its address, those
/// of a notable kind, and the notable places within 50 m whatever their address (prep/known_houses.py).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KnownHouse {
    pub commune: String,
    pub number: String,
    pub places: u32,
    pub notable: u32,
    pub near: u32,
}

/// One house of a `known_houses` value: "<number>:<places>:<notable>:<near>" (prep/known_houses.py; near: the notable
/// places within 50 m whatever their address). An older table wrote fewer counts: the missing ones are one place and
/// no notable one.
pub fn known_item(item: &str) -> (&str, u32, u32, u32) {
    let mut parts = item.split(':');
    let number = parts.next().unwrap_or(item);
    let places = parts.next().and_then(|p| p.parse().ok()).unwrap_or(1);
    let notable = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
    let near = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
    (number, places, notable, near)
}

pub fn from_section(bytes: &[u8]) -> &'static Rules {
    if bytes.len() < 4 {
        return defaults_static();
    }
    let declared = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
    let entries = parse_entries(bytes);
    if entries.len() != declared || entries.is_empty() {
        return defaults_static();
    }
    Box::leak(Box::new(rules_from_entries(entries)))
}

/// Like `from_section`, but returns an OWNED `Box<Rules>` (or None for no/invalid section) instead
/// of leaking, so the caller can store it in the Index and free it on Drop.
pub fn from_section_owned(bytes: &[u8]) -> Option<Box<Rules>> {
    if bytes.len() < 4 {
        return None;
    }
    let declared = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
    let entries = parse_entries(bytes);
    if entries.len() != declared || entries.is_empty() {
        return None;
    }
    Some(Box::new(rules_from_entries(entries)))
}

/// Parse raw section entries (used by the watermark verifier).
pub fn parse_entries(bytes: &[u8]) -> Vec<(u8, String, String)> {
    let mut out = Vec::new();
    if bytes.len() < 4 {
        return out;
    }
    let n = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
    let mut p = 4usize;
    for _ in 0..n {
        if p + 3 > bytes.len() {
            return out;
        }
        let class = bytes[p];
        let kl = u16::from_le_bytes(bytes[p + 1..p + 3].try_into().unwrap()) as usize;
        p += 3;
        if p + kl + 2 > bytes.len() {
            return out;
        }
        let key = String::from_utf8_lossy(&bytes[p..p + kl]).into_owned();
        p += kl;
        let vl = u16::from_le_bytes(bytes[p..p + 2].try_into().unwrap()) as usize;
        p += 2;
        if p + vl > bytes.len() {
            return out;
        }
        out.push((
            class,
            key,
            String::from_utf8_lossy(&bytes[p..p + vl]).into_owned(),
        ));
        p += vl;
    }
    out
}

/// Build the active rule set from raw entries: defaults extended by the entries, applied
/// in canonical (sorted) order so the result never depends on the order they arrive in.
/// Some classes are applied as ordered lists (alias and abbreviation rewrites are
/// sequential), so sorting keeps any two sheets carrying the same rule set behaving
/// identically, whatever order the entries were written in.
fn rules_from_entries(mut entries: Vec<(u8, String, String)>) -> Rules {
    entries.sort();
    let mut r = defaults(); // the section EXTENDS the defaults (key/value pairs override by key)
    for (class, key, val) in entries {
        r.add(class, key, val);
    }
    r
}

/// Serialize entries for the builder: u32 n, then (class u8, klen u16, key, vlen u16, val)*.
pub fn serialize_entries(entries: &[(u8, String, String)]) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
    for (class, key, val) in entries {
        out.push(*class);
        let kb = key.as_bytes();
        let vb = val.as_bytes();
        out.extend_from_slice(&(kb.len().min(65535) as u16).to_le_bytes());
        out.extend_from_slice(&kb[..kb.len().min(65535)]);
        out.extend_from_slice(&(vb.len().min(65535) as u16).to_le_bytes());
        out.extend_from_slice(&vb[..vb.len().min(65535)]);
    }
    out
}

/// Read rule TSV files from a directory (builder input): file name maps to class,
/// columns are tab-separated. For the 3-column abbrev2.tsv the key is "a b"
/// (first two columns joined by a space).
pub fn entries_from_tsv_dir(dir: &Path) -> std::io::Result<Vec<(u8, String, String)>> {
    let mut out = Vec::new();
    for (class, name) in CLASSES {
        let p = dir.join(format!("{name}.tsv"));
        if !p.exists() {
            continue;
        }
        for line in std::fs::read_to_string(&p)?.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let cols: Vec<&str> = line.split('\t').collect();
            let (actual_class, key, val) = match (*name, cols.as_slice()) {
                // Country-scoped rows live beside their generic rule family,
                // but are encoded into dedicated classes so they can never
                // affect an index whose metadata is not country=de.
                ("city_alias", ["de", key, val, ..]) => {
                    (18, (*key).to_string(), (*val).to_string())
                }
                ("abbrev2", ["de", a, b, val, ..]) => (19, format!("{a} {b}"), (*val).to_string()),
                ("street_types_latin", ["de", key, ..]) => (20, (*key).to_string(), String::new()),
                ("countries_mid" | "countries_tail", ["de", key, ..]) => {
                    (21, (*key).to_string(), String::new())
                }
                ("place_prefix" | "place_type_strip", ["de", key, ..]) => {
                    (22, (*key).to_string(), String::new())
                }
                ("abbrev2", ["street", key, val]) => (24, (*key).to_string(), (*val).to_string()),
                ("abbrev2", ["recipient", key, "1"]) => (25, (*key).to_string(), String::new()),
                ("abbrev2", [a, b, val, ..]) => (*class, format!("{a} {b}"), (*val).to_string()),
                (_, [key, val, ..]) => (*class, (*key).to_string(), (*val).to_string()),
                (_, [key]) => (*class, (*key).to_string(), String::new()),
                _ => continue,
            };
            out.push((actual_class, key, val));
        }
    }
    Ok(out)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    // Explicit witness inputs, not the private release tables.
    pub(crate) fn write_fixture_rules(dir: &Path) -> std::path::PathBuf {
        std::fs::create_dir_all(dir).unwrap();
        for (name, rows) in [
            (
                "city_alias.tsv",
                "de\tmunich\tmunchen\nde\tcologne\tkoln\nde\tnuremberg\tnurnberg\nde\tfrankfurt main\tfrankfurt am main\n",
            ),
            (
                "abbrev2.tsv",
                "de\ta\tm\tam main\nde\ta\td\tan der\nde\ta\trh\tam rhein\nde\ti\tbay\tin bayern\n",
            ),
            (
                "street_types_latin.tsv",
                "de\tstraße\nde\tstrasse\nde\tstr\nde\tweg\nde\tallee\nde\tplatz\nde\tgasse\nde\tdamm\nde\tufer\n",
            ),
            ("countries_mid.tsv", "de\tdeutschland\nde\tgermany\n"),
            ("countries_tail.tsv", "de\tdeutschland\nde\tgermany\n"),
            ("place_prefix.tsv", "de\tot\nde\tortsteil\n"),
            ("place_type_strip.tsv", "de\tot\nde\tortsteil\n"),
        ] {
            std::fs::write(dir.join(name), rows).unwrap();
        }
        dir.to_path_buf()
    }

    fn sample_entries() -> Vec<(u8, String, String)> {
        let s = |x: &str| x.to_string();
        vec![
            (2, s("spb"), s("sankt peterburg")),
            (2, s("bg"), s("beograd")),
            (3, s("p zza"), s("piazza")),
            (3, s("c so"), s("corso")),
            (4, s("paris"), String::new()),
            (4, s("roma"), String::new()),
            (5, s("ulica"), String::new()),
            (16, s("rue"), String::new()),
            (17, s("straat"), String::new()),
            (18, s("munich"), s("munchen")),
            (19, s("a m"), s("am main")),
            (20, s("straße"), String::new()),
            (21, s("germany"), String::new()),
            (22, s("ortsteil"), String::new()),
        ]
    }

    /// SEC_RULES entries can reach the engine in any order: the section is written by
    /// several producers and its on-disk order is not part of the format contract. Alias
    /// and abbreviation rewrites are applied as ordered lists, so the INSTALLED rule set
    /// must not depend on arrival order — otherwise two sheets carrying the same rules
    /// could answer differently.
    #[test]
    fn rule_install_does_not_depend_on_entry_arrival_order() {
        let base = rules_from_entries(sample_entries());
        for rotate in 1..sample_entries().len() {
            let mut permuted = sample_entries();
            permuted.rotate_left(rotate);
            let other = rules_from_entries(permuted);
            assert_eq!(
                base.city_alias, other.city_alias,
                "city_alias order leaked (rotate {rotate})"
            );
            assert_eq!(
                base.abbrev2, other.abbrev2,
                "abbrev2 order leaked (rotate {rotate})"
            );
            assert_eq!(
                base.capitals, other.capitals,
                "capitals order leaked (rotate {rotate})"
            );
            assert_eq!(
                base.types_cyr, other.types_cyr,
                "types_cyr order leaked (rotate {rotate})"
            );
            assert_eq!(
                base.types_latin, other.types_latin,
                "types_latin order leaked (rotate {rotate})"
            );
            assert_eq!(base.de_city_alias, other.de_city_alias);
            assert_eq!(base.de_abbrev2, other.de_abbrev2);
            assert_eq!(base.de_street_types, other.de_street_types);
        }
        let mut reversed = sample_entries();
        reversed.reverse();
        let other = rules_from_entries(reversed);
        assert_eq!(base.city_alias, other.city_alias);
        assert_eq!(base.abbrev2, other.abbrev2);
        assert_eq!(base.de_city_alias, other.de_city_alias);
        assert_eq!(base.de_abbrev2, other.de_abbrev2);
    }

    #[test]
    fn country_scoped_de_rows_never_enter_generic_rule_families() {
        let dir = write_fixture_rules(&std::env::temp_dir().join(format!(
            "gridpin-de-rule-family-fixture-{}",
            std::process::id()
        )));
        let _scratch = crate::scratch::Scratch::keep(&dir);
        let entries = entries_from_tsv_dir(&dir).unwrap();
        let rules = rules_from_entries(entries);

        assert!(rules
            .de_city_alias
            .contains(&("munich".to_string(), "munchen".to_string())));
        assert!(rules
            .de_abbrev2
            .contains(&("a m".to_string(), "am main".to_string())));
        assert!(rules.de_street_types.iter().any(|value| value == "straße"));
        assert!(rules.de_countries.contains("germany"));
        assert!(rules.de_admin_tail.contains("ortsteil"));

        assert!(!rules.city_alias.iter().any(|(key, _)| key == "munich"));
        assert!(!rules.abbrev2.iter().any(|(key, _)| key == "a m"));
        assert!(!rules.types_latin.iter().any(|value| value == "straße"));
        assert!(!rules.countries_mid.contains("germany"));
        assert!(!rules.countries_tail.contains("germany"));
        assert!(!rules.place_prefix.contains("ortsteil"));
        assert!(!rules.place_type_strip.contains("ortsteil"));
    }

    /// A truncated or corrupt section must never install a partial rule set.
    #[test]
    fn corrupt_section_installs_nothing() {
        let good = serialize_entries(&sample_entries());
        for cut in [1usize, 5, 9, good.len() - 1] {
            let truncated = &good[..cut.min(good.len())];
            let parsed = parse_entries(truncated);
            assert!(
                parsed.len() < sample_entries().len(),
                "truncation at {cut} parsed too much"
            );
        }
    }
}