impl NodeLocations { /// `ids` need not be sorted or unique; both are done here. /// /// Fallible because the coordinate array is a mapped file, and a temporary directory that is full /// or read-only is a real thing to report rather than to panic on. pub fn new(mut ids: Vec) -> Result { ids.sort_unstable(); ids.dedup(); let index = NodeIds::build(&ids); // The plain vector goes here rather than being kept alongside: it is 8 bytes per id against // the index's ~1.2, and holding both would give back the saving. Freed before the coordinate // array is mapped, so the two never peak together. drop(ids); let locs = Locs::new(index.len())?; Ok(NodeLocations { ids: index, locs }) } /// The same table from an **ascending, unique** id stream of known length. /// /// [`Self::new`] takes a vector because most callers have one. A continental or planet extract /// does not want one: [`crate::extract`]-shaped callers hold the needed ids as a bitset over the /// node id space, which is a fixed ~1.7 GB for any extract, and turning that back into 8 bytes an /// id to hand it over would be the allocation the bitset exists to avoid. /// /// **Sorted and unique is a precondition, not a request.** It is what makes every gap positive, /// and an out-of-order id would encode as a ten-byte varint and quietly corrupt the index. A /// bitset walked low to high satisfies it by construction, which is the only reason this is safe /// to expose. pub fn from_sorted(ids: impl Iterator, len: usize) -> Result { let index = NodeIds::build_sorted(ids, len); let locs = Locs::new(index.len())?; Ok(NodeLocations { ids: index, locs }) } /// The same table from an already-populated bitset over the id space, taking ownership of its /// words: bit `i` set iff id `i` is needed, `len` the number of set bits. /// /// [`Self::from_sorted`] walks the caller's bitset into ids and re-sets them here, holding two /// words arrays at once. This moves the words across and builds the rank directory in place, so /// the peak is one bitset rather than two. The only production caller is the planet ref /// collector; the vector path ([`Self::new`]) is untouched. pub fn from_bitset(words: Vec, len: usize) -> Result { let index = NodeIds::from_words(words, len); let locs = Locs::new(index.len())?; Ok(NodeLocations { ids: index, locs }) } pub fn len(&self) -> usize { self.ids.len() } pub fn is_empty(&self) -> bool { self.ids.len() == 0 } fn index_of(&self, id: i64) -> Option { self.ids.find(id) } /// Whether `id` is one of the ids this table was built for. /// /// Distinct from [`Self::get`] returning `None`, which also means "in the set but the node pass /// never found it" -- the legitimate case at an extract's cut edges. pub fn contains(&self, id: i64) -> bool { self.index_of(id).is_some() } pub fn get(&self, id: i64) -> Option<(i32, i32)> { self.locs.get(self.index_of(id)? as usize) } /// Every ref's table index into `out` (cleared first), `false` as soon as one ref has no /// coordinate -- exactly the refs [`Self::line`] would drop. Reads only the in-memory id index /// and resolved bits, never the coordinate array: a caller that needs only some of a way's /// coordinates (its ends, or a prefix) can then read just those with [`Self::coord_at`]. pub fn indices_if_complete(&self, refs: &[i64], out: &mut Vec) -> bool { out.clear(); for &id in refs { match self.index_of(id) { Some(i) if self.locs.is_resolved(i as usize) => out.push(i as usize), _ => return false, } } true } /// The coordinate at a table index [`Self::indices_if_complete`] returned, in the same /// `(lon, lat)` degrees [`Self::line`] produces. pub fn coord_at(&self, index: usize) -> Coord { let (lat_e7, lon_e7) = self.locs.get(index).expect("a resolved index"); (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7) } /// A way's geometry in lon/lat order, with unresolved refs skipped. /// /// A ref can be unresolved for a legitimate reason: an extract cut through the /// way, so some of its nodes are simply not in the file. Skipping the gap keeps /// the rest of the line rather than discarding the whole way, which is what /// `osmium extract`'s `complete_ways` produces for the same input. pub fn line(&self, refs: &[i64]) -> Vec { refs.iter() .filter_map(|id| self.get(*id)) .map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7)) .collect() } } include!("nodeloc_part1.rs"); include!("nodeloc_part2.rs"); #[cfg(test)] mod scratch_tests { use super::*; /// The coordinate table's scratch file is unlinked as soon as it is mapped: nothing is left /// in the scratch dir even while the table is live, and the table still works. #[test] fn the_coordinate_scratch_is_unlinked_while_mapped() { let dir = std::env::temp_dir().join(format!("osm_nodeloc_unlink_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut locs = Locs::new_in(&dir, 1000).unwrap(); locs.set(7, 123, -456); let left: Vec<_> = std::fs::read_dir(&dir).unwrap().collect(); #[cfg(unix)] assert!(left.is_empty(), "scratch left in {}: {left:?}", dir.display()); assert_eq!(locs.get(7), Some((123, -456))); drop(locs); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); std::fs::remove_dir(&dir).unwrap(); } }