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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::borrow::Cow;
use std::collections::{btree_map, BTreeMap};
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct MetricId {
name: Cow<'static, str>,
tags: Tags,
}
impl MetricId {
pub fn new<T>(name: T) -> MetricId
where
T: Into<Cow<'static, str>>,
{
MetricId {
name: name.into(),
tags: Tags(BTreeMap::new()),
}
}
pub fn with_tag<K, V>(mut self, key: K, value: V) -> MetricId
where
K: Into<Cow<'static, str>>,
V: Into<Cow<'static, str>>,
{
self.tags.0.insert(key.into(), value.into());
self
}
#[inline]
pub fn name(&self) -> &str {
&self.name
}
#[inline]
pub fn tags(&self) -> &Tags {
&self.tags
}
}
impl From<String> for MetricId {
#[inline]
fn from(s: String) -> Self {
MetricId::new(s)
}
}
impl From<&'static str> for MetricId {
#[inline]
fn from(s: &'static str) -> Self {
MetricId::new(s)
}
}
impl From<Cow<'static, str>> for MetricId {
#[inline]
fn from(s: Cow<'static, str>) -> MetricId {
MetricId::new(s)
}
}
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Tags(BTreeMap<Cow<'static, str>, Cow<'static, str>>);
impl Tags {
#[inline]
pub fn iter(&self) -> TagsIter<'_> {
TagsIter(self.0.iter())
}
}
impl<'a> IntoIterator for &'a Tags {
type Item = (&'a str, &'a str);
type IntoIter = TagsIter<'a>;
#[inline]
fn into_iter(self) -> TagsIter<'a> {
self.iter()
}
}
pub struct TagsIter<'a>(btree_map::Iter<'a, Cow<'static, str>, Cow<'static, str>>);
impl<'a> Iterator for TagsIter<'a> {
type Item = (&'a str, &'a str);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(k, v)| (&**k, &**v))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<'a> ExactSizeIterator for TagsIter<'a> {}
#[cfg(test)]
mod test {
use crate::MetricId;
#[test]
fn basic() {
let id = MetricId::new("foo.bar")
.with_tag("a", "b")
.with_tag("fizz", "buzz")
.with_tag("fizz", "bazz");
assert_eq!(id.name(), "foo.bar");
assert_eq!(
id.tags().iter().collect::<Vec<_>>(),
&[("a", "b"), ("fizz", "bazz")]
);
}
}