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,19 +1,54 @@
|
|||
use regex::Regex;
|
||||
|
||||
pub fn split_into_key_value(s: String) -> Option<(String, String)> {
|
||||
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(&s[..]).and_then(|cap| {
|
||||
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| (String::from(name), String::from(value)))
|
||||
.map(|value| KeyValue::new(String::from(name), String::from(value)))
|
||||
}).unwrap_or(None)
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::split_into_key_value;
|
||||
|
|
Loading…
Reference in a new issue