hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
//! The string enums of the API.
//!
//! Every enum keeps values it does not know in `Other`, so a newer server
//! does not break decoding.

use std::fmt;

/// Defines an enum of API strings with an `Other(String)` fallback. The first
/// variant is the default.
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, )+
            /// A value this version of the crate does not know.
            Other(String),
        }

        impl $name {
            /// The values this version of the crate knows, as the API spells them.
            pub const KNOWN: &'static [&'static str] = &[$($value),+];

            /// The variants that stand for [`Self::KNOWN`], in that order.
            const VARIANTS: &'static [Self] = &[$(Self::$variant),+];

            /// The value as the API spells it.
            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! {
    /// What kind of journey a departure, an arrival or a leg is
    /// (`JourneyStatusType`).
    JourneyStatus {
        /// In the timetable.
        Planned = "P",
        /// Replaces a journey of the timetable.
        Replacement = "R",
        /// Runs in addition to the timetable.
        Additional = "A",
        /// A special journey.
        Special = "S",
    }
}

string_enum! {
    /// Where a real-time time comes from (`PrognosisType`).
    PrognosisType {
        Prognosed = "PROGNOSED",
        Manual = "MANUAL",
        Reported = "REPORTED",
        Corrected = "CORRECTED",
        Calculated = "CALCULATED",
    }
}

string_enum! {
    /// What a platform text names (`PlatformTypeType`).
    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! {
    /// What kind of place a location is: a stop, an address, a point of
    /// interest or a coordinate.
    LocationKind {
        Stop = "ST",
        Address = "ADR",
        Poi = "POI",
        Coordinate = "CRD",
        Mcp = "MCP",
        Hailing = "HL",
    }
}

string_enum! {
    /// How much real-time data a search takes into account (`rtMode`).
    RtMode {
        ServerDefault = "SERVER_DEFAULT",
        /// Real-time data for the search and the times.
        Full = "FULL",
        /// Real-time data for the times, the search uses the timetable.
        Realtime = "REALTIME",
        /// Only messages, no real-time times.
        Infos = "INFOS",
        /// No real-time data.
        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
        );
    }
}