Debian Codegraph @

src/features/valuable.rs

raw ◀ ▶
1 Debian patch touch this file
1 //! Implements the [`valuable::Valuable`] trait for [`CompactString`], so it can be
2 //! inspected as a [`Value::String`] by object-safe value visitors (e.g. `tracing`).
3
4 use valuable::{Valuable, Value, Visit};
5
6 use crate::CompactString;
7
8 #[cfg_attr(docsrs, doc(cfg(feature = "valuable")))]
9 impl Valuable for CompactString {
10 fn as_value(&self) -> Value<'_> {
11 Value::String(self.as_str())
12 }
13
14 fn visit(&self, visit: &mut dyn Visit) {
15 self.as_str().visit(visit);
16 }
17 }
18
•19 #[cfg(all(test, feature = "std"))]
20 mod tests {
21 use alloc::string::String;
22
23 use test_strategy::proptest;
24 use valuable::{Valuable, Value, Visit};
25
26 use super::*;
27 use crate::tests::rand_unicode;
28
29 /// A [`Visit`] that records the single scalar value passed to it.
30 #[derive(Default)]
31 struct CapturingVisit {
32 captured: Option<String>,
33 }
34
35 impl Visit for CapturingVisit {
36 fn visit_value(&mut self, value: Value<'_>) {
37 if let Value::String(s) = value {
38 self.captured = Some(String::from(s));
39 }
40 }
41 }
42
43 #[test]
44 fn smoketest_as_value() {
45 // Inline string.
46 let short = CompactString::from("hello");
47 assert!(matches!(short.as_value(), Value::String("hello")));
48
49 // Heap allocated string.
50 let long = CompactString::from("I am a long string that will be on the heap");
51 assert!(long.is_heap_allocated());
52 assert!(matches!(
53 long.as_value(),
54 Value::String("I am a long string that will be on the heap")
55 ));
56 }
57
58 #[test]
59 fn smoketest_visit() {
60 let compact = CompactString::from("hello");
61 let mut visitor = CapturingVisit::default();
62 compact.visit(&mut visitor);
63 assert_eq!(visitor.captured.as_deref(), Some("hello"));
64 }
65
66 #[proptest]
67 #[cfg_attr(miri, ignore)]
68 fn proptest_as_value_matches_str(#[strategy(rand_unicode())] s: String) {
69 let compact = CompactString::new(&s);
70
71 // The value should always present as a `Value::String` equal to the source `&str`.
72 match compact.as_value() {
73 Value::String(v) => assert_eq!(v, s.as_str()),
74 other => panic!("expected Value::String, got {other:?}"),
75 }
76
77 // And visiting should surface the same string.
78 let mut visitor = CapturingVisit::default();
79 compact.visit(&mut visitor);
80 assert_eq!(visitor.captured.as_deref(), Some(s.as_str()));
81 }
82 }