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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//! Integration tests for enum serialization and deserialization.
use indoc::indoc;
use serde::{Deserialize, Serialize};
// Test macros
macro_rules! deser_ok {
($name:ident, $ty:ty, $input:expr, $expected:expr) => {
#[test]
fn $name() {
let val: $ty = serde_kdl2::from_str($input).unwrap();
assert_eq!(val, $expected);
}
};
}
macro_rules! roundtrip {
($name:ident, $ty:ty, $val:expr) => {
#[test]
fn $name() {
let val: $ty = $val;
let output = serde_kdl2::to_string(&val).unwrap();
let rt: $ty = serde_kdl2::from_str(&output).unwrap();
assert_eq!(val, rt);
}
};
}
// Shared types
#[derive(Debug, Serialize, Deserialize, PartialEq)]
enum Color {
Red,
Green,
Blue,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Colored {
name: String,
color: Color,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
}
// ── Enum variants ──────────────────────────────────────────────────────
deser_ok!(
deserialize_unit_variant,
Colored,
indoc! {r#"
name "widget"
color "Red"
"#},
Colored {
name: "widget".into(),
color: Color::Red
}
);
roundtrip!(
serialize_unit_variant,
Colored,
Colored {
name: "widget".into(),
color: Color::Green
}
);
// ── Struct variant enum ────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Drawing {
name: String,
shape: Shape,
}
deser_ok!(
deserialize_struct_variant,
Drawing,
indoc! {r#"
name "my drawing"
shape {
Circle {
radius 5.0
}
}
"#},
Drawing {
name: "my drawing".into(),
shape: Shape::Circle { radius: 5.0 }
}
);
roundtrip!(
serialize_struct_variant,
Drawing,
Drawing {
name: "my drawing".into(),
shape: Shape::Rectangle {
width: 10.0,
height: 20.0
},
}
);
// ── Newtype variant enum ───────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, PartialEq)]
enum Wrapper {
Text(String),
Number(i64),
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Wrapped {
value: Wrapper,
}
deser_ok!(
deserialize_newtype_variant,
Wrapped,
indoc! {r#"
value {
Text "hello"
}
"#},
Wrapped {
value: Wrapper::Text(String::from("hello"))
}
);
roundtrip!(
serialize_newtype_variant,
Wrapped,
Wrapped {
value: Wrapper::Text(String::from("hello"))
}
);