yamuse 0.2.0

typed async client for the yandex music api: catalogue, likes, playlists, radio, lossless downloads and ynison realtime
Documentation
//! query-string and form-body parameter building.
//!
//! the api takes the same key/value shape in both places, and repeats a key per
//! element for list values (`track-ids=1&track-ids=2`). [`Params`] is the one
//! builder both encodings go through.

use std::fmt::Display;

/// an ordered set of request parameters.
///
/// `None` values are dropped rather than sent empty, matching what the api
/// expects for optional parameters.
#[derive(Debug, Default, Clone)]
pub struct Params {
    pairs: Vec<(String, String)>,
}

impl Params {
    /// start an empty parameter set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// append a parameter.
    #[must_use]
    pub fn add(mut self, key: &str, value: impl Display) -> Self {
        self.pairs.push((key.to_owned(), value.to_string()));
        self
    }

    /// append a parameter only when the value is present.
    #[must_use]
    pub fn maybe(self, key: &str, value: Option<impl Display>) -> Self {
        match value {
            Some(v) => self.add(key, v),
            None => self,
        }
    }

    /// append one entry per element, repeating the key.
    #[must_use]
    pub fn add_all(mut self, key: &str, values: impl IntoIterator<Item = impl Display>) -> Self {
        for value in values {
            self.pairs.push((key.to_owned(), value.to_string()));
        }
        self
    }

    /// whether no parameters were added.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }

    /// the parameters as borrowed key/value pairs, in insertion order.
    pub(crate) fn pairs(&self) -> impl Iterator<Item = (&str, &str)> {
        self.pairs.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }
}

impl FromIterator<(String, String)> for Params {
    fn from_iter<I: IntoIterator<Item = (String, String)>>(iter: I) -> Self {
        Self {
            pairs: iter.into_iter().collect(),
        }
    }
}

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

    fn collect(params: &Params) -> Vec<(String, String)> {
        params
            .pairs()
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect()
    }

    #[test]
    fn insertion_order_is_preserved() {
        let params = Params::new().add("b", 2).add("a", 1).add("c", 3);
        assert_eq!(
            collect(&params),
            vec![
                ("b".into(), "2".into()),
                ("a".into(), "1".into()),
                ("c".into(), "3".into()),
            ]
        );
    }

    #[test]
    fn maybe_drops_absent_values() {
        let params = Params::new()
            .maybe("kept", Some("yes"))
            .maybe("dropped", Option::<&str>::None);
        assert_eq!(collect(&params), vec![("kept".into(), "yes".into())]);
    }

    #[test]
    fn add_all_repeats_the_key_per_element() {
        let params = Params::new().add_all("track-ids", [1, 2, 3]);
        assert_eq!(
            collect(&params),
            vec![
                ("track-ids".into(), "1".into()),
                ("track-ids".into(), "2".into()),
                ("track-ids".into(), "3".into()),
            ]
        );
    }

    #[test]
    fn add_all_over_an_empty_iterator_adds_nothing() {
        assert!(Params::new().add_all("ids", Vec::<i64>::new()).is_empty());
    }

    #[test]
    fn booleans_render_as_the_api_expects() {
        let params = Params::new()
            .add("nocorrect", false)
            .add("with-positions", true);
        assert_eq!(
            collect(&params),
            vec![
                ("nocorrect".into(), "false".into()),
                ("with-positions".into(), "true".into()),
            ]
        );
    }
}