use crate::error::Error as GoogleMapsError;
use crate::places::error::Error as PlacesError;
use phf::phf_map;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Debug, Eq, Default, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum RankBy {
#[default]
Prominence = 0,
Distance = 1,
}
impl<'de> Deserialize<'de> for RankBy {
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 RankBy {
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<&RankBy> for &str {
fn from(hours_type: &RankBy) -> Self {
match hours_type {
RankBy::Prominence => "prominence",
RankBy::Distance => "distance",
} } }
impl std::fmt::Display for RankBy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", std::convert::Into::<&str>::into(self))
} }
impl std::convert::From<&RankBy> for String {
fn from(secondary_hours_type: &RankBy) -> Self {
std::convert::Into::<&str>::into(secondary_hours_type).to_string()
} }
static STATUSES_BY_CODE: phf::Map<&'static str, RankBy> = phf_map! {
"prominence" => RankBy::Prominence,
"distance" => RankBy::Distance,
};
impl std::convert::TryFrom<&str> for RankBy {
type Error = GoogleMapsError;
fn try_from(hours_type: &str) -> Result<Self, Self::Error> {
Ok(STATUSES_BY_CODE
.get(hours_type)
.cloned()
.ok_or_else(|| PlacesError::InvalidRankByCode(hours_type.to_string()))?)
} }
impl std::str::FromStr for RankBy {
type Err = GoogleMapsError;
fn from_str(hours_type: &str) -> Result<Self, Self::Err> {
Ok(STATUSES_BY_CODE
.get(hours_type)
.cloned()
.ok_or_else(|| PlacesError::InvalidRankByCode(hours_type.to_string()))?)
} }
impl RankBy {
#[must_use]
pub const fn display(&self) -> &str {
match self {
Self::Prominence => "Prominence",
Self::Distance => "Distance",
} } }