use crate::directions::error::Error as DirectionsError;
use crate::error::Error as GoogleMapsError;
use phf::phf_map;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum Avoid {
Ferries = 0,
Highways = 1,
Indoor = 2,
#[default]
Tolls = 3,
}
impl<'de> Deserialize<'de> for Avoid {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let string = String::deserialize(deserializer)?;
match Self::try_from(string.as_str()) {
Ok(variant) => Ok(variant),
Err(error) => Err(serde::de::Error::custom(error.to_string())),
} } }
impl Serialize for Avoid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(std::convert::Into::<&str>::into(self))
} }
impl std::convert::From<&Avoid> for &str {
fn from(avoid: &Avoid) -> Self {
match avoid {
Avoid::Ferries => "ferries",
Avoid::Highways => "highways",
Avoid::Indoor => "indoor",
Avoid::Tolls => "tolls",
} } }
impl std::fmt::Display for Avoid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", std::convert::Into::<&str>::into(self))
} }
impl std::convert::From<&Self> for Avoid {
fn from(avoid: &Self) -> Self {
avoid.clone()
} }
impl std::convert::From<&Avoid> for String {
fn from(avoid: &Avoid) -> Self {
std::convert::Into::<&str>::into(avoid).to_string()
} }
static RESTRICTIONS_BY_CODE: phf::Map<&'static str, Avoid> = phf_map! {
"ferries" => Avoid::Ferries,
"highways" => Avoid::Highways,
"indoor" => Avoid::Indoor,
"tolls" => Avoid::Tolls,
};
impl std::convert::TryFrom<&str> for Avoid {
type Error = GoogleMapsError;
fn try_from(restriction_code: &str) -> Result<Self, Self::Error> {
Ok(RESTRICTIONS_BY_CODE
.get(restriction_code)
.cloned()
.ok_or_else(|| DirectionsError::InvalidAvoidCode(restriction_code.to_string()))?)
} }
impl std::str::FromStr for Avoid {
type Err = GoogleMapsError;
fn from_str(restriction_code: &str) -> Result<Self, Self::Err> {
Ok(RESTRICTIONS_BY_CODE
.get(restriction_code)
.cloned()
.ok_or_else(|| DirectionsError::InvalidAvoidCode(restriction_code.to_string()))?)
} }
impl Avoid {
#[must_use]
pub const fn display(&self) -> &str {
match self {
Self::Ferries => "Ferries",
Self::Highways => "Highways",
Self::Indoor => "Indoor",
Self::Tolls => "Tolls",
} } }