Split String->key-value with types
This commit is contained in:
parent
77204c8e22
commit
2c5d61c456
1 changed files with 47 additions and 12 deletions
|
@ -1,17 +1,52 @@
|
|||
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)
|
||||
})
|
||||
use std::convert::Into;
|
||||
use std::convert::From;
|
||||
|
||||
use std::option::Option;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct KeyValue<K, V> {
|
||||
k: K,
|
||||
v: V,
|
||||
}
|
||||
|
||||
impl<K, V> KeyValue<K, V> {
|
||||
|
||||
pub fn new(k: K, v: V) -> KeyValue<K, V> {
|
||||
KeyValue { k: k, v: v }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl<K, V> Into<(K, V)> for KeyValue<K, V> {
|
||||
|
||||
fn into(self) -> (K, V) {
|
||||
(self.k, self.v)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
pub trait IntoKeyValue<K, V> {
|
||||
fn into_kv(self) -> Option<KeyValue<K, V>>;
|
||||
}
|
||||
|
||||
impl IntoKeyValue<String, String> for String {
|
||||
|
||||
fn into_kv(self) -> Option<KeyValue<String, String>> {
|
||||
let r = "^(?P<KEY>(.*))=((\"(?P<DOUBLE_QVAL>(.*))\")|(\'(?P<SINGLE_QVAL>(.*)))\'|(?P<VAL>[^\'\"](.*)[^\'\"]))$";
|
||||
let regex = Regex::new(r).unwrap();
|
||||
regex.captures(&self[..]).and_then(|cap| {
|
||||
cap.name("KEY")
|
||||
.map(|name| {
|
||||
cap.name("SINGLE_QVAL")
|
||||
.or(cap.name("DOUBLE_QVAL"))
|
||||
.or(cap.name("VAL"))
|
||||
.map(|value| KeyValue::new(String::from(name), String::from(value)))
|
||||
}).unwrap_or(None)
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
Loading…
Reference in a new issue