#![allow(dead_code, reason = "each test uses a part")]
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::{Display, Write as _};
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::Duration;
use osmflow::{Block, Info, MemberType, PbfError, PbfReader, Select, TagKey, Timestamp};
const NO_INFO: Info<'static> = Info {
version: -1,
timestamp: Timestamp::EPOCH,
changeset: 0,
uid: 0,
user: "",
visible: true,
};
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_ascii_alphanumeric() || "-_.:/".contains(c) {
out.push(c);
} else {
write!(out, "%{:x}%", u32::from(c)).unwrap();
}
}
out
}
fn join<T: Display>(items: impl IntoIterator<Item = T>) -> String {
let mut out = String::new();
for (i, item) in items.into_iter().enumerate() {
let sep = if i == 0 { "" } else { "," };
write!(out, "{sep}{item}").unwrap();
}
out
}
fn head<'a>(
kind: char,
id: i64,
info: Option<Info<'_>>,
tags: impl Iterator<Item = (&'a str, &'a str)>,
basic: bool,
) -> String {
let mut tags: Vec<String> = tags
.map(|(k, v)| format!("{}={}", escape(k), escape(v)))
.collect();
if basic {
tags.sort();
return format!("{kind}{id} T{}", tags.join(","));
}
let i = info.unwrap_or(NO_INFO);
format!(
"{kind}{id} v{} d{} c{} t{} i{} u{} T{}",
i.version,
if i.visible { 'V' } else { 'D' },
i.changeset,
i.timestamp.as_millis(),
i.uid,
escape(i.user),
tags.join(",")
)
}
fn member(kind: char, id: i64, role: &str) -> String {
format!("{kind}{id}@{}", escape(role))
}
pub fn osmflow_block(block: &Block, basic: bool) -> Vec<String> {
let nodes = block.nodes().map(|n| {
let head = head('n', n.id(), n.info(), n.tags(), basic);
if basic {
format!("{head} x{} y{}", n.decimicro_lon(), n.decimicro_lat())
} else {
format!("{head} x{} y{}", n.lon_nano(), n.lat_nano())
}
});
let ways = block.ways().map(|w| {
let mut line = format!(
"{} N{}",
head('w', w.id(), w.info(), w.tags(), basic),
join(w.refs())
);
if !basic && let Some(locs) = w.locations() {
write!(
line,
" L{}",
join(locs.map(|(lat, lon)| format!("{lon}/{lat}")))
)
.unwrap();
}
line
});
let relations = block.relations().map(|r| {
let members = r.members().map(|m| {
let kind = match m.kind {
MemberType::Node => 'n',
MemberType::Way => 'w',
MemberType::Relation => 'r',
};
member(kind, m.id, m.role)
});
format!(
"{} M{}",
head('r', r.id(), r.info(), r.tags(), basic),
join(members)
)
});
nodes.chain(ways).chain(relations).collect()
}
pub fn osmflow_header(file: &PbfReader) -> Vec<String> {
let h = file.header();
vec![
format!("# required: {}", h.required_features.join(", ")),
format!("# optional: {}", h.optional_features.join(", ")),
format!(
"# writing program: {:?}, source: {:?}",
h.writing_program, h.source
),
format!(
"# bbox: {:?}",
h.bbox.map(|b| (b.left, b.bottom, b.right, b.top))
),
format!(
"# replication: {:?} {:?} {:?}",
h.replication_timestamp.map(|t| t.to_string()),
h.replication_sequence,
h.replication_base_url
),
]
}
pub fn osmflow(file: &PbfReader, basic: bool) -> Result<Vec<String>, PbfError> {
let mut out = Vec::new();
for block in file.blocks(Select::all())? {
let block = block?;
check_tag_lookup(&block);
out.extend(osmflow_block(&block, basic));
}
Ok(out)
}
pub fn check_tag_lookup(block: &Block) {
let mut keys: Vec<&str> = block
.nodes()
.flat_map(|n| n.tags())
.chain(block.ways().flat_map(|w| w.tags()))
.chain(block.relations().flat_map(|r| r.tags()))
.map(|(k, _)| k)
.collect();
keys.sort_unstable();
keys.dedup();
let found: HashMap<&str, TagKey<'_>> = keys
.iter()
.map(|&k| {
(
k,
block
.tag_key(k)
.expect("a key of the block's tags is in its string table"),
)
})
.collect();
let check = |kind: &str,
id: i64,
tags: Vec<(&str, &str)>,
tag: &dyn Fn(TagKey<'_>) -> Option<String>| {
for (i, &(k, v)) in tags.iter().enumerate() {
if tags[..i].iter().all(|&(earlier, _)| earlier != k) {
assert_eq!(tag(found[k]).as_deref(), Some(v), "{kind} {id} key {k}");
}
}
if let Some(missing) = keys.iter().find(|&&k| tags.iter().all(|&(t, _)| t != k)) {
assert_eq!(tag(found[missing]), None, "{kind} {id} lacks {missing}");
}
};
for n in block.nodes() {
check("node", n.id(), n.tags().collect(), &|k| {
n.tag(k).map(str::to_owned)
});
}
for w in block.ways() {
check("way", w.id(), w.tags().collect(), &|k| {
w.tag(k).map(str::to_owned)
});
}
for r in block.relations() {
check("relation", r.id(), r.tags().collect(), &|k| {
r.tag(k).map(str::to_owned)
});
}
assert!(block.tag_key("no such key in any fixture").is_none());
}
pub fn osmflow_ordered(file: &PbfReader) -> Result<Vec<String>, PbfError> {
let mut out = Vec::new();
for block in file.par_ordered(Select::all())? {
out.extend(osmflow_block(&block?, false));
}
Ok(out)
}
fn osmpbf_info<'a>(i: &osmpbf::Info<'a>) -> Info<'a> {
Info {
version: i.version().unwrap_or(-1),
timestamp: Timestamp::from_millis(i.milli_timestamp().unwrap_or(0)),
changeset: i.changeset().unwrap_or(0),
uid: i.uid().unwrap_or(0),
user: i.user().transpose().unwrap().unwrap_or(""),
visible: i.visible(),
}
}
pub fn osmpbf(path: &Path) -> Result<Vec<String>, osmpbf::Error> {
use osmpbf::{BlobDecode, BlobReader, Element, RelMemberType};
let mut out = Vec::new();
for blob in BlobReader::from_path(path)? {
let BlobDecode::OsmData(block) = blob?.decode()? else {
continue;
};
let mut lines = Vec::new();
block.for_each_element(|e| {
lines.push(match e {
Element::Node(n) => format!(
"{} x{} y{}",
head('n', n.id(), Some(osmpbf_info(&n.info())), n.tags(), false),
n.nano_lon(),
n.nano_lat()
),
Element::DenseNode(n) => {
let info = n.info().map(|i| Info {
version: i.version(),
timestamp: Timestamp::from_millis(i.milli_timestamp()),
changeset: i.changeset(),
uid: i.uid(),
user: i.user().unwrap(),
visible: i.visible(),
});
format!(
"{} x{} y{}",
head('n', n.id(), info, n.tags(), false),
n.nano_lon(),
n.nano_lat()
)
}
Element::Way(w) => {
let head = head('w', w.id(), Some(osmpbf_info(&w.info())), w.tags(), false);
let mut line = format!("{head} N{}", join(w.refs()));
let mut locs = w
.node_locations()
.map(|l| format!("{}/{}", l.nano_lon(), l.nano_lat()))
.peekable();
if locs.peek().is_some() {
write!(line, " L{}", join(locs)).unwrap();
}
line
}
Element::Relation(r) => {
let members = r.members().map(|m| {
let kind = match m.member_type {
RelMemberType::Node => 'n',
RelMemberType::Way => 'w',
RelMemberType::Relation => 'r',
};
member(kind, m.member_id, m.role().unwrap())
});
let head = head('r', r.id(), Some(osmpbf_info(&r.info())), r.tags(), false);
format!("{head} M{}", join(members))
}
});
});
lines.sort_by_key(|l| match l.as_bytes()[0] {
b'n' => 0,
b'w' => 1,
_ => 2,
});
out.extend(lines);
}
Ok(out)
}
pub fn osmpbfreader(path: &Path) -> Result<Vec<String>, osmpbfreader::Error> {
use osmpbfreader::{OsmId, OsmObj, OsmPbfReader, Tags};
let head = |kind, id, tags: &Tags| {
head(
kind,
id,
None,
tags.iter().map(|(k, v)| (k.as_str(), v.as_str())),
true,
)
};
let mut reader = OsmPbfReader::new(File::open(path)?);
let mut out = Vec::new();
for obj in reader.iter() {
out.push(match obj? {
OsmObj::Node(n) => format!(
"{} x{} y{}",
head('n', n.id.0, &n.tags),
n.decimicro_lon,
n.decimicro_lat
),
OsmObj::Way(w) => format!(
"{} N{}",
head('w', w.id.0, &w.tags),
join(w.nodes.iter().map(|n| n.0))
),
OsmObj::Relation(r) => {
let members = r.refs.iter().map(|m| match m.member {
OsmId::Node(id) => member('n', id.0, &m.role),
OsmId::Way(id) => member('w', id.0, &m.role),
OsmId::Relation(id) => member('r', id.0, &m.role),
});
format!("{} M{}", head('r', r.id.0, &r.tags), join(members))
}
});
}
Ok(out)
}
pub fn fnv(lines: &[String]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for line in lines {
for &b in line.as_bytes().iter().chain(b"\n") {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
}
hash
}
fn types(block: &Block) -> u8 {
u8::from(block.nodes().len() > 0)
| u8::from(block.ways().len() > 0) << 1
| u8::from(block.relations().len() > 0) << 2
}
#[allow(
clippy::panic_in_result_fn,
reason = "the barrier check fails the test"
)]
pub fn osmflow_unordered(file: &PbfReader) -> Result<Vec<String>, PbfError> {
static POOL: OnceLock<Arc<rayon::ThreadPool>> = OnceLock::new();
let pool = POOL.get_or_init(|| {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(3)
.build()
.unwrap();
Arc::new(pool)
});
let file = file.clone().with_pool(Arc::clone(pool));
let mut run_of = BTreeMap::new();
let (mut run_types, mut run_start) = (0, 0);
for block in file.blocks(Select::all())? {
let block = block?;
let (blob, t) = (block.position().blob, types(&block));
if t != 0 && t != run_types {
(run_types, run_start) = (t, blob);
}
run_of.insert(blob, run_start);
}
let finished = Mutex::new(BTreeSet::new());
let blocks = Mutex::new(Vec::new());
file.par_unordered(Select::all(), |block| {
let blob = block.position().blob;
let start = run_of[&blob];
{
let finished = finished.lock().unwrap();
for &earlier in run_of.range(..start).map(|(b, _)| b) {
assert!(
finished.contains(&earlier),
"blob {blob}, in the run from blob {start}, started before blob {earlier} finished"
);
}
}
thread::sleep(Duration::from_millis(1));
let lines = osmflow_block(&block, false);
blocks.lock().unwrap().push((blob, lines));
finished.lock().unwrap().insert(blob);
Ok(())
})?;
let mut blocks = blocks.into_inner().unwrap();
blocks.sort_by_key(|(blob, _)| *blob);
Ok(blocks.into_iter().flat_map(|(_, lines)| lines).collect())
}
pub fn node_locations<T: osmflow::TagMode>(
file: &PbfReader,
select: Select<T>,
) -> Result<Vec<(i64, i64, i64)>, PbfError> {
let mut out = Vec::new();
for block in file.blocks(select)? {
out.extend(block?.nodes().map(|n| (n.id(), n.lat_nano(), n.lon_nano())));
}
Ok(out)
}