From 11344993ad1763e152356378577233ea55365816 Mon Sep 17 00:00:00 2001 From: Fenhl Date: Sun, 5 Aug 2018 07:43:39 +0000 Subject: [PATCH] Add `join` convenience function --- src/lib.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 6ff8c97..fe5bf21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -181,6 +181,15 @@ pub fn quote(in_str: &str) -> Cow { } } +/// 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>(words: I) -> String { + words.into_iter() + .map(quote) + .collect::>() + .join(" ") +} + #[cfg(test)] static SPLIT_TEST_ITEMS: &'static [(&'static str, Option<&'static [&'static str]>)] = &[ ("foo$baz", Some(&["foo$baz"])), @@ -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"); +}