mirror of
https://github.com/aramperes/nut-rs.git
synced 2025-09-09 05:28:31 -04:00
Add util for joining and splitting words
This commit is contained in:
parent
1e3481e18d
commit
1842ebef15
2 changed files with 43 additions and 0 deletions
|
@ -8,6 +8,8 @@ pub mod client;
|
||||||
/// "Server-bound" implies commands RECEIVED and DECODED by the server. The client implementation
|
/// "Server-bound" implies commands RECEIVED and DECODED by the server. The client implementation
|
||||||
/// must use the same messages to ENCODE and SEND.
|
/// must use the same messages to ENCODE and SEND.
|
||||||
pub mod server;
|
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 that implements the list of "words" in the NUT network protocol.
|
||||||
macro_rules! impl_words {
|
macro_rules! impl_words {
|
||||||
|
|
41
rups/src/proto/util.rs
Normal file
41
rups/src/proto/util.rs
Normal 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",);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue