prometheus_wire/parser/
label.rs1use std::collections::HashMap;
2use std::str::FromStr;
3
4#[derive(Debug, PartialEq)]
6pub struct LabelList(HashMap<String, String>);
7
8impl LabelList {
9 pub fn new() -> Self {
10 LabelList(HashMap::new())
11 }
12
13 pub fn from_map(h: HashMap<String, String>) -> Self {
14 LabelList(h)
15 }
16
17 pub fn get_string(&self, key: &str) -> Option<&String> {
19 self.0.get(key)
20 }
21
22 pub fn get_number(&self, key: &str) -> Option<f64> {
24 self.0.get(key).and_then(|s| match s.as_str() {
25 "+Inf" => Some(f64::INFINITY),
26 "-Inf" => Some(f64::NEG_INFINITY),
27 s => f64::from_str(&s).ok(),
28 })
29 }
30}
31
32impl Default for LabelList {
33 fn default() -> Self {
34 Self::new()
35 }
36}
37impl From<Vec<(&str, String)>> for LabelList {
38 fn from(input: Vec<(&str, String)>) -> Self {
39 let mut map = HashMap::with_capacity(input.len());
40
41 for (key, value) in input {
42 map.insert(key.to_string(), value);
43 }
44
45 LabelList(map)
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use crate::parser::label::LabelList;
52 use std::collections::HashMap;
53
54 #[test]
55 fn test_get_float() {
56 let mut m = HashMap::new();
57 m.insert("test1".into(), "1.5e-03".into());
58 m.insert("test2".into(), "-1.7560473e+07".into());
59 m.insert("test3".into(), "+Inf".into());
60 m.insert("test4".into(), "-Inf".into());
61 m.insert("test5".into(), "alfa".into());
62 m.insert("test6".into(), "".into());
63
64 let l = LabelList::from_map(m);
65
66 assert_eq!(l.get_number("test1"), Some(0.0015));
67 assert_eq!(l.get_number("test2"), Some(-17560473.0));
68 assert_eq!(l.get_number("test3"), Some(f64::INFINITY));
69 assert_eq!(l.get_number("test4"), Some(f64::NEG_INFINITY));
70 assert_eq!(l.get_number("test5"), None);
71 assert_eq!(l.get_number("test6"), None);
72 }
73}