1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::{error, fmt};

#[derive(PartialEq, Debug)]
pub struct Coordinate {
    pub latitude: f64,
    pub longitude: f64,
}

#[derive(PartialEq, Debug)]
pub enum Error {
    InvalidLength(usize),
    InvalidCode(String),
    InvalidCoordinates(Vec<String>),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidLength(length) => {
                write!(f, "Invalid length {}, should be 2, 4, 6, 8 or 10", length)
            }
            Error::InvalidCode(code) => write!(f, "Invalid code: {}", code),
            Error::InvalidCoordinates(coordinate) => {
                write!(f, "Invalid coordinate: {:?}", coordinate)
            }
        }
    }
}
impl error::Error for Error {}

pub fn min(a: f64, b: f64) -> f64 {
    if a < b {
        return a;
    }
    b
}

pub fn max(a: f64, b: f64) -> f64 {
    if a > b {
        return a;
    }
    b
}

pub const DIGITS: &'static str = "23456789CFGHJMPQRVWX";

pub fn parse_coordinate(coords: Vec<String>) -> Result<Coordinate, Error> {
    let flattened: Vec<Result<f64, _>> = coords
        .iter()
        .flat_map(|latlon| latlon.split(","))
        .filter(|latlon| !latlon.is_empty())
        .map(|coord| coord.parse())
        .collect();

    if flattened.len() != 2 {
        return Err(Error::InvalidCoordinates(coords).into());
    }

    let latitude = match flattened[0] {
        Ok(c) => c,
        Err(_) => return Err(Error::InvalidCoordinates(coords)),
    };

    let longitude = match flattened[1] {
        Ok(c) => c,
        Err(_) => return Err(Error::InvalidCoordinates(coords)),
    };

    Ok(Coordinate {
        latitude,
        longitude,
    })
}