1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
use std::str::FromStr;
/// Auxiliary struct for parsing key-value pairs.
pub struct KeyValue<'a, K> {
/// Should be of any type that implements [`FromStr`].
pub key: K,
/// The whitespace-trimmed content after the colon (`:`).
pub value: &'a str,
}
impl<'a, K: FromStr> KeyValue<'a, K> {
/// Create a new [`KeyValue`] pair by splitting on the first `:`
/// and parsing the key.
///
/// # Example
///
/// ```
/// use rosu_map::util::KeyValue;
/// use rosu_map::section::difficulty::DifficultyKey;
///
/// let line = "ApproachRate: 9.3 // Some comment";
///
/// let kv = KeyValue::<DifficultyKey>::parse(line).unwrap();
///
/// assert_eq!(kv.key, DifficultyKey::ApproachRate);
/// assert_eq!(kv.value, "9.3 // Some comment");
/// ```
pub fn parse(s: &'a str) -> Result<Self, K::Err> {
let mut split = s.split(':').map(str::trim);
Ok(Self {
key: split.next().unwrap_or(s.trim()).parse()?,
value: split.next().unwrap_or_default(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq, Eq)]
struct Key;
impl FromStr for Key {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"key" => Ok(Self),
_ => Err(()),
}
}
}
#[test]
fn key_and_value() {
let kv = KeyValue::<Key>::parse("key:value").unwrap();
assert_eq!(kv.key, Key);
assert_eq!(kv.value, "value");
let kv = KeyValue::<Key>::parse(" key : value ").unwrap();
assert_eq!(kv.key, Key);
assert_eq!(kv.value, "value");
}
#[test]
fn only_key() {
let kv = KeyValue::<Key>::parse("key:").unwrap();
assert_eq!(kv.key, Key);
assert_eq!(kv.value, "");
let kv = KeyValue::<Key>::parse(" key : ").unwrap();
assert_eq!(kv.key, Key);
assert_eq!(kv.value, "");
}
#[test]
fn only_value() {
assert!(KeyValue::<Key>::parse(":value").is_err());
assert!(KeyValue::<Key>::parse(" : value ").is_err());
}
#[test]
fn no_colon() {
assert!(KeyValue::<Key>::parse("key value").is_err());
}
}