Skip to main content

micromegas_tracing/spans/
span_properties.rs

1//! Properties a span carries until its end event.
2use crate::property_set::{DynProperty, PropertySet};
3
4#[cfg(not(target_arch = "wasm32"))]
5use smallvec::SmallVec;
6#[cfg(not(target_arch = "wasm32"))]
7use std::fmt::{self, Write as _};
8
9/// Properties a span carries until its end event. Values are copied in, so they only need to
10/// outlive the call that sets them.
11///
12/// Names stay `'static` because the number of distinct names must stay bounded; put unbounded
13/// data in the values.
14#[cfg(not(target_arch = "wasm32"))]
15pub struct SpanProperties {
16    static_set: &'static PropertySet,
17    // name, then offset and length of the value in `values`
18    entries: SmallVec<[(&'static str, u32, u32); 8]>,
19    values: SmallVec<[u8; 128]>,
20}
21
22#[cfg(not(target_arch = "wasm32"))]
23struct ValueWriter<'a>(&'a mut SmallVec<[u8; 128]>);
24
25#[cfg(not(target_arch = "wasm32"))]
26impl fmt::Write for ValueWriter<'_> {
27    fn write_str(&mut self, s: &str) -> fmt::Result {
28        self.0.extend_from_slice(s.as_bytes());
29        Ok(())
30    }
31}
32
33#[cfg(not(target_arch = "wasm32"))]
34impl SpanProperties {
35    pub fn new(static_set: &'static PropertySet) -> Self {
36        Self {
37            static_set,
38            entries: SmallVec::new(),
39            values: SmallVec::new(),
40        }
41    }
42
43    /// Sets a property, replacing the value of a property of the same name (compared
44    /// case-insensitively, like `property_get`). It beats a literal of the same name given when
45    /// the span was created.
46    ///
47    /// ```
48    /// use micromegas_tracing::prelude::*;
49    ///
50    /// # fn main() {
51    /// let mut span = span_scope!(name = "fetch_rows", region = "eu");
52    /// span.set_property("rows", 42);
53    /// span.set_property("cache", if true { "hit" } else { "miss" });
54    /// # }
55    /// ```
56    pub fn set_property(&mut self, name: &'static str, value: impl fmt::Display) {
57        if let Some(i) = self
58            .entries
59            .iter()
60            .position(|e| e.0.eq_ignore_ascii_case(name))
61        {
62            let (_, offset, len) = self.entries.remove(i);
63            // Compacted so that a property set in a loop doesn't grow the buffer.
64            self.values.drain(offset as usize..(offset + len) as usize);
65            for entry in self.entries.iter_mut().filter(|e| e.1 > offset) {
66                entry.1 -= len;
67            }
68        }
69        let start = self.values.len();
70        // `ValueWriter` never fails; a `Display` that errs leaves its partial output.
71        let _ = write!(ValueWriter(&mut self.values), "{value}");
72        let len = self.values.len() - start;
73        self.entries.push((name, start as u32, len as u32));
74    }
75
76    pub(crate) fn is_empty(&self) -> bool {
77        self.entries.is_empty() && self.static_set.get_properties().is_empty()
78    }
79
80    /// Bytes held by the values set at run time.
81    #[doc(hidden)]
82    pub fn value_bytes(&self) -> usize {
83        self.values.len()
84    }
85
86    /// Hands the static set and the entries set at run time to `f`, as the tagged end functions
87    /// of the dispatch take them.
88    #[doc(hidden)]
89    pub fn with_dyn<R>(&self, f: impl FnOnce(&'static PropertySet, &[DynProperty<'_>]) -> R) -> R {
90        let dyn_properties: SmallVec<[DynProperty<'_>; 8]> = self
91            .entries
92            .iter()
93            .map(|&(name, offset, len)| {
94                let bytes = &self.values[offset as usize..(offset + len) as usize];
95                // SAFETY: the bytes were written by `fmt::Write::write_str` from `&str`s, and
96                // entries are removed whole.
97                DynProperty::new(name, unsafe { std::str::from_utf8_unchecked(bytes) })
98            })
99            .collect();
100        f(self.static_set, &dyn_properties)
101    }
102}
103
104/// Properties are not recorded on wasm32.
105#[cfg(target_arch = "wasm32")]
106pub struct SpanProperties {
107    static_set: &'static PropertySet,
108}
109
110#[cfg(target_arch = "wasm32")]
111impl SpanProperties {
112    pub fn new(static_set: &'static PropertySet) -> Self {
113        Self { static_set }
114    }
115
116    pub fn set_property(&mut self, _name: &'static str, _value: impl std::fmt::Display) {}
117
118    pub(crate) fn is_empty(&self) -> bool {
119        true
120    }
121
122    #[doc(hidden)]
123    pub fn with_dyn<R>(&self, f: impl FnOnce(&'static PropertySet, &[DynProperty<'_>]) -> R) -> R {
124        f(self.static_set, &[])
125    }
126
127    #[doc(hidden)]
128    pub fn value_bytes(&self) -> usize {
129        0
130    }
131}