proto_types/common/
latlng.rs1use thiserror::Error;
2
3use crate::LatLng;
4
5#[derive(Debug, Error, PartialEq, Eq, Clone)]
7#[non_exhaustive]
8pub enum LatLngError {
9 #[error("Latitude out of valid range (-90.0, +90.0)")]
10 InvalidLatitude,
11 #[error("Longitude out of valid range (-180.0, +180.0)")]
12 InvalidLongitude,
13}
14
15fn validate_latlng(latitude: f64, longitude: f64) -> Result<(), LatLngError> {
16 if !((-90.0..=90.0).contains(&latitude)) {
17 Err(LatLngError::InvalidLatitude)
18 } else if !((-180.0..=180.0).contains(&longitude)) {
19 Err(LatLngError::InvalidLongitude)
20 } else {
21 Ok(())
22 }
23}
24
25impl LatLng {
26 #[inline]
27 pub fn new(latitude: f64, longitude: f64) -> Result<Self, LatLngError> {
29 validate_latlng(latitude, longitude)?;
30
31 Ok(Self {
32 latitude,
33 longitude,
34 })
35 }
36
37 #[inline]
38 pub fn validate(&self) -> Result<(), LatLngError> {
40 validate_latlng(self.latitude, self.longitude)
41 }
42
43 #[must_use]
45 #[inline]
46 pub fn is_valid(&self) -> bool {
47 self.validate().is_ok()
48 }
49}
50
51impl core::fmt::Display for LatLng {
52 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53 write!(f, "{:.6},{:.6}", self.latitude, self.longitude)
54 }
55}