use std::io::Write;
use crate::record::{GeocodingLayer, GeocodingRecord};
pub struct PhotonWriter<W: Write> {
writer: W,
count: u64,
}
impl<W: Write> PhotonWriter<W> {
pub const fn new(writer: W) -> Self {
Self { writer, count: 0 }
}
pub fn write_record(&mut self, record: &GeocodingRecord) -> std::io::Result<()> {
let feature = record_to_photon_json(record);
writeln!(self.writer, "{feature}")?;
self.count += 1;
Ok(())
}
#[must_use]
pub const fn count(&self) -> u64 {
self.count
}
pub fn flush(&mut self) -> std::io::Result<()> {
self.writer.flush()
}
}
#[must_use]
pub fn record_to_photon_json(record: &GeocodingRecord) -> String {
let (osm_type, osm_id) = match &record.source {
geolith::source::input::DataSource::Osm { element_type, .. } => {
use geolith::source::input::OsmElementType;
let letter = match element_type {
OsmElementType::Node => "N",
OsmElementType::Way => "W",
OsmElementType::Relation => "R",
};
(letter, crate::osm::element_id(record.id))
}
_ => ("N", record.id),
};
let layer_str = layer_to_photon_type(record.layer);
let mut props = Vec::with_capacity(16);
props.push(format!("\"osm_type\":\"{}\"", osm_type));
props.push(format!("\"osm_id\":{osm_id}"));
props.push(format!("\"type\":\"{}\"", layer_str));
props.push(format!("\"name\":\"{}\"", json_str(&record.name)));
if let Some(cc) = record.country_code.as_deref() {
props.push(format!("\"country_code\":\"{}\"", json_str(cc)));
}
if let Some(c) = record.admin.country.as_deref() {
props.push(format!("\"country\":\"{}\"", json_str(c)));
}
if let Some(r) = record.admin.region.as_deref() {
props.push(format!("\"state\":\"{}\"", json_str(r)));
}
if let Some(c) = record.admin.county.as_deref() {
props.push(format!("\"county\":\"{}\"", json_str(c)));
}
if let Some(l) = record.admin.locality.as_deref() {
props.push(format!("\"city\":\"{}\"", json_str(l)));
}
if let Some(n) = record.admin.neighbourhood.as_deref() {
props.push(format!("\"district\":\"{}\"", json_str(n)));
}
if let Some(addr) = &record.address {
if let Some(s) = addr.street.as_deref() {
props.push(format!("\"street\":\"{}\"", json_str(s)));
}
if let Some(n) = addr.number.as_deref() {
props.push(format!("\"housenumber\":\"{}\"", json_str(n)));
}
if let Some(p) = addr.postcode.as_deref() {
props.push(format!("\"postcode\":\"{}\"", json_str(p)));
}
}
let mut name_keys: Vec<&String> = record.names.keys().collect();
name_keys.sort();
for lang in name_keys {
if let Some(val) = record.names.get(lang) {
props.push(format!("\"name:{}\":\"{}\"", json_str(lang), json_str(val)));
}
}
let props_str = props.join(",");
format!(
"{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{{}}}}}",
record.lon, record.lat, props_str
)
}
const fn layer_to_photon_type(layer: GeocodingLayer) -> &'static str {
match layer {
GeocodingLayer::Address => "house",
GeocodingLayer::Venue => "amenity",
GeocodingLayer::Street => "street",
GeocodingLayer::Locality => "city",
GeocodingLayer::County => "county",
GeocodingLayer::Region => "state",
GeocodingLayer::Country => "country",
}
}
fn json_str(s: &str) -> String {
let quoted = serde_json::to_string(s).unwrap_or_else(|_| String::from("\"\""));
quoted[1..quoted.len() - 1].to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::RecordInit;
use crate::record::{GeocodingLayer, GeocodingRecord};
use geolith::admin::AdminHierarchy;
use geolith::source::input::{DataSource, OsmElementType};
use std::collections::HashMap;
fn make_record(name: &str, layer: GeocodingLayer) -> GeocodingRecord {
GeocodingRecord::new(RecordInit {
id: 1,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: vec![],
},
layer,
name: name.to_string(),
lon: 77.0,
lat: 28.0,
admin: AdminHierarchy {
country_code: Some("IN".to_string()),
country: Some("India".to_string()),
region: Some("Delhi NCT".to_string()),
county: None,
locality: Some("New Delhi".to_string()),
neighbourhood: None,
borough: None,
postcode: None,
city: None,
},
address: None,
names: HashMap::new(),
importance: 0.8,
})
}
#[test]
fn photon_json_is_valid_geojson_feature() {
let record = make_record("India Gate", GeocodingLayer::Venue);
let json = record_to_photon_json(&record);
assert!(json.starts_with("{\"type\":\"Feature\""));
assert!(json.contains("\"coordinates\":[77.0000000,28.0000000]"));
assert!(json.contains("\"name\":\"India Gate\""));
}
#[test]
fn photon_json_contains_admin_fields() {
let record = make_record("Connaught Place", GeocodingLayer::Venue);
let json = record_to_photon_json(&record);
assert!(json.contains("\"country\":\"India\""));
assert!(json.contains("\"city\":\"New Delhi\""));
assert!(json.contains("\"country_code\":\"IN\""));
}
#[test]
fn photon_writer_count() {
let mut buf = Vec::new();
let mut writer = PhotonWriter::new(&mut buf);
let record = make_record("Test", GeocodingLayer::Locality);
writer.write_record(&record).expect("write");
writer.write_record(&record).expect("write");
assert_eq!(writer.count(), 2);
let output = String::from_utf8(buf).expect("utf8");
assert_eq!(output.lines().count(), 2);
}
#[test]
fn json_str_escapes_special_chars() {
assert_eq!(json_str("a\"b"), "a\\\"b");
assert_eq!(json_str("a\\b"), "a\\\\b");
assert_eq!(json_str("a\nb"), "a\\nb");
}
#[test]
fn json_str_carriage_return_and_tab() {
assert_eq!(json_str("a\rb"), "a\\rb");
assert_eq!(json_str("a\tb"), "a\\tb");
assert_eq!(json_str(""), "");
assert_eq!(json_str("café"), "café");
}
#[test]
fn layer_to_photon_type_all_variants() {
assert_eq!(layer_to_photon_type(GeocodingLayer::Address), "house");
assert_eq!(layer_to_photon_type(GeocodingLayer::Venue), "amenity");
assert_eq!(layer_to_photon_type(GeocodingLayer::Street), "street");
assert_eq!(layer_to_photon_type(GeocodingLayer::Locality), "city");
assert_eq!(layer_to_photon_type(GeocodingLayer::County), "county");
assert_eq!(layer_to_photon_type(GeocodingLayer::Region), "state");
assert_eq!(layer_to_photon_type(GeocodingLayer::Country), "country");
}
#[test]
fn osm_type_letter_for_each_element_type() {
for (et, expected) in [
(OsmElementType::Node, "\"osm_type\":\"N\""),
(OsmElementType::Way, "\"osm_type\":\"W\""),
(OsmElementType::Relation, "\"osm_type\":\"R\""),
] {
let mut r = make_record("X", GeocodingLayer::Venue);
r.source = DataSource::Osm {
element_type: et,
relations: vec![],
};
let json = record_to_photon_json(&r);
assert!(json.contains(expected), "missing {expected}: {json}");
}
}
#[test]
fn osm_id_is_the_element_id_without_the_type_bits() {
let mut r = make_record("India Gate", GeocodingLayer::Venue);
r.id = (1 << 62) + 361_709_652;
r.source = DataSource::Osm {
element_type: OsmElementType::Way,
relations: vec![],
};
let json = record_to_photon_json(&r);
assert!(json.contains("\"osm_id\":361709652,"), "{json}");
}
#[test]
fn osm_type_defaults_to_node_for_non_osm_source() {
let mut r = make_record("X", GeocodingLayer::Country);
r.source = DataSource::NaturalEarth {
source_layer: "ne_10m_admin_0_countries".to_string(),
};
let json = record_to_photon_json(&r);
assert!(json.contains("\"osm_type\":\"N\""));
}
#[test]
fn photon_json_omits_optional_admin_fields_when_missing() {
let mut r = make_record("X", GeocodingLayer::Country);
r.country_code = None;
r.admin = AdminHierarchy {
country_code: None,
country: None,
region: None,
county: None,
locality: None,
neighbourhood: None,
borough: None,
postcode: None,
city: None,
};
let json = record_to_photon_json(&r);
assert!(!json.contains("\"country\":"));
assert!(!json.contains("\"state\":"));
assert!(!json.contains("\"county\":"));
assert!(!json.contains("\"city\":"));
assert!(!json.contains("\"district\":"));
assert!(!json.contains("\"country_code\":"));
}
#[test]
fn photon_json_includes_all_admin_levels_when_present() {
let mut r = make_record("X", GeocodingLayer::Locality);
r.admin = AdminHierarchy {
country_code: Some("FR".to_string()),
country: Some("France".to_string()),
region: Some("Île-de-France".to_string()),
county: Some("Paris".to_string()),
locality: Some("Paris".to_string()),
neighbourhood: Some("Le Marais".to_string()),
borough: None,
postcode: None,
city: None,
};
let json = record_to_photon_json(&r);
assert!(json.contains("\"country\":\"France\""));
assert!(json.contains("\"state\":\"Île-de-France\""));
assert!(json.contains("\"county\":\"Paris\""));
assert!(json.contains("\"city\":\"Paris\""));
assert!(json.contains("\"district\":\"Le Marais\""));
}
#[test]
fn photon_json_includes_address_fields() {
use crate::record::AddressFields;
let mut r = make_record("X", GeocodingLayer::Address);
r.address = Some(AddressFields {
number: Some("10".into()),
street: Some("Downing St".into()),
unit: None,
postcode: Some("SW1A 2AA".into()),
city: None,
});
let json = record_to_photon_json(&r);
assert!(json.contains("\"street\":\"Downing St\""));
assert!(json.contains("\"housenumber\":\"10\""));
assert!(json.contains("\"postcode\":\"SW1A 2AA\""));
}
#[test]
fn photon_json_omits_address_when_none() {
let r = make_record("X", GeocodingLayer::Locality);
let json = record_to_photon_json(&r);
assert!(!json.contains("\"street\":"));
assert!(!json.contains("\"housenumber\":"));
assert!(!json.contains("\"postcode\":"));
}
#[test]
fn photon_json_multilingual_names_sorted() {
let mut r = make_record("Beijing", GeocodingLayer::Locality);
r.names.insert("zh".into(), "北京".into());
r.names.insert("en".into(), "Beijing".into());
r.names.insert("ar".into(), "بكين".into());
let json = record_to_photon_json(&r);
assert!(json.contains("\"name:ar\":"));
assert!(json.contains("\"name:en\":"));
assert!(json.contains("\"name:zh\":"));
let ar = json.find("\"name:ar\":").unwrap();
let en = json.find("\"name:en\":").unwrap();
let zh = json.find("\"name:zh\":").unwrap();
assert!(ar < en);
assert!(en < zh);
}
#[test]
fn photon_writer_flush_succeeds() {
let mut probe = FlushProbe::default();
let mut writer = PhotonWriter::new(&mut probe);
writer
.write_record(&make_record("X", GeocodingLayer::Venue))
.expect("write");
writer.flush().expect("flush");
assert!(probe.flushed, "flush reaches the underlying writer");
}
#[derive(Default)]
struct FlushProbe {
flushed: bool,
}
impl std::io::Write for FlushProbe {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.flushed = true;
Ok(())
}
}
#[test]
fn photon_json_lat_lon_precision_seven_decimals() {
let mut r = make_record("X", GeocodingLayer::Venue);
r.lon = -122.4194155;
r.lat = 37.7749295;
let json = record_to_photon_json(&r);
assert!(json.contains("[-122.4194155,37.7749295]"));
}
#[test]
fn control_characters_in_a_name_give_valid_json() {
let mut record = make_record(
"Caf\u{0}\u{8}\u{1b}e \"quoted\" \\ tab\t",
GeocodingLayer::Venue,
);
record.lon = 2.5;
record.lat = 48.5;
record.names.insert("fr".into(), "nom\u{1f}".to_owned());
let line = record_to_photon_json(&record);
let parsed: serde_json::Value =
serde_json::from_str(&line).expect("the line is valid JSON");
assert_eq!(
parsed["properties"]["name"],
"Caf\u{0}\u{8}\u{1b}e \"quoted\" \\ tab\t"
);
assert_eq!(parsed["properties"]["name:fr"], "nom\u{1f}");
assert!(
!line.bytes().any(|b| b < 0x20),
"no raw control byte: {line:?}"
);
}
}