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
|
use valuable::{NamedValues, Valuable, Value, Visit};
struct Print(String);
impl Print {
fn indent(&self) -> Print {
Print(format!("{} ", self.0))
}
}
impl Visit for Print {
fn visit_value(&mut self, value: Value<'_>) {
match value {
Value::Structable(v) => {
let def = v.definition();
// Print the struct name
println!("{}{}:", self.0, def.name());
// Visit fields
let mut visit = self.indent();
v.visit(&mut visit);
}
Value::Enumerable(v) => {
let def = v.definition();
let variant = v.variant();
// Print the enum name
println!("{}{}::{}:", self.0, def.name(), variant.name());
// Visit fields
let mut visit = self.indent();
v.visit(&mut visit);
}
Value::Listable(v) => {
println!("{}", self.0);
// Visit fields
let mut visit = self.indent();
v.visit(&mut visit);
}
Value::Mappable(v) => {
println!("{}", self.0);
// Visit fields
let mut visit = self.indent();
v.visit(&mut visit);
}
// Primitive or unknown type, just render Debug
v => println!("{:?}", v),
}
}
fn visit_named_fields(&mut self, named_values: &NamedValues<'_>) {
for (field, value) in named_values {
print!("{}- {}: ", self.0, field.name());
value.visit(self);
}
}
fn visit_unnamed_fields(&mut self, values: &[Value<'_>]) {
for value in values {
print!("{}- ", self.0);
value.visit(self);
}
}
fn visit_entry(&mut self, key: Value<'_>, value: Value<'_>) {
print!("{}- {:?}: ", self.0, key);
value.visit(self);
}
}
#[derive(Valuable)]
struct Person {
name: String,
age: u32,
addresses: Vec<Address>,
}
#[derive(Valuable)]
struct Address {
street: String,
city: String,
zip: String,
}
fn main() {
let person = Person {
name: "Angela Ashton".to_string(),
age: 31,
addresses: vec![
Address {
street: "123 1st Ave".to_string(),
city: "Townsville".to_string(),
zip: "12345".to_string(),
},
Address {
street: "555 Main St.".to_string(),
city: "New Old Town".to_string(),
zip: "55555".to_string(),
},
],
};
let mut print = Print("".to_string());
valuable::visit(&person, &mut print);
}
|