Skip to main content

polyoxide_core/
query.rs

1//! Comma-joined query values.
2
3/// Comma-joins a multi-value query parameter; `None` when the joined value is
4/// empty, so the parameter is omitted rather than sent empty.
5///
6/// ```
7/// assert_eq!(polyoxide_core::csv(["a", "b"]), Some("a,b".to_owned()));
8/// assert_eq!(polyoxide_core::csv(Vec::<String>::new()), None);
9/// assert_eq!(polyoxide_core::csv([""]), None);
10/// ```
11pub fn csv<I, S>(values: I) -> Option<String>
12where
13    I: IntoIterator<Item = S>,
14    S: ToString,
15{
16    let joined = values
17        .into_iter()
18        .map(|v| v.to_string())
19        .collect::<Vec<String>>()
20        .join(",");
21    (!joined.is_empty()).then_some(joined)
22}
23
24#[cfg(test)]
25mod tests {
26    use super::csv;
27
28    #[test]
29    fn csv_joins_values_with_commas() {
30        assert_eq!(csv(["0xa", "0xb"]), Some("0xa,0xb".to_owned()));
31        assert_eq!(csv([7, 8]), Some("7,8".to_owned()));
32    }
33
34    #[test]
35    fn csv_of_nothing_is_none_so_the_parameter_is_omitted() {
36        assert_eq!(csv(Vec::<String>::new()), None);
37    }
38}