use std::fmt;
macro_rules! string_enum {
(
$(#[$meta:meta])*
$name:ident {
$( $(#[$vmeta:meta])* $variant:ident = $value:literal, )+
}
) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(from = "String", into = "String")]
pub enum $name {
$( $(#[$vmeta])* $variant, )+
Other(String),
}
impl $name {
pub const KNOWN: &'static [&'static str] = &[$($value),+];
const VARIANTS: &'static [Self] = &[$(Self::$variant),+];
pub fn as_str(&self) -> &str {
match self {
$( Self::$variant => $value, )+
Self::Other(value) => value,
}
}
}
impl Default for $name {
fn default() -> Self {
Self::VARIANTS[0].clone()
}
}
impl From<String> for $name {
fn from(value: String) -> Self {
let known = Self::VARIANTS.iter().find(|known| known.as_str() == value);
known.cloned().unwrap_or(Self::Other(value))
}
}
impl From<$name> for String {
fn from(value: $name) -> Self {
match value {
$name::Other(value) => value,
known => known.as_str().to_owned(),
}
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
};
}
string_enum! {
JourneyStatus {
Planned = "P",
Replacement = "R",
Additional = "A",
Special = "S",
}
}
string_enum! {
PrognosisType {
Prognosed = "PROGNOSED",
Manual = "MANUAL",
Reported = "REPORTED",
Corrected = "CORRECTED",
Calculated = "CALCULATED",
}
}
string_enum! {
PlatformKind {
Unknown = "U",
Platform = "PL",
Stand = "ST",
Gate = "GA",
Pier = "PI",
Slot = "SL",
Floor = "FL",
CheckIn = "CI",
CheckOut = "CO",
Miscellaneous = "X",
Hidden = "H",
}
}
string_enum! {
LocationKind {
Stop = "ST",
Address = "ADR",
Poi = "POI",
Coordinate = "CRD",
Mcp = "MCP",
Hailing = "HL",
}
}
string_enum! {
RtMode {
ServerDefault = "SERVER_DEFAULT",
Full = "FULL",
Realtime = "REALTIME",
Infos = "INFOS",
Off = "OFF",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_unknown_values() {
let status: JourneyStatus = serde_json::from_str(r#""Z""#).unwrap();
assert_eq!(status, JourneyStatus::Other("Z".to_owned()));
assert_eq!(status.as_str(), "Z");
assert_eq!(serde_json::to_string(&status).unwrap(), r#""Z""#);
}
#[test]
fn spells_known_values_like_the_api() {
assert_eq!(RtMode::Realtime.to_string(), "REALTIME");
assert_eq!(String::from(PlatformKind::Platform), "PL");
assert_eq!(LocationKind::default(), LocationKind::Stop);
assert_eq!(
PrognosisType::from("MANUAL".to_owned()),
PrognosisType::Manual
);
}
}