hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
//! Lists in the JSON of HAFAS.
//!
//! The JSON is a mapping of the XML schema. An element that may repeat comes
//! as an array, but some servers send a single object where there is only
//! one, and they leave out empty lists or send `null`. Lists of the schema
//! that have their own element, like `Notes` with `Note` inside, come as an
//! object around the array: [`wrapped!`] unwraps them.

use serde::{Deserialize, Deserializer};

#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMany<T> {
    Many(Vec<T>),
    One(T),
}

/// Reads an array, a single value as an array of one, and `null` as empty.
pub(crate) fn one_or_many<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    Ok(match Option::<OneOrMany<T>>::deserialize(deserializer)? {
        None => Vec::new(),
        Some(OneOrMany::Many(items)) => items,
        Some(OneOrMany::One(item)) => vec![item],
    })
}

/// Defines a module for `#[serde(with = "...")]` that reads and writes a
/// list wrapped in an object, like `{"Note": [...]}`.
macro_rules! wrapped {
    ($module:ident, $inner:literal) => {
        pub(crate) mod $module {
            use serde::{Deserialize, Deserializer, Serialize, Serializer};

            #[derive(Serialize)]
            struct Out<'a, T> {
                #[serde(rename = $inner)]
                items: &'a [T],
            }

            #[derive(Deserialize)]
            #[serde(bound = "T: Deserialize<'de>")]
            struct In<T> {
                #[serde(rename = $inner, default, deserialize_with = "crate::list::one_or_many")]
                items: Vec<T>,
            }

            pub(crate) fn serialize<S: Serializer, T: Serialize>(
                items: &[T],
                serializer: S,
            ) -> Result<S::Ok, S::Error> {
                Out { items }.serialize(serializer)
            }

            pub(crate) fn deserialize<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
                deserializer: D,
            ) -> Result<Vec<T>, D::Error> {
                Ok(Option::<In<T>>::deserialize(deserializer)?
                    .map(|list| list.items)
                    .unwrap_or_default())
            }
        }
    };
}

wrapped!(notes, "Note");
wrapped!(messages, "Message");
wrapped!(location_notes, "LocationNote");
wrapped!(stops, "Stop");
wrapped!(legs, "Leg");
wrapped!(names, "Name");
wrapped!(directions, "Direction");

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
    struct Holder {
        #[serde(default, deserialize_with = "super::one_or_many")]
        list: Vec<u32>,
        #[serde(rename = "Notes", default, with = "super::notes")]
        notes: Vec<u32>,
    }

    fn read(json: &str) -> Holder {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn reads_arrays_single_values_and_nothing() {
        assert_eq!(read(r#"{"list":[1,2]}"#).list, [1, 2]);
        assert_eq!(read(r#"{"list":3}"#).list, [3]);
        assert_eq!(read(r#"{"list":null}"#).list, Vec::<u32>::new());
        assert_eq!(read("{}"), Holder::default());
    }

    #[test]
    fn unwraps_lists_in_their_own_element() {
        assert_eq!(read(r#"{"Notes":{"Note":[1,2]}}"#).notes, [1, 2]);
        assert_eq!(read(r#"{"Notes":{"Note":4}}"#).notes, [4]);
        assert_eq!(read(r#"{"Notes":{}}"#).notes, Vec::<u32>::new());
        assert_eq!(read(r#"{"Notes":null}"#).notes, Vec::<u32>::new());
    }

    #[test]
    fn writes_them_back_in_the_same_form() {
        let holder = Holder {
            list: vec![1],
            notes: vec![2],
        };
        let json = serde_json::to_string(&holder).unwrap();
        assert_eq!(json, r#"{"list":[1],"Notes":{"Note":[2]}}"#);
        assert_eq!(read(&json), holder);
    }
}