diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2016-01-20 09:42:48 +0100 |
---|---|---|
committer | Matthias Beyer <mail@beyermatthias.de> | 2016-01-20 09:42:48 +0100 |
commit | 77204c8e22d7243c5a261ff080ebf66277214f6f (patch) | |
tree | 10e5c3143d8046fe1966959b41d3975694558f40 /libimagutil | |
parent | 9b77ae13486169be554f1d392abe11deadd5cff7 (diff) |
Add key-value-splitter helper
Diffstat (limited to 'libimagutil')
-rw-r--r-- | libimagutil/src/key_value_split.rs | 53 | ||||
-rw-r--r-- | libimagutil/src/lib.rs | 1 |
2 files changed, 54 insertions, 0 deletions
diff --git a/libimagutil/src/key_value_split.rs b/libimagutil/src/key_value_split.rs new file mode 100644 index 00000000..a00bd2db --- /dev/null +++ b/libimagutil/src/key_value_split.rs @@ -0,0 +1,53 @@ +use regex::Regex; + +pub fn split_into_key_value(s: String) -> Option<(String, String)> { + let r = "^(?P<KEY>(.*))=((\"(?P<DOUBLE_QVAL>(.*))\")|(\'(?P<SINGLE_QVAL>(.*)))\'|(?P<VAL>[^\'\"](.*)[^\'\"]))$"; + let regex = Regex::new(r).unwrap(); + regex.captures(&s[..]).and_then(|cap| { + cap.name("KEY") + .map(|name| { + cap.name("SINGLE_QVAL") + .or(cap.name("DOUBLE_QVAL")) + .or(cap.name("VAL")) + .map(|value| (String::from(name), String::from(value))) + }).unwrap_or(None) + }) +} + +#[cfg(test)] +mod test { + use super::split_into_key_value; + + #[test] + fn test_single_quoted() { + let s = String::from("foo='bar'"); + assert_eq!(Some((String::from("foo"), String::from("bar"))), split_into_key_value(s)); + } + + #[test] + fn test_double_quoted() { + let s = String::from("foo=\"bar\""); + assert_eq!(Some((String::from("foo"), String::from("bar"))), split_into_key_value(s)); + } + + #[test] + fn test_double_and_single_quoted() { + let s = String::from("foo=\"bar\'"); + assert!(split_into_key_value(s).is_none()); + } + + #[test] + fn test_single_and_double_quoted() { + let s = String::from("foo=\'bar\""); + assert!(split_into_key_value(s).is_none()); + } + + #[test] + fn test_not_quoted() { + let s = String::from("foo=bar"); + assert_eq!(Some((String::from("foo"), String::from("bar"))), split_into_key_value(s)); + } + +} + + diff --git a/libimagutil/src/lib.rs b/libimagutil/src/lib.rs index 0fb164de..d26e1d7e 100644 --- a/libimagutil/src/lib.rs +++ b/libimagutil/src/lib.rs @@ -1,3 +1,4 @@ extern crate regex; +pub mod key_value_split; pub mod variants; |