Split String->key-value with types

This commit is contained in:
Matthias Beyer 2016-01-20 10:37:24 +01:00
parent 77204c8e22
commit 2c5d61c456

View file

@ -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)]