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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use std::{
    cmp::Ordering,
    collections::{BTreeSet, HashSet},
    hash::{Hash, Hasher},
};

use opentelemetry::{Array, Key, KeyValue, Value};
use ordered_float::OrderedFloat;

use crate::Resource;

#[derive(Clone, Debug)]
struct HashKeyValue(KeyValue);

impl Hash for HashKeyValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.key.hash(state);
        match &self.0.value {
            Value::F64(f) => OrderedFloat(*f).hash(state),
            Value::Array(a) => match a {
                Array::Bool(b) => b.hash(state),
                Array::I64(i) => i.hash(state),
                Array::F64(f) => f.iter().for_each(|f| OrderedFloat(*f).hash(state)),
                Array::String(s) => s.hash(state),
            },
            Value::Bool(b) => b.hash(state),
            Value::I64(i) => i.hash(state),
            Value::String(s) => s.hash(state),
        };
    }
}

impl PartialOrd for HashKeyValue {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for HashKeyValue {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.0.key.cmp(&other.0.key) {
            Ordering::Equal => match type_order(&self.0.value).cmp(&type_order(&other.0.value)) {
                Ordering::Equal => match (&self.0.value, &other.0.value) {
                    (Value::F64(f), Value::F64(of)) => OrderedFloat(*f).cmp(&OrderedFloat(*of)),
                    (Value::Array(Array::Bool(b)), Value::Array(Array::Bool(ob))) => b.cmp(ob),
                    (Value::Array(Array::I64(i)), Value::Array(Array::I64(oi))) => i.cmp(oi),
                    (Value::Array(Array::String(s)), Value::Array(Array::String(os))) => s.cmp(os),
                    (Value::Array(Array::F64(f)), Value::Array(Array::F64(of))) => {
                        match f.len().cmp(&of.len()) {
                            Ordering::Equal => f
                                .iter()
                                .map(|x| OrderedFloat(*x))
                                .collect::<Vec<_>>()
                                .cmp(&of.iter().map(|x| OrderedFloat(*x)).collect()),
                            other => other,
                        }
                    }
                    (Value::Bool(b), Value::Bool(ob)) => b.cmp(ob),
                    (Value::I64(i), Value::I64(oi)) => i.cmp(oi),
                    (Value::String(s), Value::String(os)) => s.cmp(os),
                    _ => Ordering::Equal,
                },
                other => other, // 2nd order by value types
            },
            other => other, // 1st order by key
        }
    }
}

fn type_order(v: &Value) -> u8 {
    match v {
        Value::Bool(_) => 1,
        Value::I64(_) => 2,
        Value::F64(_) => 3,
        Value::String(_) => 4,
        Value::Array(a) => match a {
            Array::Bool(_) => 5,
            Array::I64(_) => 6,
            Array::F64(_) => 7,
            Array::String(_) => 8,
        },
    }
}

impl PartialEq for HashKeyValue {
    fn eq(&self, other: &Self) -> bool {
        self.0.key == other.0.key
            && match (&self.0.value, &other.0.value) {
                (Value::F64(f), Value::F64(of)) => OrderedFloat(*f).eq(&OrderedFloat(*of)),
                (Value::Array(Array::F64(f)), Value::Array(Array::F64(of))) => {
                    f.len() == of.len()
                        && f.iter()
                            .zip(of.iter())
                            .all(|(f, of)| OrderedFloat(*f).eq(&OrderedFloat(*of)))
                }
                (non_float, other_non_float) => non_float.eq(other_non_float),
            }
    }
}

impl Eq for HashKeyValue {}

/// A unique set of attributes that can be used as instrument identifiers.
///
/// This must implement [Hash], [PartialEq], and [Eq] so it may be used as
/// HashMap keys and other de-duplication methods.
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq)]
pub struct AttributeSet(BTreeSet<HashKeyValue>);

impl From<&[KeyValue]> for AttributeSet {
    fn from(values: &[KeyValue]) -> Self {
        let mut seen = HashSet::with_capacity(values.len());
        AttributeSet(
            values
                .iter()
                .rev()
                .filter_map(|kv| {
                    if seen.contains(&&kv.key) {
                        None
                    } else {
                        seen.insert(&kv.key);
                        Some(HashKeyValue(kv.clone()))
                    }
                })
                .collect(),
        )
    }
}

impl From<&Resource> for AttributeSet {
    fn from(values: &Resource) -> Self {
        AttributeSet(
            values
                .iter()
                .map(|(key, value)| HashKeyValue(KeyValue::new(key.clone(), value.clone())))
                .collect(),
        )
    }
}

impl AttributeSet {
    /// Returns the number of elements in the set.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if the set contains no elements.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Retains only the attributes specified by the predicate.
    pub fn retain<F>(&mut self, f: F)
    where
        F: Fn(&KeyValue) -> bool,
    {
        self.0.retain(|kv| f(&kv.0))
    }

    /// Iterate over key value pairs in the set
    pub fn iter(&self) -> impl Iterator<Item = (&Key, &Value)> {
        self.0.iter().map(|kv| (&kv.0.key, &kv.0.value))
    }
}