rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! The version of the API that answers, against the newest one the fixtures
//! cover.

use hafas::ResponseInfo;

/// The newest dialect version that the fixtures and tests cover.
pub const TESTED_VERSION: (u32, u32) = (2, 52);

/// A response that says which version answered.
pub(crate) trait Informed {
    fn info(&self) -> &ResponseInfo;
}

macro_rules! informed {
    ($($response:ty),*) => {
        $(impl Informed for $response {
            fn info(&self) -> &ResponseInfo {
                &self.info
            }
        })*
    };
}

informed!(
    hafas::LocationList,
    hafas::DepartureList,
    hafas::ArrivalList,
    hafas::Journey,
    hafas::TripList
);

/// `major.minor` of a version like `2.39.1`.
fn parse(version: &str) -> Option<(u32, u32)> {
    let mut parts = version.trim().split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    Some((major, minor))
}

/// The version of the response, like `2.60`, if it is newer than
/// [`TESTED_VERSION`]. Built from the numbers alone, so no other text of the
/// server gets through.
pub(crate) fn newer(info: &ResponseInfo) -> Option<String> {
    let version = info
        .server_version
        .as_deref()
        .and_then(parse)
        .or_else(|| info.dialect_version.as_deref().and_then(parse))?;
    (version > TESTED_VERSION).then(|| format!("{}.{}", version.0, version.1))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn info(server: Option<&str>, dialect: Option<&str>) -> ResponseInfo {
        ResponseInfo {
            server_version: server.map(str::to_owned),
            dialect_version: dialect.map(str::to_owned),
            ..ResponseInfo::default()
        }
    }

    #[test]
    fn notices_newer_versions_only() {
        assert_eq!(newer(&info(Some("2.39.1"), Some("2.39"))), None);
        assert_eq!(newer(&info(Some("2.52.3"), None)), None);
        assert_eq!(
            newer(&info(Some("2.60.0"), Some("2.39"))),
            Some("2.60".to_owned())
        );
        assert_eq!(newer(&info(None, Some("2.60"))), Some("2.60".to_owned()));
        assert_eq!(
            newer(&info(Some("3.0.1 secret"), None)),
            Some("3.0".to_owned())
        );
        assert_eq!(newer(&info(Some("2"), None)), None);
        assert_eq!(newer(&info(None, None)), None);
    }
}