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
//! Geocoding record type and `search_text` builder.
//!
//! [`GeocodingRecord`] is the unified geocoding data model used across all
//! output formats (PostgreSQL COPY, Photon NDJSON, Pelias Elasticsearch).
//! The [`build_search_text`] function builds the BM25-indexed search field.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use geolith::admin::AdminHierarchy;
use geolith::source::input::DataSource;
/// Geocoding layer classification.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GeocodingLayer {
/// Street address (house number + street).
Address,
/// Named venue, POI, or amenity.
Venue,
/// Street or road name.
Street,
/// Locality (city, town, village).
Locality,
/// County or district.
County,
/// Region (state, province).
Region,
/// Country.
Country,
}
impl GeocodingLayer {
/// The name of the layer in the output files: the `.glx` and `pg-copy`
/// `layer` column. These strings are the file format.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Address => "address",
Self::Venue => "venue",
Self::Street => "street",
Self::Locality => "locality",
Self::County => "county",
Self::Region => "region",
Self::Country => "country",
}
}
}
static BAD_POINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Whether a point is a place on Earth: finite, longitude -180..180, latitude
/// -90..90. A NaN or out-of-range point used to be written and filed at the
/// origin by the dedup index.
#[must_use]
pub fn valid_point(lon: f64, lat: f64) -> bool {
lon.is_finite()
&& lat.is_finite()
&& (-180.0..=180.0).contains(&lon)
&& (-90.0..=90.0).contains(&lat)
}
/// Count a record refused for a bad point.
pub fn count_bad_point() {
BAD_POINTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
/// How many records were refused for a bad point in this process.
#[must_use]
pub fn bad_points() -> u64 {
BAD_POINTS.load(std::sync::atomic::Ordering::Relaxed)
}
/// Address-specific fields for geocoding records.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AddressFields {
/// House number.
pub number: Option<String>,
/// Street name.
pub street: Option<String>,
/// Unit / apartment.
pub unit: Option<String>,
/// Postal code.
pub postcode: Option<String>,
/// The city the address names (`addr:city`).
#[serde(default)]
pub city: Option<String>,
}
/// Unified geocoding record for all output formats.
#[derive(Debug, Clone)]
pub struct GeocodingRecord {
/// Feature ID.
pub id: u64,
/// Data source.
pub source: DataSource,
/// Geocoding layer.
pub layer: GeocodingLayer,
/// Primary display name.
pub name: String,
/// BM25-indexed search text (concatenated fields).
pub search_text: String,
/// Centroid longitude (WGS84).
pub lon: f64,
/// Centroid latitude (WGS84).
pub lat: f64,
/// ISO 3166-1 alpha-2 country code.
pub country_code: Option<String>,
/// Resolved admin hierarchy.
pub admin: AdminHierarchy,
/// Address-specific fields (None for non-address features).
pub address: Option<AddressFields>,
/// Multilingual names (language code → name).
pub names: HashMap<String, String>,
/// Other names of the place (OSM `alt_name`, `old_name` and the like),
/// searched like its name.
pub other_names: Vec<String>,
/// Titles of the place's Wikipedia articles that are new names ("Big
/// Ben" for the tower OSM names "Elizabeth Tower"), searched like its
/// names in other languages: past the language mark, so they do not
/// lengthen the scored text.
pub article_names: Vec<String>,
/// Feature importance score [0.0, 1.0].
pub importance: f32,
/// Original source identifier (Overture GERS UUID). Falls back to
/// the numeric `id` in output formats when absent.
pub source_id: Option<String>,
/// Category strings (Overture `basic_category` + taxonomy + categories).
pub categories: Vec<String>,
/// Source-specific extra data (Pelias `addendum` namespaces).
/// Keys are namespace names (e.g. "overture"); values are JSON objects.
pub addendum: HashMap<String, serde_json::Value>,
/// The place's outline, written by `glx::format::encode_shape` (see
/// [`crate::shape`]); empty when the place is a point only.
pub shape: Vec<u8>,
}
/// The fields a new [`GeocodingRecord`] is built from.
#[derive(Debug, Clone)]
pub struct RecordInit {
/// Stable record id.
pub id: u64,
/// Source dataset.
pub source: DataSource,
/// Geocoding layer.
pub layer: GeocodingLayer,
/// Primary display name.
pub name: String,
/// Longitude in degrees.
pub lon: f64,
/// Latitude in degrees.
pub lat: f64,
/// Administrative hierarchy.
pub admin: AdminHierarchy,
/// Street address, when known.
pub address: Option<AddressFields>,
/// Names keyed by language code.
pub names: HashMap<String, String>,
/// Ranking importance in `0.0..=1.0`.
pub importance: f32,
}
impl GeocodingRecord {
/// Create a new geocoding record.
///
/// Automatically builds `search_text` from the provided fields.
#[must_use]
pub fn new(init: RecordInit) -> Self {
let RecordInit {
id,
source,
layer,
name,
lon,
lat,
admin,
address,
names,
importance,
} = init;
let country_code = admin.country_code.clone();
let mut record = Self {
id,
source,
layer,
name,
search_text: String::new(),
lon,
lat,
country_code,
admin,
address,
names,
other_names: Vec::new(),
article_names: Vec::new(),
importance,
source_id: None,
categories: Vec::new(),
addendum: HashMap::new(),
shape: Vec::new(),
};
record.rebuild_search_text();
record
}
/// Every name of the place: its name, its English name when that
/// differs, then its other names.
#[must_use]
pub fn all_names(&self) -> Vec<&str> {
let mut names: Vec<&str> = Vec::with_capacity(2 + self.other_names.len());
if !self.name.is_empty() {
names.push(&self.name);
}
names.extend(english_name(&self.name, &self.names));
names.extend(self.other_names.iter().map(String::as_str));
names
}
/// The place's names and its category words as one text, for the `.glx`
/// name match: "station" weighs like a name word for a station named
/// "東京", as Nominatim's special phrases treat a class word.
#[must_use]
pub fn name_text(&self) -> String {
let mut text = self.all_names().join(" ");
for words in self
.category_words()
.into_iter()
.chain(self.language_names())
.chain(self.article_names.iter().cloned())
.chain(self.synonym_words())
{
if !text.is_empty() {
text.push(' ');
}
text.push_str(&words);
}
text
}
/// The place's names in other languages (OSM `name:*`, Overture
/// `names.common`), in language-code order, each once and none that
/// repeats one of [`Self::all_names`]. Keys that are not language codes
/// (`name:etymology`, `name:pronunciation`) are left out.
#[must_use]
pub fn language_names(&self) -> Vec<String> {
let mut seen: Vec<String> = self.all_names().iter().map(|n| n.to_lowercase()).collect();
let mut languages: Vec<(&String, &String)> = self
.names
.iter()
.filter(|(code, name)| is_language_code(code) && !name.trim().is_empty())
.collect();
languages.sort_unstable_by(|a, b| a.0.cmp(b.0));
let mut out = Vec::with_capacity(languages.len());
for (_, name) in languages {
let name = name.trim();
let folded = name.to_lowercase();
if !seen.contains(&folded) {
seen.push(folded);
out.push(name.to_string());
}
}
out
}
/// The other words the place's names are searched by
/// ([`super::synonyms`]), each once.
pub fn synonym_words(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for name in self.all_names() {
for extra in super::synonyms::synonyms(name) {
if !out.contains(&extra) {
out.push(extra);
}
}
}
out
}
/// The first category with `_` as a space; `None` when there is none.
pub fn category_words(&self) -> Option<String> {
let words = self.categories.first()?.replace('_', " ");
let words = words.trim();
(!words.is_empty()).then(|| words.to_string())
}
/// Shows a country by its English name, as Pelias does by default: a
/// country whose name is in another script ("भारत") takes its English
/// name ("India") and keeps the other as an other name, still
/// searchable. Other places keep their own name.
pub fn prefer_english_name(&mut self) {
if self.layer != GeocodingLayer::Country {
return;
}
let Some(english) = english_name(&self.name, &self.names).map(str::to_owned) else {
return;
};
let local = std::mem::replace(&mut self.name, english);
if !self.other_names.contains(&local) {
self.other_names.insert(0, local);
}
self.rebuild_search_text();
}
/// Build `search_text` again from the names, address, admin and the
/// first category.
///
/// The first category (Overture `basic_category`, or the OSM venue tag
/// value) is searched with `_` as a space, so a place is found by what it
/// is: "tokyo station" finds the station named "東京". Nominatim does this
/// with special phrases and Photon with classification words.
pub fn rebuild_search_text(&mut self) {
self.search_text = build_search_text(&self.all_names(), self.address.as_ref(), &self.admin);
if let Some(words) = self.category_words() {
if !self.search_text.is_empty() {
self.search_text.push(' ');
}
self.search_text.push_str(&words);
}
// The neighbourhood, the borough and the names in other languages
// are searched, but after the language mark, so they do not lengthen
// the scored text (Photon keeps them in fields of their own).
let mut unscored: Vec<String> = [
&self.admin.neighbourhood,
&self.admin.borough,
&self.admin.city,
]
.into_iter()
.flatten()
.filter(|name| !name.is_empty())
.cloned()
.collect();
unscored.extend(self.language_names());
unscored.extend(self.article_names.iter().cloned());
unscored.extend(self.synonym_words());
if !unscored.is_empty() {
self.search_text.push(glx::tokenize::LANGUAGE_MARK);
self.search_text.push_str(&unscored.join(" "));
}
}
/// Set the original source identifier (builder-style).
#[must_use]
pub fn with_source_id(mut self, source_id: impl Into<String>) -> Self {
self.source_id = Some(source_id.into());
self
}
/// Set category strings (builder-style).
#[must_use]
pub fn with_categories(mut self, categories: Vec<String>) -> Self {
self.categories = categories;
self.rebuild_search_text();
self
}
/// Add an addendum namespace (builder-style).
#[must_use]
pub fn with_addendum(mut self, namespace: impl Into<String>, value: serde_json::Value) -> Self {
self.addendum.insert(namespace.into(), value);
self
}
}
/// Whether `code` is a language code as OSM `name:<code>` uses it: two or
/// three lower-case letters, then optional `-` subtags (`zh-Hant`,
/// `sr-Latn`). `etymology` or `pronunciation` are not.
pub fn is_language_code(code: &str) -> bool {
let mut parts = code.split('-');
let primary = parts.next().unwrap_or("");
(2..=3).contains(&primary.len())
&& primary.bytes().all(|b| b.is_ascii_lowercase())
&& parts.all(|tag| {
(2..=8).contains(&tag.len()) && tag.bytes().all(|b| b.is_ascii_alphanumeric())
})
}
/// The English name of a place when it differs from its primary name, so a
/// search in English finds a place named in another language: "Eiffel
/// Tower" for "Tour Eiffel".
#[must_use]
pub fn english_name<'a>(name: &str, names: &'a HashMap<String, String>) -> Option<&'a str> {
names
.get("en")
.map(String::as_str)
.filter(|english| !english.eq_ignore_ascii_case(name))
}
/// Build the BM25-indexed search text for a geocoding record.
///
/// Concatenates: names + street + postcode + locality + county + region +
/// country. Fields are separated by spaces. Empty/None fields are skipped.
#[must_use]
pub fn build_search_text(
names: &[&str],
address: Option<&AddressFields>,
admin: &AdminHierarchy,
) -> String {
let mut parts: Vec<&str> = Vec::with_capacity(names.len() + 6);
parts.extend(names.iter().copied().filter(|name| !name.is_empty()));
if let Some(addr) = address {
if let Some(s) = addr.street.as_deref() {
parts.push(s);
}
if let Some(p) = addr.postcode.as_deref() {
parts.push(p);
}
}
if let Some(l) = admin.locality.as_deref() {
parts.push(l);
}
if let Some(c) = admin.county.as_deref() {
parts.push(c);
}
if let Some(r) = admin.region.as_deref() {
parts.push(r);
}
if let Some(c) = admin.country.as_deref() {
parts.push(c);
}
// The place's own house number and city, as Photon and Nominatim
// search them; after the country so glx derives the rest of the text.
if let Some(addr) = address {
if let Some(n) = addr.number.as_deref() {
parts.push(n);
}
if let Some(city) = addr.city.as_deref()
&& !admin
.locality
.as_deref()
.is_some_and(|locality| locality.eq_ignore_ascii_case(city))
{
parts.push(city);
}
}
parts.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
fn empty_admin() -> AdminHierarchy {
AdminHierarchy::default()
}
fn admin_with_locality(locality: &str, region: &str, country: &str) -> AdminHierarchy {
AdminHierarchy {
country_code: Some("IN".to_string()),
country: Some(country.to_string()),
region: Some(region.to_string()),
county: None,
locality: Some(locality.to_string()),
neighbourhood: None,
borough: None,
postcode: None,
city: None,
}
}
/// A venue is found by its own address, as Photon and Nominatim index
/// a place's `addr:housenumber` and `addr:city`: "Sri Sai Enterprises"
/// at 2A 2nd Main Road answers "2A 2nd Main Road, Bengaluru". The number
/// and a city that differs from the locality go after the country, so
/// glx still derives the text from the record's fields.
#[test]
fn a_venue_is_searched_by_its_house_number_and_city() {
let address = AddressFields {
number: Some("456".into()),
street: Some("Kiwale Road".into()),
city: Some("pune".into()),
..AddressFields::default()
};
let admin = admin_with_locality("Pimpri-Chinchwad", "Maharashtra", "India");
assert_eq!(
build_search_text(&["pqr restraunt"], Some(&address), &admin),
"pqr restraunt Kiwale Road Pimpri-Chinchwad Maharashtra India 456 pune"
);
// A city the locality already names is not repeated.
let admin = admin_with_locality("Pune", "Maharashtra", "India");
assert_eq!(
build_search_text(&["pqr restraunt"], Some(&address), &admin),
"pqr restraunt Kiwale Road Pune Maharashtra India 456"
);
}
/// A place is found by what it is, not only by its name: Tokyo's main
/// station is named "東京" (English "Tokyo"), and a search for "tokyo
/// station" must match it. Like Nominatim's special phrases and Photon's
/// classification words, the category goes into the search text, with
/// `_` as a space. It also ends the name text, so it weighs like a name
/// word: on the planet, hundreds of shops named "Tokyo Station" match
/// both words in their names, and the station must still win on its
/// importance.
#[test]
fn the_category_words_are_searched_like_names() {
use geolith::source::input::{DataSource, OsmElementType};
let names = HashMap::from([("en".to_string(), "Tokyo".to_string())]);
let record = GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
},
layer: GeocodingLayer::Venue,
name: "東京".to_string(),
lon: 139.767,
lat: 35.681,
admin: empty_admin(),
address: None,
names,
importance: 0.5,
})
.with_categories(vec!["train_station".to_string(), "transport".to_string()]);
assert_eq!(record.search_text, "東京 Tokyo train station");
assert_eq!(record.name_text(), "東京 Tokyo train station");
}
/// "collector office Kadapa" finds the Collectorate: a name's synonyms
/// are searched after the language mark, like names in other
/// languages, and weigh as name words.
#[test]
fn a_names_synonyms_are_searched_after_the_mark() {
use geolith::source::input::{DataSource, OsmElementType};
let record = GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
},
layer: GeocodingLayer::Venue,
name: "Collectorate".to_string(),
lon: 78.82,
lat: 14.47,
admin: empty_admin(),
address: None,
names: HashMap::new(),
importance: 0.0,
});
let mark = glx::tokenize::LANGUAGE_MARK;
assert_eq!(
record.search_text,
format!("Collectorate{mark}collector office")
);
assert_eq!(record.name_text(), "Collectorate collector office");
}
/// The place's names in other languages (OSM `name:*`, Overture
/// `names.common`) are searched after the language mark, which keeps them
/// out of the scored length; keys that are not language codes
/// (`name:etymology`, `name:pronunciation`) and repeats of the name are
/// left out, and they count as names.
#[test]
fn names_in_other_languages_are_searched_after_the_language_mark() {
let names = HashMap::from([
("en".to_string(), "Mumbai".to_string()),
("hi".to_string(), "मुंबई".to_string()),
("mr".to_string(), "मुंबई".to_string()),
("ta".to_string(), "மும்பை".to_string()),
("zh-Hant".to_string(), "孟買".to_string()),
("etymology".to_string(), "Mumbadevi".to_string()),
("pronunciation".to_string(), "mum-bai".to_string()),
("de".to_string(), "mumbai".to_string()),
]);
let record = GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Overture {
theme: "places".into(),
otype: "place".into(),
},
layer: GeocodingLayer::Locality,
name: "Mumbai".to_string(),
lon: 72.88,
lat: 19.08,
admin: empty_admin(),
address: None,
names,
importance: 0.5,
});
let mark = glx::tokenize::LANGUAGE_MARK;
assert_eq!(record.search_text, format!("Mumbai{mark}मुंबई மும்பை 孟買"));
assert_eq!(record.name_text(), "Mumbai मुंबई மும்பை 孟買");
}
/// The city around the place's ward is searched past the language mark
/// with its neighbourhood: "Swensen's, Bengaluru" finds the shop whose
/// locality is the ward Chikka Devasandra.
#[test]
fn the_city_around_the_ward_is_searched_with_the_neighbourhood() {
let admin = AdminHierarchy {
locality: Some("Chikka Devasandra".into()),
neighbourhood: Some("ITI Layout".into()),
city: Some("Bengaluru".into()),
..empty_admin()
};
let record = GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Overture {
theme: "places".into(),
otype: "place".into(),
},
layer: GeocodingLayer::Venue,
name: "Swensen's".to_string(),
lon: 77.7,
lat: 12.99,
admin,
address: None,
names: HashMap::new(),
importance: 0.0,
});
let mark = glx::tokenize::LANGUAGE_MARK;
assert_eq!(
record.search_text,
format!("Swensen's Chikka Devasandra{mark}ITI Layout Bengaluru")
);
}
#[test]
fn search_text_with_address() {
let addr = AddressFields {
number: Some("1".to_string()),
street: Some("Main Street".to_string()),
unit: None,
postcode: Some("110001".to_string()),
city: None,
};
let text = build_search_text(&["Shop"], Some(&addr), &empty_admin());
assert!(text.contains("Main Street"), "should contain street");
assert!(text.contains("110001"), "should contain postcode");
assert!(text.starts_with("Shop"), "should start with name");
}
#[test]
fn search_text_with_admin() {
let admin = admin_with_locality("Delhi", "Delhi NCT", "India");
let text = build_search_text(&["Red Fort"], None, &admin);
assert!(text.contains("Red Fort"));
assert!(text.contains("Delhi"));
assert!(text.contains("India"));
}
#[test]
fn search_text_full() {
let addr = AddressFields {
number: Some("1".to_string()),
street: Some("Rajpath".to_string()),
unit: None,
postcode: Some("110001".to_string()),
city: None,
};
let admin = admin_with_locality("New Delhi", "Delhi NCT", "India");
let text = build_search_text(&["India Gate"], Some(&addr), &admin);
assert!(text.contains("India Gate"));
assert!(text.contains("Rajpath"));
assert!(text.contains("110001"));
assert!(text.contains("New Delhi"));
assert!(text.contains("India"));
}
#[test]
fn the_english_name_follows_the_primary_name() {
let admin = admin_with_locality("Paris", "Ile-de-France", "France");
let text = build_search_text(&["Tour Eiffel", "Eiffel Tower"], None, &admin);
assert_eq!(text, "Tour Eiffel Eiffel Tower Paris Ile-de-France France");
// A lone name stands alone, and an empty one adds nothing.
assert_eq!(
build_search_text(&["Taj Mahal"], None, &empty_admin()),
"Taj Mahal"
);
assert_eq!(build_search_text(&[""], None, &empty_admin()), "");
}
#[test]
fn an_english_name_like_the_primary_name_is_left_out() {
let names = |en: &str| HashMap::from([("en".to_string(), en.to_string())]);
let tower = names("Eiffel Tower");
assert_eq!(english_name("Tour Eiffel", &tower), Some("Eiffel Tower"));
assert_eq!(english_name("London", &names("london")), None);
assert_eq!(english_name("London", &HashMap::new()), None);
}
#[test]
fn geocoding_record_new_sets_search_text() {
use geolith::source::input::{DataSource, OsmElementType};
let admin = admin_with_locality("Mumbai", "Maharashtra", "India");
let record = GeocodingRecord::new(RecordInit {
id: 42,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: vec![],
},
layer: GeocodingLayer::Venue,
name: "Gateway of India".to_string(),
lon: 72.8347,
lat: 18.9220,
admin,
address: None,
names: HashMap::new(),
importance: 0.9,
});
assert!(record.search_text.contains("Gateway of India"));
assert!(record.search_text.contains("Mumbai"));
assert_eq!(record.country_code.as_deref(), Some("IN"));
}
/// India's Overture division point is named "भारत" with the English name
/// "India": it shows as India and is found by both names. A region keeps
/// its own name.
#[test]
fn a_country_shows_its_english_name() {
let names = HashMap::from([("en".to_string(), "India".to_string())]);
let mut country = GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Overture {
theme: "divisions".into(),
otype: "division".into(),
},
layer: GeocodingLayer::Country,
name: "भारत".into(),
lon: 78.0,
lat: 21.0,
admin: AdminHierarchy::default(),
address: None,
names: names.clone(),
importance: 0.9,
});
country.prefer_english_name();
assert_eq!(country.name, "India");
assert_eq!(country.other_names, ["भारत"]);
assert!(
country.search_text.starts_with("India भारत"),
"{}",
country.search_text
);
let mut region = GeocodingRecord::new(RecordInit {
id: 2,
source: DataSource::Overture {
theme: "divisions".into(),
otype: "division".into(),
},
layer: GeocodingLayer::Region,
name: "महाराष्ट्र".into(),
lon: 75.0,
lat: 19.0,
admin: AdminHierarchy::default(),
address: None,
names,
importance: 0.7,
});
region.prefer_english_name();
assert_eq!(region.name, "महाराष्ट्र");
}
/// The layer names of the `.glx` and `pg-copy` rows were
/// `format!("{:?}")` lowercased: renaming a variant would have changed
/// the file format with no compile error. The strings are the format and
/// are written out here.
#[test]
fn the_layer_strings_are_the_file_format() {
let all = [
(GeocodingLayer::Address, "address"),
(GeocodingLayer::Venue, "venue"),
(GeocodingLayer::Street, "street"),
(GeocodingLayer::Locality, "locality"),
(GeocodingLayer::County, "county"),
(GeocodingLayer::Region, "region"),
(GeocodingLayer::Country, "country"),
];
for (layer, text) in all {
assert_eq!(layer.as_str(), text);
}
}
#[test]
fn a_valid_point_is_finite_and_on_earth() {
assert!(valid_point(0.0, 0.0));
assert!(valid_point(-180.0, -90.0));
assert!(valid_point(180.0, 90.0));
assert!(!valid_point(180.0001, 0.0));
assert!(!valid_point(0.0, 90.0001));
assert!(!valid_point(f64::NAN, 0.0));
assert!(!valid_point(0.0, f64::NEG_INFINITY));
}
}