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
#![allow(dead_code)]
use model_mapper::Mapper;
mod ignore_extra_into {
use super::*;
#[derive(Default)]
struct Foo {
field1: String,
field2: i64,
field3: Option<i32>,
field4: Option<String>,
}
/// When deriving 'into' for structs the [Default] trait is required on the target type,
/// in order to populate missing fields
#[derive(Mapper)]
#[mapper(into, ty = Foo, ignore_extra)]
struct Bar {
field1: String,
field2: i64,
}
/// But it's not required for enums
enum FooEnum {
One,
Two,
Three,
Four,
}
#[derive(Mapper)]
#[mapper(into, ty = FooEnum, ignore_extra)]
enum BarEnum {
One,
Two,
}
}
mod ignore_extra_from {
use super::*;
struct Foo {
field1: String,
field2: i64,
field3: Option<i32>,
field4: Option<String>,
}
/// When deriving 'from' for structs the [Default] trait is not required on the target type
#[derive(Mapper)]
#[mapper(from, ty = Foo, ignore_extra)]
struct Bar {
field1: String,
field2: i64,
}
enum FooEnum {
One,
Two,
Three,
Four,
}
/// But it's required on the source enum, in order to route missing variants
#[derive(Mapper, Default)]
#[mapper(from, ty = FooEnum, ignore_extra)]
enum BarEnum {
#[default]
One,
Two,
}
}
mod ignore_extra_explicit {
use super::*;
struct Foo {
field1: String,
field2: i64,
field3: Option<i32>,
field4: Option<String>,
}
/// The [Default] is not required for the target struct if the additional fields are explicitly set.
/// For example if [Foo] resides in other crate and we can't modify it
#[derive(Mapper)]
#[mapper(
into, from,
ty = Foo,
// By providing an explicit value
add(field = field3, default(value = Some(1))),
// Or explicitly setting to the default (if the field's type implements it)
add(field = field4, default)
)]
struct Bar {
field1: String,
field2: i64,
}
enum FooEnum {
One,
Two,
Three,
Four,
}
/// Neither on the enum if we explicitly provide defaults.
/// Allowing us to provide a different default value for each additional variant
#[derive(Mapper)]
#[mapper(
from,
ty = FooEnum,
add(field = Three, default(value = BarEnum::One)),
add(field = Four, default(value = BarEnum::Two))
)]
enum BarEnum {
One,
Two,
}
}
fn main() {}