use std::fmt::Display;
#[derive(Debug, Default, Clone)]
pub struct Params {
pairs: Vec<(String, String)>,
}
impl Params {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn add(mut self, key: &str, value: impl Display) -> Self {
self.pairs.push((key.to_owned(), value.to_string()));
self
}
#[must_use]
pub fn maybe(self, key: &str, value: Option<impl Display>) -> Self {
match value {
Some(v) => self.add(key, v),
None => self,
}
}
#[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
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
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(¶ms),
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(¶ms), 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(¶ms),
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(¶ms),
vec![
("nocorrect".into(), "false".into()),
("with-positions".into(), "true".into()),
]
);
}
}