Skip to main content

rmv_core/
version.rs

1//! The version of the API that answers, against the newest one the fixtures
2//! cover.
3
4use hafas::ResponseInfo;
5
6/// The newest dialect version that the fixtures and tests cover.
7pub const TESTED_VERSION: (u32, u32) = (2, 52);
8
9/// A response that says which version answered.
10pub(crate) trait Informed {
11    fn info(&self) -> &ResponseInfo;
12}
13
14macro_rules! informed {
15    ($($response:ty),*) => {
16        $(impl Informed for $response {
17            fn info(&self) -> &ResponseInfo {
18                &self.info
19            }
20        })*
21    };
22}
23
24informed!(
25    hafas::LocationList,
26    hafas::DepartureList,
27    hafas::ArrivalList,
28    hafas::Journey,
29    hafas::TripList
30);
31
32/// `major.minor` of a version like `2.39.1`.
33fn parse(version: &str) -> Option<(u32, u32)> {
34    let mut parts = version.trim().split('.');
35    let major = parts.next()?.parse().ok()?;
36    let minor = parts.next()?.parse().ok()?;
37    Some((major, minor))
38}
39
40/// The version of the response, like `2.60`, if it is newer than
41/// [`TESTED_VERSION`]. Built from the numbers alone, so no other text of the
42/// server gets through.
43pub(crate) fn newer(info: &ResponseInfo) -> Option<String> {
44    let version = info
45        .server_version
46        .as_deref()
47        .and_then(parse)
48        .or_else(|| info.dialect_version.as_deref().and_then(parse))?;
49    (version > TESTED_VERSION).then(|| format!("{}.{}", version.0, version.1))
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    fn info(server: Option<&str>, dialect: Option<&str>) -> ResponseInfo {
57        ResponseInfo {
58            server_version: server.map(str::to_owned),
59            dialect_version: dialect.map(str::to_owned),
60            ..ResponseInfo::default()
61        }
62    }
63
64    #[test]
65    fn notices_newer_versions_only() {
66        assert_eq!(newer(&info(Some("2.39.1"), Some("2.39"))), None);
67        assert_eq!(newer(&info(Some("2.52.3"), None)), None);
68        assert_eq!(
69            newer(&info(Some("2.60.0"), Some("2.39"))),
70            Some("2.60".to_owned())
71        );
72        assert_eq!(newer(&info(None, Some("2.60"))), Some("2.60".to_owned()));
73        assert_eq!(
74            newer(&info(Some("3.0.1 secret"), None)),
75            Some("3.0".to_owned())
76        );
77        assert_eq!(newer(&info(Some("2"), None)), None);
78        assert_eq!(newer(&info(None, None)), None);
79    }
80}