87 lines
2.1 KiB
Rust
Raw Normal View History

use crate::{
common::{optional_separator, parse_direction},
Direction,
};
use nom::{
branch::alt,
character::complete::{self, space0, space1},
combinator::{eof, map, map_opt, map_res, opt},
number::complete::double,
sequence::{pair, tuple},
IResult,
};
use std::str::FromStr;
#[derive(PartialEq, Debug)]
pub struct Coordinate(pub DM, pub DM);
#[derive(PartialEq, Debug)]
pub struct DM {
pub degrees: i16,
pub minutes: f64,
pub direction: Direction,
}
pub fn parse_coordinate(i: &str) -> IResult<&str, Coordinate> {
map_opt(
tuple((parse, optional_separator(','), parse)),
|(ns, _, ew)| {
// Ensure this is a north/south then east/west direction
if ns.direction.is_lat() && ew.direction.is_lon() {
Some(Coordinate(ns, ew))
} else {
None
}
},
)(i)
}
pub fn parse(i: &str) -> IResult<&str, DM> {
map(
tuple((
// Degrees
complete::i16,
optional_separator('°'),
// Minutes
double,
optional_separator('\''),
// Direction
parse_direction,
)),
|(degrees, (), minutes, (), direction)| DM {
degrees,
minutes,
direction,
},
)(i)
}
impl FromStr for DM {
type Err = ();
/// Recognizes DMS in the formats:
///
/// * `40° 31' 21" N, 105° 5' 39" W`
/// * `40 31 21 N, 105 5 39 W`
///
/// ```rust
/// use spatial_coordinate_systems::dm::DM;
/// use spatial_coordinate_systems::Direction;
/// use std::str::FromStr;
///
/// assert_eq!(DM::from_str("40 31.3 N").unwrap(), DM {
/// degrees: 40,
/// minutes: 31.3_f64,
/// direction: Direction::North,
/// });
/// assert_eq!(DM::from_str("40°31' N").unwrap(), DM {
/// degrees: 40,
/// minutes: 31_f64,
/// direction: Direction::North,
/// });
/// ```
fn from_str(i: &str) -> Result<Self, Self::Err> {
parse(i).map_err(|_| ()).map(|(_, ret)| ret)
}
}