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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! `TracedValues` and closely related types.

use serde::{
    de::{MapAccess, Visitor},
    ser::SerializeMap,
    Deserialize, Deserializer, Serialize, Serializer,
};
use tracing_core::{
    field::{Field, ValueSet, Visit},
    span::Record,
    Event,
};

use core::{fmt, mem, ops, slice};

use crate::{
    alloc::{vec, String, Vec},
    TracedValue,
};

/// Collection of named [`TracedValue`]s.
///
/// Functionally this collection is similar to a `HashMap<S, TracedValue>`,
/// with the key difference being that the order of [iteration](Self::iter()) is the insertion order.
/// If a value is updated, including via [`Extend`] etc., it preserves its old placement.
#[derive(Clone)]
pub struct TracedValues<S> {
    // Using `Vec` for entries is inefficient for random access, but seems acceptable given that
    // valid value sets have no more than 32 values. We need this (vs using `linked_hash_map`)
    // for no-std compatibility.
    inner: Vec<(S, TracedValue)>,
}

impl<S> Default for TracedValues<S> {
    fn default() -> Self {
        Self { inner: Vec::new() }
    }
}

impl<S: AsRef<str>> fmt::Debug for TracedValues<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = formatter.debug_map();
        for (name, value) in &self.inner {
            map.entry(&name.as_ref(), value);
        }
        map.finish()
    }
}

impl<S: From<&'static str> + AsRef<str>> TracedValues<S> {
    /// Creates traced values from the specified value set.
    pub fn from_values(values: &ValueSet<'_>) -> Self {
        let mut visitor = TracedValueVisitor {
            values: Self::default(),
        };
        values.record(&mut visitor);
        visitor.values
    }

    /// Creates traced values from the specified record.
    pub fn from_record(values: &Record<'_>) -> Self {
        let mut visitor = TracedValueVisitor {
            values: Self::default(),
        };
        values.record(&mut visitor);
        visitor.values
    }

    /// Creates traced values from the values in the specified event.
    pub fn from_event(event: &Event<'_>) -> Self {
        let mut visitor = TracedValueVisitor {
            values: Self::default(),
        };
        event.record(&mut visitor);
        visitor.values
    }
}

impl<S: AsRef<str>> TracedValues<S> {
    /// Creates new empty values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of stored values.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Checks whether this collection of values is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the value with the specified name, or `None` if it not set.
    pub fn get(&self, name: &str) -> Option<&TracedValue> {
        self.inner.iter().find_map(|(existing_name, value)| {
            if existing_name.as_ref() == name {
                Some(value)
            } else {
                None
            }
        })
    }

    /// Iterates over the contained name-value pairs.
    pub fn iter(&self) -> TracedValuesIter<'_, S> {
        TracedValuesIter {
            inner: self.inner.iter(),
        }
    }

    /// Inserts a value with the specified name. If a value with the same name was present
    /// previously, it is overwritten. Returns the previous value with the specified name,
    /// if any.
    pub fn insert(&mut self, name: S, value: TracedValue) -> Option<TracedValue> {
        let position = self
            .inner
            .iter()
            .position(|(existing_name, _)| existing_name.as_ref() == name.as_ref());
        if let Some(position) = position {
            let place = &mut self.inner[position].1;
            Some(mem::replace(place, value))
        } else {
            self.inner.push((name, value));
            None
        }
    }
}

impl<S: AsRef<str>> ops::Index<&str> for TracedValues<S> {
    type Output = TracedValue;

    fn index(&self, index: &str) -> &Self::Output {
        self.get(index)
            .unwrap_or_else(|| panic!("value `{index}` is not defined"))
    }
}

impl<S: AsRef<str>> FromIterator<(S, TracedValue)> for TracedValues<S> {
    fn from_iter<I: IntoIterator<Item = (S, TracedValue)>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let mut this = Self::new();
        this.extend(iter);
        this
    }
}

impl<S: AsRef<str>> Extend<(S, TracedValue)> for TracedValues<S> {
    fn extend<I: IntoIterator<Item = (S, TracedValue)>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.inner.reserve(iter.size_hint().0);
        for (name, value) in iter {
            self.insert(name, value);
        }
    }
}

impl<S> IntoIterator for TracedValues<S> {
    type Item = (S, TracedValue);
    type IntoIter = vec::IntoIter<(S, TracedValue)>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.into_iter()
    }
}

/// Iterator over name-value references returned from [`TracedValues::iter()`].
#[derive(Debug)]
pub struct TracedValuesIter<'a, S> {
    inner: slice::Iter<'a, (S, TracedValue)>,
}

impl<'a, S: AsRef<str>> Iterator for TracedValuesIter<'a, S> {
    type Item = (&'a str, &'a TracedValue);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner
            .next()
            .map(|(name, value)| (name.as_ref(), value))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, S: AsRef<str>> DoubleEndedIterator for TracedValuesIter<'a, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner
            .next_back()
            .map(|(name, value)| (name.as_ref(), value))
    }
}

impl<'a, S: AsRef<str>> ExactSizeIterator for TracedValuesIter<'a, S> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, S: AsRef<str>> IntoIterator for &'a TracedValues<S> {
    type Item = (&'a str, &'a TracedValue);
    type IntoIter = TracedValuesIter<'a, S>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<S: AsRef<str>> Serialize for TracedValues<S> {
    fn serialize<Ser: Serializer>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error> {
        let mut map = serializer.serialize_map(Some(self.len()))?;
        for (name, value) in self {
            map.serialize_entry(name, value)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for TracedValues<String> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct MapVisitor;

        impl<'v> Visitor<'v> for MapVisitor {
            type Value = TracedValues<String>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("map of name-value entries")
            }

            fn visit_map<A: MapAccess<'v>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                let mut values = TracedValues {
                    inner: Vec::with_capacity(map.size_hint().unwrap_or(0)),
                };
                while let Some((name, value)) = map.next_entry()? {
                    values.insert(name, value);
                }
                Ok(values)
            }
        }

        deserializer.deserialize_map(MapVisitor)
    }
}

struct TracedValueVisitor<S> {
    values: TracedValues<S>,
}

impl<S: AsRef<str>> fmt::Debug for TracedValueVisitor<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ValueVisitor")
            .field("values", &self.values)
            .finish()
    }
}

impl<S: From<&'static str> + AsRef<str>> Visit for TracedValueVisitor<S> {
    fn record_f64(&mut self, field: &Field, value: f64) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_i128(&mut self, field: &Field, value: i128) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_u128(&mut self, field: &Field, value: u128) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
        self.values.insert(field.name().into(), value.into());
    }

    fn record_str(&mut self, field: &Field, value: &str) {
        self.values.insert(field.name().into(), value.into());
    }

    #[cfg(feature = "std")]
    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
        self.values
            .insert(field.name().into(), TracedValue::error(value));
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.values
            .insert(field.name().into(), TracedValue::debug(value));
    }
}