From 1842ebef155610084eb661dd0f71e19a4534b1f6 Mon Sep 17 00:00:00 2001 From: Aram Peres Date: Wed, 4 Aug 2021 02:30:19 -0400 Subject: [PATCH] Add util for joining and splitting words --- rups/src/proto/mod.rs | 2 ++ rups/src/proto/util.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 rups/src/proto/util.rs diff --git a/rups/src/proto/mod.rs b/rups/src/proto/mod.rs index 02f4bb3..15a7509 100644 --- a/rups/src/proto/mod.rs +++ b/rups/src/proto/mod.rs @@ -8,6 +8,8 @@ pub mod client; /// "Server-bound" implies commands RECEIVED and DECODED by the server. The client implementation /// must use the same messages to ENCODE and SEND. pub mod server; +/// Utilities for encoding and decoding packets. +pub mod util; /// Macro that implements the list of "words" in the NUT network protocol. macro_rules! impl_words { diff --git a/rups/src/proto/util.rs b/rups/src/proto/util.rs new file mode 100644 index 0000000..8a9a0fa --- /dev/null +++ b/rups/src/proto/util.rs @@ -0,0 +1,41 @@ +/// Splits a sentence (line) into a `Vec`, minding quotation marks +/// for words with spaces in them. +/// +/// Returns `None` if the sentence cannot be split safely (usually unbalanced quotation marks). +pub fn split_sentence>(sentence: T) -> Option> { + shell_words::split(sentence.as_ref()).ok() +} + +/// Joins a collection of words (`&str`) into one sentence string, +/// adding quotation marks for words with spaces in them. +pub fn join_sentence(words: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + shell_words::join(words) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_split() { + assert_eq!( + split_sentence("AbC dEf GHi"), + Some(vec!["AbC".into(), "dEf".into(), "GHi".into()]) + ); + assert_eq!( + split_sentence("\"AbC dEf\" GHi"), + Some(vec!["AbC dEf".into(), "GHi".into()]) + ); + assert_eq!(split_sentence("\"AbC dEf GHi"), None); + } + + #[test] + fn test_join() { + assert_eq!(join_sentence(vec!["AbC", "dEf", "GHi"]), "AbC dEf GHi",); + assert_eq!(join_sentence(vec!["AbC dEf", "GHi"]), "'AbC dEf' GHi",); + assert_eq!(join_sentence(vec!["\"AbC dEf", "GHi"]), "'\"AbC dEf' GHi",); + } +}