struct-mapper-derive 0.2.0

Procedural macro implementation for struct-mapper β€” do not depend on this directly, use struct-mapper instead
Documentation
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
<div align="center">

# πŸ”„ struct-mapper

**Derive macro to auto-generate `From<Source>` and `TryFrom<Source>` for your structs**
**β€” zero boilerplate field mapping.**

[![CI](https://github.com/ddsha441981/struct-mapper/actions/workflows/ci.yml/badge.svg)](https://github.com/ddsha441981/struct-mapper/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/badge/crates.io-v0.2.0-orange?style=flat-square&logo=rust)](https://crates.io/crates/struct-mapper)
[![Docs](https://img.shields.io/badge/docs.rs-struct--mapper-blue?style=flat-square&logo=docs.rs)](https://docs.rs/struct-mapper)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-green?style=flat-square)](https://github.com/ddsha441981/struct-mapper)
[![MSRV](https://img.shields.io/badge/MSRV-1.71.0-blue?style=flat-square&logo=rust)](https://www.rust-lang.org)

[πŸ“– Documentation](https://docs.rs/struct-mapper) Β· [πŸ“¦ Crates.io](https://crates.io/crates/struct-mapper) Β· [πŸ› Report Bug](https://github.com/ddsha441981/struct-mapper/issues) Β· [πŸ’‘ Request Feature](https://github.com/ddsha441981/struct-mapper/issues)

</div>

---

Stop writing tedious manual `From` and `TryFrom` implementations for struct-to-struct conversions. `struct-mapper` generates them at **compile time** with **zero runtime overhead**.

```rust
use struct_mapper::MapFrom;

struct UserEntity {
    name: String,
    email: String,
    age: u32,
}

#[derive(MapFrom)]
#[map_from(UserEntity)]
struct UserResponse {
    name: String,
    email: String,
    age: u32,
}

// That's it! Now you can do:
let entity = UserEntity { name: "Alice".into(), email: "a@b.com".into(), age: 30 };
let response: UserResponse = entity.into();
```

> No runtime cost. No reflection. Just a clean `impl From<>` generated at compile time.

---

## ✨ Why struct-mapper?

Every Rust backend developer writes this **dozens of times**:

<table>
<tr>
<th>😩 Before β€” Manual boilerplate</th>
<th>πŸš€ After β€” One derive</th>
</tr>
<tr>
<td>

```rust
impl From<UserEntity> for UserResponse {
    fn from(e: UserEntity) -> Self {
        UserResponse {
            name: e.name,
            email: e.email,
            age: e.age,
            display_name: e.first_name,
            address: e.address.into(),
            created_at: Default::default(),
        }
    }
}
```

</td>
<td>

```rust
#[derive(MapFrom)]
#[map_from(UserEntity)]
struct UserResponse {
    name: String,
    email: String,
    age: u32,
    #[map(from = "first_name")]
    display_name: String,
    #[map(into)]
    address: AddressResponse,
    #[map(skip, default)]
    created_at: String,
}
```

</td>
</tr>
</table>

---

## πŸ“¦ Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
struct-mapper = "0.2"
```

**Minimum Supported Rust Version:** `1.71.0`

---

## πŸš€ Features

### 1️⃣ Basic Mapping β€” Same Name, Same Type

Fields with matching names are mapped automatically. No attributes needed.

```rust
use struct_mapper::MapFrom;

struct Source {
    name: String,
    age: u32,
}

#[derive(MapFrom)]
#[map_from(Source)]
struct Target {
    name: String,
    age: u32,
}

let target: Target = Source { name: "Alice".into(), age: 30 }.into();
assert_eq!(target.name, "Alice");
```

### 2️⃣ Renamed Fields β€” `#[map(from = "...")]`

When source and target field names differ:

```rust
use struct_mapper::MapFrom;

struct DbRow {
    user_name: String,
    user_age: u32,
}

#[derive(MapFrom)]
#[map_from(DbRow)]
struct ApiUser {
    #[map(from = "user_name")]
    name: String,
    #[map(from = "user_age")]
    age: u32,
}
```

### 3️⃣ Skip + Default β€” `#[map(skip, default)]`

For fields that don't exist in the source struct:

```rust
use struct_mapper::MapFrom;

struct Entity {
    name: String,
}

#[derive(MapFrom)]
#[map_from(Entity)]
struct Response {
    name: String,
    #[map(skip, default)]
    request_id: String,    // β†’ Default::default() = ""
    #[map(skip, default)]
    retry_count: u32,      // β†’ Default::default() = 0
}
```

### 4️⃣ Nested Conversion β€” `#[map(into)]`

For fields where the source type implements `Into<TargetType>`:

```rust
use struct_mapper::MapFrom;

struct AddressEntity { street: String, city: String }

#[derive(MapFrom)]
#[map_from(AddressEntity)]
struct AddressDTO { street: String, city: String }

struct OrderEntity {
    id: u64,
    address: AddressEntity,
}

#[derive(MapFrom)]
#[map_from(OrderEntity)]
struct OrderDTO {
    id: u64,
    #[map(into)]
    address: AddressDTO,   // β†’ source.address.into()
}
```

### 5️⃣ Custom Function β€” `#[map(with = "...")]`

For complex transformations using any function:

```rust
use struct_mapper::MapFrom;

fn cents_to_dollars(cents: u64) -> f64 {
    cents as f64 / 100.0
}

struct PriceEntity {
    amount_cents: u64,
}

#[derive(MapFrom)]
#[map_from(PriceEntity)]
struct PriceResponse {
    #[map(from = "amount_cents", with = "cents_to_dollars")]
    amount: f64,
}
```

### πŸ”— Combine Everything

All attributes work together seamlessly:

```rust
use struct_mapper::MapFrom;

struct OrderEntity {
    order_id: u64,
    user_name: String,
    total_cents: u64,
    address: AddressEntity,
}

#[derive(MapFrom)]
#[map_from(OrderEntity)]
struct OrderResponse {
    order_id: u64,                                      // direct
    #[map(from = "user_name")]
    name: String,                                       // renamed
    #[map(from = "total_cents", with = "cents_to_dollars")]
    total: f64,                                         // renamed + custom fn
    #[map(into)]
    address: AddressDTO,                                // nested conversion
    #[map(skip, default)]
    request_id: String,                                 // skipped
}
```

---

## πŸ”„ Fallible Conversions β€” `TryMapFrom` (v0.2)

When conversions can **fail** (type narrowing, parsing, validation), use `TryMapFrom`:

```rust
use struct_mapper::TryMapFrom;
use std::num::ParseIntError;

fn parse_port(s: String) -> Result<u16, ParseIntError> {
    s.parse::<u16>()
}

struct RawConfig {
    port_str: String,
    max_conn: i64,
    host: String,
}

#[derive(TryMapFrom)]
#[try_map_from(RawConfig)]
struct ValidConfig {
    #[map(from = "port_str", try_with = "parse_port")]
    port: u16,                    // fallible: string β†’ u16
    #[map(try_into)]
    max_conn: u32,                // fallible: i64 β†’ u32
    host: String,                 // direct (infallible)
}

// Success:
let raw = RawConfig { port_str: "8080".into(), max_conn: 100, host: "localhost".into() };
let config: ValidConfig = raw.try_into().unwrap();

// Failure β€” tells you exactly which field failed:
let bad = RawConfig { port_str: "not_a_port".into(), max_conn: 100, host: "x".into() };
let err = ValidConfig::try_from(bad).unwrap_err();
assert_eq!(err.field, "port");
println!("{}", err); // "mapping failed at field `port`: invalid digit found in string"
```

---

## πŸ“‹ Attribute Reference

| Attribute | Applies To | Description |
|:----------|:----------:|:------------|
| `#[map_from(Type)]` | Struct | Source type to generate `From<Type>` for |
| `#[try_map_from(Type)]` | Struct | Source type to generate `TryFrom<Type>` for |
| `#[map(from = "name")]` | Field | Map from a differently-named source field |
| `#[map(skip, default)]` | Field | Skip this field, use `Default::default()` |
| `#[map(into)]` | Field | Call `.into()` on the source value |
| `#[map(with = "fn")]` | Field | Apply a custom conversion function |
| `#[map(try_into)]` | Field | Call `.try_into()` on the source value *(TryMapFrom only)* |
| `#[map(try_with = "fn")]` | Field | Apply a fallible function *(TryMapFrom only)* |

> πŸ’‘ **Tip:** Attributes can be combined: `#[map(from = "old_name", try_with = "parse_fn")]`

---

## πŸ›‘οΈ Error Messages

`struct-mapper` provides **clear, actionable error messages** that tell you exactly what went wrong and how to fix it:

```
error: missing `#[map_from(SourceType)]` attribute.
       Add `#[map_from(YourSourceStruct)]` to specify which struct to map from.

       Example:
         #[derive(MapFrom)]
         #[map_from(UserEntity)]
         struct UserResponse { ... }
```

```
error: `#[map(skip)]` requires `#[map(skip, default)]`.
       When skipping a field, you must provide a default value.

       Fix: #[map(skip, default)]
```

---

## πŸ“Š Comparison

How does `struct-mapper` compare to alternatives?

| Feature | **struct-mapper** | derive-into | more-convert | structural-convert |
|:--------|:-:|:-:|:-:|:-:|
| Same-field mapping | βœ… | βœ… | βœ… | βœ… |
| Field renaming | βœ… | βœ… | βœ… | ⚠️ |
| Skip + default | βœ… | ⚠️ | ⚠️ | ⚠️ |
| Nested `.into()` | βœ… | βœ… | ❌ | ⚠️ |
| Custom function | βœ… | βœ… | ⚠️ | ⚠️ |
| **`TryFrom` support** | βœ… | ❌ | ❌ | ❌ |
| **Fallible custom fn** | βœ… | ❌ | ❌ | ❌ |
| **Clear error messages** | βœ… | ❌ | ❌ | ❌ |
| **Clean syntax** | βœ… | ⚠️ | ⚠️ | ⚠️ |
| Compile-time only | βœ… | βœ… | βœ… | βœ… |
| Zero runtime deps | βœ… | βœ… | βœ… | βœ… |

---

## πŸ—ΊοΈ Roadmap

- [x] `From` β€” infallible struct conversion
- [x] Field renaming, skipping, nesting, custom functions
- [x] Clear compile-time error messages
- [x] `TryFrom` β€” fallible conversions (`v0.2`) βœ…
- [ ] Enum variant mapping (`v0.3`)
- [ ] Bi-directional mapping (`v0.4`)

---

## ⚠️ Limitations (v0.2)

- Only named struct fields. Tuple structs and enums are not yet supported.
- Generics on the target struct are supported; generic source types require manual annotation.

---

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'feat: add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## πŸ‘¨β€πŸ’» Author

<table>
<tr>
<td>

**Deendayal Kumawat**

[![LinkedIn](https://img.shields.io/badge/LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/deendayal-kumawat/)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/ddsha441981)
[![Email](https://img.shields.io/badge/Email-0078D4?style=flat-square&logo=microsoft-outlook&logoColor=white)](mailto:deendayal_kumawat@outlook.com)

</td>
</tr>
</table>

---

## πŸ“„ License

Licensed under either of:

- **Apache License, Version 2.0** β€” [LICENSE-APACHE]LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>
- **MIT License** β€” [LICENSE-MIT]LICENSE-MIT or <http://opensource.org/licenses/MIT>

at your option.

---

<div align="center">

**⭐ If you find this useful, please consider giving it a star! ⭐**

*Made with ❀️ in Rust*

</div>