Skip to main content

micromegas_tracing/
property_value.rs

1//! Values that the logging and metric macros accept as bare `key = value` entries.
2use std::{borrow::Cow, rc::Rc, sync::Arc};
3
4mod sealed {
5    pub trait Sealed {}
6    impl Sealed for str {}
7    impl Sealed for String {}
8    impl Sealed for std::borrow::Cow<'_, str> {}
9    impl<T: Sealed + ?Sized> Sealed for &T {}
10    impl<T: Sealed + ?Sized> Sealed for Box<T> {}
11    impl<T: Sealed + ?Sized> Sealed for std::sync::Arc<T> {}
12    impl<T: Sealed + ?Sized> Sealed for std::rc::Rc<T> {}
13}
14
15/// A value that can be recorded as a property without being formatted first.
16///
17/// Strings borrow, so a bare value costs no allocation. Use `%value` (`Display`) or `?value`
18/// (`Debug`) for anything else. The trait is sealed: a deferred log message is rebuilt from
19/// `property_value()` while the local sink prints the value with `Display`, so every impl must
20/// produce the same text for both.
21pub trait PropertyValue: sealed::Sealed {
22    fn property_value(&self) -> Cow<'_, str>;
23}
24
25impl PropertyValue for str {
26    fn property_value(&self) -> Cow<'_, str> {
27        Cow::Borrowed(self)
28    }
29}
30
31impl PropertyValue for String {
32    fn property_value(&self) -> Cow<'_, str> {
33        Cow::Borrowed(self.as_str())
34    }
35}
36
37impl PropertyValue for Cow<'_, str> {
38    fn property_value(&self) -> Cow<'_, str> {
39        Cow::Borrowed(&**self)
40    }
41}
42
43impl<T: PropertyValue + ?Sized> PropertyValue for &T {
44    fn property_value(&self) -> Cow<'_, str> {
45        (**self).property_value()
46    }
47}
48
49impl<T: PropertyValue + ?Sized> PropertyValue for Box<T> {
50    fn property_value(&self) -> Cow<'_, str> {
51        (**self).property_value()
52    }
53}
54
55impl<T: PropertyValue + ?Sized> PropertyValue for Arc<T> {
56    fn property_value(&self) -> Cow<'_, str> {
57        (**self).property_value()
58    }
59}
60
61impl<T: PropertyValue + ?Sized> PropertyValue for Rc<T> {
62    fn property_value(&self) -> Cow<'_, str> {
63        (**self).property_value()
64    }
65}