Skip to content

Commit

Permalink
Add join convenience function
Browse files Browse the repository at this point in the history
  • Loading branch information
fenhl committed Aug 5, 2018
1 parent 95ef696 commit 1134499
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,15 @@ pub fn quote(in_str: &str) -> Cow<str> {
}
}

/// Convenience function that consumes an iterable of words and turns it into a single string,
/// quoting words when necessary. Consecutive words will be separated by a single space.
pub fn join<'a, I: IntoIterator<Item = &'a str>>(words: I) -> String {
words.into_iter()
.map(quote)
.collect::<Vec<_>>()
.join(" ")
}

#[cfg(test)]
static SPLIT_TEST_ITEMS: &'static [(&'static str, Option<&'static [&'static str]>)] = &[
("foo$baz", Some(&["foo$baz"])),
Expand Down Expand Up @@ -227,3 +236,11 @@ fn test_quote() {
assert_eq!(quote("\""), "\"\\\"\"");
assert_eq!(quote(""), "\"\"");
}

#[test]
fn test_join() {
assert_eq!(join(vec![]), "");
assert_eq!(join(vec![""]), "\"\"");
assert_eq!(join(vec!["a", "b"]), "a b");
assert_eq!(join(vec!["foo bar", "baz"]), "\"foo bar\" baz");
}

0 comments on commit 1134499

Please sign in to comment.