Add util for joining and splitting words

This commit is contained in:
Aram 🍐 2021-08-04 02:30:19 -04:00
parent 1e3481e18d
commit 1842ebef15
2 changed files with 43 additions and 0 deletions

View file

@ -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 {

41
rups/src/proto/util.rs Normal file
View file

@ -0,0 +1,41 @@
/// Splits a sentence (line) into a `Vec<String>`, 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<T: AsRef<str>>(sentence: T) -> Option<Vec<String>> {
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<I, S>(words: I) -> String
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
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",);
}
}