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
use serde::Serialize;
use std::fmt;
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize)]
pub struct Key(&'static str);
impl Key {
pub fn new(s: &'static str) -> Self {
Self(s)
}
pub fn as_str(&self) -> &'static str {
self.0
}
}
#[derive(Clone, Copy)]
pub enum Value<'v> {
Debug(&'v (dyn fmt::Debug)),
Display(&'v (dyn fmt::Display)),
Serde(&'v (dyn erased_serde::Serialize)),
}
impl<'v> fmt::Debug for Value<'v> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
Value::Debug(d) => fmt::Debug::fmt(d, f),
Value::Display(d) => fmt::Display::fmt(d, f),
Value::Serde(s) => {
fmt::Debug::fmt(&serde_json::to_value(s).map_err(|_| fmt::Error)?, f)
}
}
}
}
impl<'v> Value<'v> {
pub fn from_serde<T: serde::Serialize>(value: &'v T) -> Self {
Value::Serde(value)
}
pub fn from_debug<T: fmt::Debug>(value: &'v T) -> Self {
Value::Debug(value)
}
pub fn from_display<T: fmt::Display>(value: &'v T) -> Self {
Value::Display(value)
}
}
#[derive(Clone, Debug)]
pub struct KeyValue<'v> {
key: Key,
value: Value<'v>,
}
impl<'v> KeyValue<'v> {
pub fn new(key: &'static str, value: Value<'v>) -> Self {
Self {
key: Key::new(key),
value,
}
}
}
impl<'v> Schema for KeyValue<'v> {
fn visit(&self, visitor: &mut dyn Visitor) {
visitor.visit_pair(self.key, self.value)
}
}
pub trait Schema {
fn visit(&self, visitor: &mut dyn Visitor);
}
pub trait Visitor {
fn visit_pair(&mut self, key: Key, value: Value<'_>);
}
impl<'a, 'b: 'a> Visitor for fmt::DebugMap<'a, 'b> {
fn visit_pair(&mut self, key: Key, value: Value<'_>) {
self.entry(&key, &value);
}
}