lat_long/lib.rs
1//! Geographic latitude and longitude coordinate types.
2//!
3//! This crate provides strongly-typed [`Latitude`], [`Longitude`], and [`Coordinate`] values that are validated on
4//! construction and carry their own display logic (decimal degrees **or** degrees–minutes–seconds). The goal is not
5//! to provide a single, large, and potentially unwieldy "geo" crate, but rather a collection of small, focused crates
6//! that can be used together or independently.
7//!
8//! ## Quick start
9//!
10//! ```rust
11//! use lat_long::{Angle, Coordinate, Latitude, Longitude};
12//!
13//! let lat = Latitude::new(48, 51, 29.6).expect("valid latitude");
14//! let lon = Longitude::new(2, 21, 7.6).expect("valid longitude");
15//! let paris = Coordinate::new(lat, lon);
16//!
17//! // Decimal-degree display (default)
18//! println!("{paris}"); // => 48.858222, 2.218778
19//! // Degrees–minutes–seconds display (alternate flag)
20//! println!("{paris:#}"); // => 48° 51' 29.6" N, 2° 21' 7.6" E
21//! ```
22//!
23//! ```rust
24//! use lat_long::{parse::{self, Parsed}, Coordinate};
25//!
26//! if let Ok(Parsed::Coordinate(london)) = parse::parse_str("51.522, -0.127") {
27//! println!("{london}"); // => 51.522, -0.127
28//! }
29//! ```
30//!
31//! ```rust,ignore
32//! // Convert to URL, requires `url` feature flag
33//! let url = url::Url::from(paris);
34//! println!("{url}"); // => geo:48.858222,2.218778
35//! ```
36//!
37//! ```rust,ignore
38//! // Convert to JSON, requires `geojson` feature flag
39//! let json = serde_json::Value::from(paris);
40//! println!("{json}"); // => { "type": "Point", "coordinates": [48.858222,2.218778] }
41//! ```
42//!
43//! ## Formatting
44//!
45//! The [`fmt`] module provides functionality for formatting and parsing coordinates.
46//!
47//! | `FormatKind` | Format String | Positive | Negative |
48//! |-----------------|---------------|----------------------|----------------------|
49//! | `Decimal` | `{}` | 48.858222 | -48.858222 |
50//! | `DmsSigned` | `{:#}` | 48° 51′ 29.600000″ | -48° 51′ 29.600000″ |
51//! | `DmsLabeled` | N/A | 48° 51′ 29.600000″ N | 48° 51′ 29.600000″ S |
52//! | `DmsBare` | N/A | +048:51:29.600000 | -048:51:29.600000 |
53//!
54//! Note that the `DmsBare` format is intended as a regular, easy-to-parse format for use in
55//! data files, rather than as a human-readable format. In it`s coordinate pair form, it is
56//! also the only format that does not allow whitespace around the comma separator.
57//!
58//! ## Parsing
59//!
60//! The [`parse`] module provides functionality for parsing coordinates. The parser accepts all of the
61//! formats described above. The parser is also used by the implementation of `FromStr` for `Latitude`,
62//! `Longitude`, and `Coordinate`.
63//!
64//! ## Feature flags
65#![doc = document_features::document_features!()]
66//! ## References
67//!
68//! * [Latitude and longitude](https://en.wikipedia.org/wiki/Geographic_coordinate_system#Latitude_and_longitude)
69//! * [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)
70
71use std::fmt::{Debug, Display};
72use std::hash::Hash;
73
74// ---------------------------------------------------------------------------
75// Public Types
76// ---------------------------------------------------------------------------
77
78pub trait Angle:
79 Clone
80 + Copy
81 + Debug
82 + Default
83 + Display
84 + PartialEq
85 + Eq
86 + PartialOrd
87 + Ord
88 + Hash
89 + TryFrom<OrderedFloat<f64>, Error = Error>
90 + Into<OrderedFloat<f64>>
91{
92 const MIN: Self;
93 const MAX: Self;
94
95 /// Construct a new angle from degrees, minutes, and seconds.
96 fn new(degrees: i32, minutes: u32, seconds: f32) -> Result<Self, Error>
97 where
98 Self: Sized;
99
100 fn as_float(&self) -> OrderedFloat<f64> {
101 (*self).into()
102 }
103
104 /// Returns `true` if the angle is exactly zero.
105 fn is_zero(&self) -> bool {
106 self.as_float() == inner::ZERO
107 }
108
109 /// Returns `true` if the angle is positive and non-zero.
110 fn is_nonzero_positive(&self) -> bool {
111 !self.is_zero() && self.as_float() > inner::ZERO
112 }
113
114 /// Returns `true` if the angle is negative and non-zero.
115 fn is_nonzero_negative(&self) -> bool {
116 !self.is_zero() && self.as_float() < inner::ZERO
117 }
118
119 /// The signed integer degrees component (carries the sign for negative angles).
120 fn degrees(&self) -> i32 {
121 inner::to_degrees_minutes_seconds(self.as_float()).0
122 }
123
124 /// The unsigned minutes component (always in `0..60`).
125 fn minutes(&self) -> u32 {
126 inner::to_degrees_minutes_seconds(self.as_float()).1
127 }
128
129 /// The unsigned seconds component (always in `0.0..60.0`).
130 fn seconds(&self) -> f32 {
131 inner::to_degrees_minutes_seconds(self.as_float()).2
132 }
133
134 /// Checked absolute value. Computes self.abs(), returning None if self == MIN.
135 fn checked_abs(self) -> Option<Self>
136 where
137 Self: Sized,
138 {
139 if self == Self::MIN {
140 None
141 } else {
142 Some(Self::try_from(OrderedFloat(self.into().0.abs())).unwrap())
143 }
144 }
145
146 /// Computes the absolute value of self.
147 ///
148 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow happened.
149 /// If self is the minimum value Self::MIN, then the minimum value will be returned again and true will be returned
150 /// for an overflow happening.
151 fn overflowing_abs(self) -> (Self, bool)
152 where
153 Self: Sized,
154 {
155 if self == Self::MIN {
156 (self, true)
157 } else {
158 (
159 Self::try_from(OrderedFloat(self.into().0.abs())).unwrap(),
160 false,
161 )
162 }
163 }
164
165 /// Saturating absolute value. Computes self.abs(), returning MAX if self == MIN instead of overflowing.
166 fn saturating_abs(self) -> Self
167 where
168 Self: Sized,
169 {
170 if self == Self::MIN {
171 Self::MAX
172 } else {
173 Self::try_from(OrderedFloat(self.into().0.abs())).unwrap()
174 }
175 }
176
177 /// Strict absolute value. Computes self.abs(), panicking if self == MIN.
178 fn strict_abs(self) -> Self
179 where
180 Self: Sized,
181 {
182 if self == Self::MIN {
183 panic!("attempt to take absolute value of the minimum value")
184 } else {
185 Self::try_from(OrderedFloat(self.into().0.abs())).unwrap()
186 }
187 }
188
189 /// Unchecked absolute value. Computes self.abs(), assuming overflow cannot occur.
190 ///
191 /// Calling x.unchecked_abs() is semantically equivalent to calling x.checked_abs().unwrap_unchecked().
192 ///
193 /// If you’re just trying to avoid the panic in debug mode, then do not use this. Instead, you’re looking for wrapping_abs.
194 fn unchecked_abs(self) -> Self
195 where
196 Self: Sized,
197 {
198 Self::try_from(OrderedFloat(self.into().0.abs())).unwrap()
199 }
200
201 /// Wrapping (modular) absolute value. Computes self.abs(), wrapping around at the boundary of the type.
202 ///
203 /// The only case where such wrapping can occur is when one takes the absolute value of the negative minimal
204 /// value for the type; this is a positive value that is too large to represent in the type. In such a case,
205 /// this function returns MIN itself.
206 fn wrapping_abs(self) -> Self
207 where
208 Self: Sized,
209 {
210 if self == Self::MIN {
211 Self::MIN
212 } else {
213 Self::try_from(OrderedFloat(self.into().0.abs())).unwrap()
214 }
215 }
216}
217
218// ---------------------------------------------------------------------------
219// Internal Modules
220// ---------------------------------------------------------------------------
221
222mod inner;
223pub mod parse;
224
225// ---------------------------------------------------------------------------
226// Public Modules & Exports
227// ---------------------------------------------------------------------------
228
229pub mod coord;
230pub use coord::Coordinate;
231pub mod error;
232pub use error::Error;
233pub mod fmt;
234pub mod lat;
235pub use lat::Latitude;
236pub mod long;
237pub use long::Longitude;
238use ordered_float::OrderedFloat;