Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/roadrunner-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ tracing.workspace = true

[dev-dependencies]
criterion = "0.7.0"
serde_json = "1"

[[bench]]
name = "graph_traversal"
Expand Down
3 changes: 2 additions & 1 deletion crates/roadrunner-core/benches/graph_traversal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::collections::{HashSet, VecDeque};
use std::hint::black_box;

use criterion::{BenchmarkId, Criterion, Throughput};
use roadrunner_core::geo::Coordinate;
use roadrunner_core::graph::{Edge, EdgeId, Graph, Node, NodeId};

const FAN_OUT: u32 = 3;
Expand All @@ -14,7 +15,7 @@ fn generated_graph(node_count: u32) -> Graph {
let mut graph = Graph::new();

for value in 0..node_count {
let result = graph.add_node(Node::new(NodeId::new(value)));
let result = graph.add_node(Node::new(NodeId::new(value), Coordinate::ORIGIN));
assert!(
result.is_ok(),
"generated node insertion failed: {result:?}"
Expand Down
165 changes: 165 additions & 0 deletions crates/roadrunner-core/src/geo/bounding_box.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::Coordinate;

/// An inclusive, axis-aligned geographic bounding box.
///
/// Antimeridian-crossing boxes are deferred. Consequently, the western longitude
/// must be less than or equal to the eastern longitude.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "BoundingBoxRepr", into = "BoundingBoxRepr")]
pub struct BoundingBox {
south_west: Coordinate,
north_east: Coordinate,
}

impl BoundingBox {
/// Creates a box from its south-west and north-east corners.
///
/// # Errors
///
/// Returns [`BoundingBoxError`] when latitude or longitude bounds are inverted.
pub fn new(south_west: Coordinate, north_east: Coordinate) -> Result<Self, BoundingBoxError> {
if south_west.latitude() > north_east.latitude() {
return Err(BoundingBoxError::InvertedLatitude {
south: south_west.latitude(),
north: north_east.latitude(),
});
}
if south_west.longitude() > north_east.longitude() {
return Err(BoundingBoxError::InvertedLongitude {
west: south_west.longitude(),
east: north_east.longitude(),
});
}

Ok(Self {
south_west,
north_east,
})
}

/// Returns the south-west corner.
#[must_use]
pub const fn south_west(self) -> Coordinate {
self.south_west
}

/// Returns the north-east corner.
#[must_use]
pub const fn north_east(self) -> Coordinate {
self.north_east
}

/// Returns whether a coordinate lies inside or on the box boundary.
#[must_use]
pub fn contains(self, coordinate: Coordinate) -> bool {
(self.south_west.latitude()..=self.north_east.latitude()).contains(&coordinate.latitude())
&& (self.south_west.longitude()..=self.north_east.longitude())
.contains(&coordinate.longitude())
}
}

#[derive(Serialize, Deserialize)]
struct BoundingBoxRepr {
south_west: Coordinate,
north_east: Coordinate,
}

impl TryFrom<BoundingBoxRepr> for BoundingBox {
type Error = BoundingBoxError;

fn try_from(value: BoundingBoxRepr) -> Result<Self, Self::Error> {
Self::new(value.south_west, value.north_east)
}
}

impl From<BoundingBox> for BoundingBoxRepr {
fn from(value: BoundingBox) -> Self {
Self {
south_west: value.south_west(),
north_east: value.north_east(),
}
}
}

/// Errors produced when constructing a bounding box.
#[derive(Debug, Clone, Copy, PartialEq, Error)]
pub enum BoundingBoxError {
/// The southern latitude is north of the northern latitude.
#[error("south latitude {south} exceeds north latitude {north}")]
InvertedLatitude {
/// The rejected southern latitude.
south: f64,
/// The rejected northern latitude.
north: f64,
},

/// The western longitude is east of the eastern longitude.
#[error("west longitude {west} exceeds east longitude {east}")]
InvertedLongitude {
/// The rejected western longitude.
west: f64,
/// The rejected eastern longitude.
east: f64,
},
}

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

fn coordinate(latitude: f64, longitude: f64) -> Coordinate {
let result = Coordinate::new(latitude, longitude);
let Ok(coordinate) = result else {
panic!("expected test coordinate to be valid: {result:?}");
};
coordinate
}

#[test]
fn contains_interior_and_boundary_coordinates() {
let bounds = BoundingBox::new(coordinate(6.0, 3.0), coordinate(7.0, 4.0));
let Ok(bounds) = bounds else {
panic!("expected test bounds to be valid");
};

assert!(bounds.contains(coordinate(6.5, 3.5)));
assert!(bounds.contains(coordinate(6.0, 3.0)));
assert!(bounds.contains(coordinate(7.0, 4.0)));
assert!(!bounds.contains(coordinate(7.1, 3.5)));
}

#[test]
fn rejects_inverted_latitude_bounds() {
assert_eq!(
BoundingBox::new(coordinate(7.0, 3.0), coordinate(6.0, 4.0)),
Err(BoundingBoxError::InvertedLatitude {
south: 7.0,
north: 6.0,
})
);
}

#[test]
fn rejects_inverted_longitudes_and_antimeridian_crossing_boxes() {
assert_eq!(
BoundingBox::new(coordinate(-10.0, 170.0), coordinate(10.0, -170.0)),
Err(BoundingBoxError::InvertedLongitude {
west: 170.0,
east: -170.0,
})
);
}

#[test]
fn deserialization_preserves_box_invariants() {
let serialized = r#"{
"south_west":{"latitude":7,"longitude":3},
"north_east":{"latitude":6,"longitude":4}
}"#;

assert!(serde_json::from_str::<BoundingBox>(serialized).is_err());
}
}
162 changes: 162 additions & 0 deletions crates/roadrunner-core/src/geo/coordinate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// A validated WGS 84 latitude and longitude pair in decimal degrees.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "CoordinateRepr", into = "CoordinateRepr")]
pub struct Coordinate {
latitude: f64,
longitude: f64,
}

impl Coordinate {
/// The intersection of the equator and prime meridian.
pub const ORIGIN: Self = Self {
latitude: 0.0,
longitude: 0.0,
};

/// Creates a validated coordinate in decimal degrees.
///
/// # Errors
///
/// Returns [`CoordinateError`] when either component is not finite, latitude
/// falls outside `[-90, 90]`, or longitude falls outside `[-180, 180]`.
pub fn new(latitude: f64, longitude: f64) -> Result<Self, CoordinateError> {
if !latitude.is_finite() {
return Err(CoordinateError::LatitudeNotFinite { latitude });
}
if !longitude.is_finite() {
return Err(CoordinateError::LongitudeNotFinite { longitude });
}
if !(-90.0..=90.0).contains(&latitude) {
return Err(CoordinateError::LatitudeOutOfRange { latitude });
}
if !(-180.0..=180.0).contains(&longitude) {
return Err(CoordinateError::LongitudeOutOfRange { longitude });
}

Ok(Self {
latitude,
longitude,
})
}

/// Returns latitude in decimal degrees.
#[must_use]
pub const fn latitude(self) -> f64 {
self.latitude
}

/// Returns longitude in decimal degrees.
#[must_use]
pub const fn longitude(self) -> f64 {
self.longitude
}
}

#[derive(Serialize, Deserialize)]
struct CoordinateRepr {
latitude: f64,
longitude: f64,
}

impl TryFrom<CoordinateRepr> for Coordinate {
type Error = CoordinateError;

fn try_from(value: CoordinateRepr) -> Result<Self, Self::Error> {
Self::new(value.latitude, value.longitude)
}
}

impl From<Coordinate> for CoordinateRepr {
fn from(value: Coordinate) -> Self {
Self {
latitude: value.latitude(),
longitude: value.longitude(),
}
}
}

/// Errors produced when constructing a coordinate.
#[derive(Debug, Clone, Copy, PartialEq, Error)]
pub enum CoordinateError {
/// Latitude is NaN or infinite.
#[error("latitude must be finite, got {latitude}")]
LatitudeNotFinite {
/// The rejected latitude.
latitude: f64,
},

/// Longitude is NaN or infinite.
#[error("longitude must be finite, got {longitude}")]
LongitudeNotFinite {
/// The rejected longitude.
longitude: f64,
},

/// Latitude is outside the inclusive WGS 84 range.
#[error("latitude must be between -90 and 90 degrees, got {latitude}")]
LatitudeOutOfRange {
/// The rejected latitude.
latitude: f64,
},

/// Longitude is outside the inclusive WGS 84 range.
#[error("longitude must be between -180 and 180 degrees, got {longitude}")]
LongitudeOutOfRange {
/// The rejected longitude.
longitude: f64,
},
}

#[cfg(test)]
mod tests {
use serde_json::json;

use super::*;

#[test]
fn accepts_boundary_coordinates() {
assert!(Coordinate::new(-90.0, -180.0).is_ok());
assert!(Coordinate::new(90.0, 180.0).is_ok());
}

#[test]
fn rejects_out_of_range_components() {
assert_eq!(
Coordinate::new(90.1, 0.0),
Err(CoordinateError::LatitudeOutOfRange { latitude: 90.1 })
);
assert_eq!(
Coordinate::new(0.0, -180.1),
Err(CoordinateError::LongitudeOutOfRange { longitude: -180.1 })
);
}

#[test]
fn rejects_non_finite_components() {
assert!(matches!(
Coordinate::new(f64::NAN, 0.0),
Err(CoordinateError::LatitudeNotFinite { .. })
));
assert!(matches!(
Coordinate::new(0.0, f64::INFINITY),
Err(CoordinateError::LongitudeNotFinite { .. })
));
}

#[test]
fn serde_round_trip_preserves_fields_and_validation() {
let coordinate = Coordinate::new(6.5244, 3.3792);
let Ok(coordinate) = coordinate else {
panic!("expected the Lagos coordinate to be valid");
};

assert!(matches!(
serde_json::to_value(coordinate),
Ok(value) if value == json!({ "latitude": 6.5244, "longitude": 3.3792 })
));
assert!(serde_json::from_str::<Coordinate>(r#"{"latitude":91,"longitude":0}"#).is_err());
}
}
Loading
Loading