builder-pattern 0.4.2

A derivable macro for declaring a builder pattern.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! A derivable macro for declaring a builder pattern.
//! This crate is highly inspired by [derive_builder](https://crates.io/crates/derive-builder).
//!
//! ## Usage
//!
//! ```
//! use builder_pattern::Builder;
//! # enum Gender {
//! #     Male,
//! #     Female,
//! #     Nonbinary
//! # }
//!
//! #[derive(Builder)]
//! struct Person {
//!     #[into]
//!     name: String,
//!     age: i32,
//!     #[default(Gender::Nonbinary)]
//!     #[setter(value, async)]
//!     gender: Gender,
//! }
//!
//! let p1 = Person::new()          // PersonBuilder<(), (), (), ...>
//!     .name(String::from("Joe"))  // PersonBuilder<String, (), (), ...>
//!     .age(27)                    // PersonBuilder<String, i32, (), ...>
//!     .build();                   // Person
//!     
//! // Order does not matter.
//! let p2 = Person::new()          // PersonBuilder<(), (), (), ...>
//!     .age(32)                    // PersonBuilder<(), i32, (), ...>
//!     // `&str` is implicitly converted into `String`
//!     // because of `into` attribute!
//!     .name("Jack")               // PersonBuilder<String, i32, (), ...>
//!     .gender(Gender::Male)       // PersonBuilder<String, i32, Gender, ...>
//!     .build();                   // Person
//!
//! // Asynchronously evaluated
//! # tokio_test::block_on(async {
//! let p3 = Person::new()          // PersonBuilder<(), (), (), ...>
//!     .age(32)                    // PersonBuilder<(), i32, (), ...>
//!     // `&str` is implicitly converted into `String`
//!     // because of `into` attribute!
//!     .name("Jack")               // PersonBuilder<String, i32, (), ...>
//!     .gender_async(|| async {
//!         Gender::Male
//!     })                          // PersonBuilder<String, i32, Gender, ...>
//!     .build()                    // Future<Person>
//!     .await;                     // Person
//! # });
//! # // cont
//! ```
//! ```compile_fail
//! # // cont
//! # use builder_pattern::Builder;
//! # enum Gender {
//! #     Male,
//! #     Female,
//! #     Nonbinary
//! # }
//! #
//! # #[derive(Builder)]
//! # struct Person {
//! #     #[into]
//! #     name: String,
//! #     age: i32,
//! #     #[default(Gender::Nonbinary)]
//! #     gender: Gender,
//! # }
//! // `name` field required - Compilation error.
//! let p4 = Person::new()          // PersonBuilder<(), (), (), ...>
//!     .age(15)                    // PersonBuilder<(), i32, (), ...>
//!     .build();
//! ```
//!
//! ## Features
//!
//! - **Chaining**: Can make structure with chained setters.
//! - **Complex types are supported**: Lifetime, trait bounds, and where clauses are well supported.
//! - **Type safety**: Autocompletion tools can suggest correct setters to build the struct. Also, `build`
//! function is allowed only the all of required fields are provided. **No Result**, **No Unwrap**. Just use it.
//! - **Lazy evaluation and asynchronous**: Lazy evaluation and asynchronous are supported.
//! The values will be evaluated when the structure is built.
//! - **No additional tasks**: There's no additional constraints to use the macro. Any structures and fields are allowed.
//! - **Auto-generated documentation**: Documentation for the builder functions are automatically generated.
//!
//! ## Attributes
//!
//! ### `#[default(expr)]`
//!
//! A field having this attribute will be considered as optional, and the `expr` will be evaluated
//! as a default value of the field. `build` function can be called without providing this field.
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder)]
//! struct Test {
//!     #[default(5)]
//!     pub a: i32,
//!     pub b: &'static str,
//! }
//!
//! let t1 = Test::new().b("Hello").build(); // The structure can be built without `a`.
//! let t2 = Test::new().b("Hi").a(3).build();
//! ```
//! ### `#[default_lazy(expr)]`
//!
//! A field having this attribute will be considered as optional, and the `expr`
//! will be lazily evaluated as a default value of the field. `expr` should be
//! a function or a closure having no arguments.
//!
//! ```
//! # use builder_pattern::Builder;
//! # fn some_heavy_task() -> i32 { 3 }
//! #[derive(Builder)]
//! struct Test {
//!     #[default_lazy(|| some_heavy_task() + 3)]
//!     pub a: i32,
//!     #[default_lazy(some_heavy_task)]
//!     pub b: i32,
//! }
//!
//! // The structure can be built without `a` and `b`.
//! let t1 = Test::new().build();
//! let t2 = Test::new().a(3).build();
//! ```
//!
//! ### `#[hidden]`
//!
//! If this attribute is present, the builder function would not be generated for the field.
//! This field requires `default` or `default_lazy` attribute.
//!
//! Example:
//!
//! ```
//! # use builder_pattern::Builder;
//! # use uuid::Uuid;
//! #[derive(Builder)]
//! struct Test {
//!     #[default(Uuid::new_v4())]
//!     #[hidden]
//!     id: Uuid,
//!     name: String,
//! }
//!
//! let test1 = Test::new()         // TestBuilder<(), (), ...>
//!     .name(String::from("Joe"))  // TestBuilder<String, (), ...>
//!     .build();                   // Test
//! # // cont
//! ```
//! ```compile_fail
//! # // cont
//! # use builder_pattern::Builder;
//! # use uuid::Uuid;
//! # #[derive(Builder)]
//! # struct Test {
//! #     #[default(Uuid::new_v4())]
//! #     #[hidden]
//! #     id: Uuid,
//! #     name: String,
//! # }
//! let test2 = Test::new()         // TestBuilder<(), (), ...>
//!     .name(String::from("Jack")) // TestBuilder<String, (), ...>
//!     // Error: `id` function is not generated.
//!     .id(Uuid::parse_str("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e").unwrap())
//!     .build();
//! ```
//!
//! ### `#[public]`
//!
//! If this attribute is present, a field would be exposed with setter functions even though the
//! field is private. It provides a way to access private fields during the building.
//!
//! Example:
//!
//! ```
//! # use uuid::Uuid;
//! mod test {
//! #   use builder_pattern::Builder;
//! #   use uuid::Uuid;
//!     #[derive(Builder)]
//!     pub struct Test {
//!         #[public]
//!         id: Uuid,
//!         pub name: &'static str,
//!     }
//! }
//! use test::Test;
//!
//! let test1 = Test::new()   // TestBuilder<(), (), ...>
//!     .id(Uuid::new_v4())   // TestBuilder<Uuid, (), ...>
//!     .name("Joe")          // TestBuilder<Uuid, &'static str, ...>
//!     .build();             // Test
//! assert_eq!(test1.name, "Joe");
//! # // cont
//! ```
//! ```compile_fail
//! # //cont
//! # use uuid::Uuid;
//! # mod test {
//! #     use builder_pattern::Builder;
//! #     use uuid::Uuid;
//! #     #[derive(Builder)]
//! #     pub struct Test {
//! #         #[public]
//! #         id: Uuid,
//! #         pub name: &'static str,
//! #     }
//! # }
//! # use test::Test;
//! # let test1 = Test::new()
//! #     .id(Uuid::new_v4())
//! #     .name("Joe")
//! #     .build();
//! println!("{}", test1.id); // Error: `id` is a private field.
//! ```
//!
//! ### `#[setter(value | lazy | async)]`
//!
//! If this attribute presents, it provides specified setters.
//! If it doesn't, only the value setter is provided.
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder, Debug)]
//! struct Person {
//!     // All kinds of setters are provided.
//!     #[setter(value, lazy, async)]
//!     name: String,
//!     // Only value setter is provided.
//!     age: u8,
//!     // Only lazy setter is provided.
//!     #[setter(lazy)]
//!     address: &'static str,
//! }
//!
//! # tokio_test::block_on(async {
//! let p1 = Person::new()
//!     .name_async(|| async { String::from("Joe") })
//!     .age(15)
//!     .address_lazy(|| "123 Main St")
//!     .build()  // `address` is validated here
//!     .await; // `name` is validated here
//! # });
//! ```
//!
//! ### `#[into]`
//!
//! A setter function for a field having this attribute will accept `Into`
//! trait as a parameter. You can use this setter with implicit conversion.
//!
//! Example:
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder)]
//! struct Test {
//!     #[into]
//!     #[setter(value, lazy)]
//!     pub name: String,
//! }
//!
//! let test1 = Test::new()         // TestBuilder<(), ...>
//!     // `&str` is implicitly converted into `String`.
//!     .name("Hello")              // TestBuilder<String, ...>
//!     .build();                   // Test
//!
//! let test2 = Test::new()         // TestBuilder<(), ...>
//!     // `&str` is implicitly converted into `String`.
//!     .name_lazy(|| "Hello")      // TestBuilder<String, ...>
//!     .build();                   // Test
//! ```
//!
//! ### `#[validator(expr)]`
//!
//! Implement a validator for a field. `expr` could be a validating function that takes the field's
//! type and returns `Result`.
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder)]
//! struct Test {
//!     #[validator(is_not_empty)]
//!     #[into]
//!     pub name: String,
//! }
//!
//! fn is_not_empty(name: String) -> Result<String, &'static str> {
//!     if name.is_empty() {
//!         Err("Name cannot be empty.")
//!     } else {
//!         Ok(name)
//!     }
//! }
//!
//! let test1 = Test::new()          // TestBuilder<(), ...>
//!     .name(String::from("Hello")) // Ok(TestBuilder<String, ...>)
//!     .unwrap()                    // TestBuilder<String, ...>
//!     .build();                    // Test
//! # // cont
//! ```
//! ```should_panic
//! # // cont
//! # use builder_pattern::Builder;
//! # #[derive(Builder)]
//! # struct Test {
//! #     #[validator(is_not_empty)]
//! #     #[into]
//! #     pub name: String,
//! # }
//! #
//! # fn is_not_empty(name: String) -> Result<String, &'static str> {
//! #     if name.is_empty() {
//! #         Err("Name cannot be empty.")
//! #     } else {
//! #         Ok(name)
//! #     }
//! # }
//! #
//! let test2 = Test::new() // TestBuilder<(), ...>
//!     .name("")           // Err(String{ "Validation failed: Name cannot be empty." })
//!     .unwrap()           // panic!
//!     .build();
//! ```
//!
//! If a `validator` is used with `lazy` or `async` setters,
//! it will also validated lazily or asynchronously. So, the
//! setter doesn't return `Result` but it is returned when it is built.
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder)]
//! struct Test {
//!     #[validator(is_not_empty)]
//!     #[setter(lazy, async)]
//!     pub name: &'static str,
//! }
//! # fn is_not_empty(name: &'static str) -> Result<&'static str, &'static str> {
//! #     if name.is_empty() {
//! #         Err("Name cannot be empty.")
//! #     } else {
//! #         Ok(name)
//! #     }
//! # }
//! #
//!
//! let test1 = Test::new()         // TestBuilder<(), ...>
//!     .name_lazy(|| "Hello")      // TestBuilder<String, ...>
//!     .build()                    // Ok(Test)
//!     .unwrap();                  // Test
//!
//! # tokio_test::block_on(async {
//! let test2 = Test::new()         // TestBuilder<(), ...>
//!     .name_async(|| async { "Hello" }) // TestBuilder<String, ...>
//!     .build()                    // Future<Result<Test, String>>
//!     .await                      // Ok(Test)
//!     .unwrap();                  // Test
//! # });
//! ```
//!
//! ## Auto-Generated Documentation
//!
//! This crate generates documentation for the builder functions. If you document fields,
//! the builder functions for them also copy the documentation.
//!
//! ### Example
//!
//! Example code:
//!
//! ```
//! # use builder_pattern::Builder;
//! #[derive(Builder)]
//! struct Test {
//!     /// A positive integer.
//!     pub positive: i32,
//!
//!     /// An integer having zero as a default value.
//!     #[default(0)]
//!     pub zero: i32,
//! }
//! ```
//!
//! Generated code:
//!
//! ```
//! # use core::marker::PhantomData;
//! # use builder_pattern::setter::*;
//! # struct Test {
//! #     pub positive: i32,
//! #     pub zero: i32,
//! # }
//! impl Test {
//!     /// Creating a builder.
//!     /// ## Required fields
//!     /// ### `positive`
//!     /// - Type: `i32`
//!     ///
//!     /// A positive integer.
//!     ///
//!     /// ## Optional fields
//!     /// ### `zero`
//!     /// - Type: `i32`
//!     /// - Default: `0`
//!     ///
//!     /// An integer having zero as a default value.
//!     fn new<'a>() -> TestBuilder<'a, (), (), (), ()> {
//!         TestBuilder {
//!             _phantom: PhantomData,
//!             positive: None,
//!             zero: Some(Setter::Value(0)),
//!         }
//!     }
//! }
//!
//! /// A builder for `Test`.
//! struct TestBuilder<
//!     'a,
//!     T1,
//!     T2,
//!     AsyncFieldMarker,
//!     ValidatorOption,
//! > {
//!     _phantom: PhantomData<(
//!         T1,
//!         T2,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     )>,
//!     positive: Option<Setter<'a, i32>>,
//!     zero: Option<Setter<'a, i32>>,
//! }
//!
//! impl<'a, T2, AsyncFieldMarker, ValidatorOption>
//!     TestBuilder<'a, (), T2, AsyncFieldMarker, ValidatorOption>
//! {
//!     /// # positive
//!     /// - Type: `i32`
//!     ///
//!     /// A positive integer.
//!     pub fn positive(
//!         self,
//!         value: i32
//!     ) -> TestBuilder<'a, i32, T2, AsyncFieldMarker, ValidatorOption> {
//!         TestBuilder {
//!             _phantom: PhantomData,
//!             positive: Some(Setter::Value(value)),
//!             zero: self.zero,
//!         }
//!     }
//! }
//!
//! impl<'a, T1, AsyncFieldMarker, ValidatorOption>
//!     TestBuilder<'a, T1, (), AsyncFieldMarker, ValidatorOption>
//! {
//!     /// # zero
//!     /// - Type: `i32`
//!     /// - Default: `0`
//!     ///
//!     /// An integer having zero as a default value.
//!     pub fn zero(
//!         self,
//!         value: i32
//!     ) -> TestBuilder<'a, T1, i32, AsyncFieldMarker, ValidatorOption> {
//!         TestBuilder {
//!             _phantom: PhantomData,
//!             positive: self.positive,
//!             zero: Some(Setter::Value(value)),
//!         }
//!     }
//! }
//! ```
//! ## How it works
//!
//! The following code
//!
//! ```
//! # use builder_pattern::Builder;
//! # enum Gender {
//! #     Male,
//! #     Female,
//! #     Nonbinary
//! # }
//! # fn is_not_empty(val: String) -> Result<String, ()> {
//! #    Ok(val)
//! # }
//! #[derive(Builder)]
//! struct Person {
//!     #[into]
//!     #[validator(is_not_empty)]
//!     name: String,
//!     age: i32,
//!     #[default(Gender::Nonbinary)]
//!     gender: Gender,
//! }
//! ```
//!
//! will generates:
//!
//! ```
//! # use core::marker::PhantomData;
//! # use builder_pattern::setter::*;
//! # enum Gender {
//! #     Male,
//! #     Female,
//! #     Nonbinary
//! # }
//! # fn is_not_empty(val: String) -> Result<String, ()> {
//! #    Ok(val)
//! # }
//! # struct Person {
//! #     name: String,
//! #     age: i32,
//! #     gender: Gender,
//! # }
//! impl Person {
//!     // Create an empty builder
//!     fn new<'a>() -> PersonBuilder<'a, (), (), (), (), ()> {
//!         PersonBuilder {
//!             _phantom: PhantomData,
//!             age: None,
//!             name: None,
//!             gender: Some(Setter::Value(Gender::Nonbinary)),
//!         }
//!     }
//! }
//! // A builder structure for `Person`.
//! struct PersonBuilder<
//!     'a, T1, T2, T3,
//!     AsyncFieldMarker, // A generic for checking async fields
//!     ValidatorOption,  // A generic for checking lazy validators
//! > {
//!     _phantom: PhantomData<(
//!         T1, T2, T3,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     )>,
//!     // Fields are wrapped in `Option`s.
//!     age: Option<Setter<'a, i32>>,
//!     name: Option<Setter<'a, String>>,
//!     gender: Option<Setter<'a, Gender>>,
//! }
//! // Implementation for `build` function
//! impl<'a, T3>
//!     // It can be called regardless of whether `T3` is `()` or `Gender`.
//!     PersonBuilder<'a, i32, String, T3, (), ()>
//! {
//!     fn build(self) -> Person {
//!         let age = match self.age.unwrap() {
//!             Setter::Value(v) => v,
//!             Setter::Lazy(f) => f(),
//!             _ => unimplemented!(),
//!         };
//!         let name = match self.name.unwrap() {
//!             Setter::Value(v) => v,
//!             Setter::Lazy(f) => f(),
//!             _ => unimplemented!(),
//!         };
//!         let gender = match self.gender.unwrap() {
//!             Setter::Value(v) => v,
//!             Setter::Lazy(f) => f(),
//!             _ => unimplemented!(),
//!         };
//!         Person { age, name, gender }
//!     }
//! }
//! impl<'a, T2, T3, AsyncFieldMarker, ValidatorOption>
//!     PersonBuilder<
//!         'a, (), T2, T3,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     >
//! {
//!     // Setter for `age`
//!     fn age(
//!         self,
//!         value: i32,
//!     ) -> PersonBuilder<
//!         'a, i32, T2, T3,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     > {
//!         PersonBuilder {
//!             _phantom: PhantomData,
//!             age: Some(Setter::Value(value.into())),
//!             name: self.name,
//!             gender: self.gender,
//!         }
//!     }
//! }
//! impl<'a, T1, T3, AsyncFieldMarker, ValidatorOption>
//!     PersonBuilder<
//!         'a, T1, (), T3,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     >
//! {
//!     // Setter for `name`
//!     fn name<IntoType: Into<String>>(
//!         self,
//!         value: IntoType,
//!     ) -> Result<
//!         PersonBuilder<
//!             'a, T1, String, T3,
//!             AsyncFieldMarker,
//!             ValidatorOption,
//!         >,
//!         String,
//!     > {
//!         // Validate the value
//!         match is_not_empty(value.into()) {
//!             Ok(value) => Ok(PersonBuilder {
//!                 _phantom: PhantomData,
//!                 age: self.age,
//!                 name: Some(Setter::Value(value)),
//!                 gender: self.gender,
//!             }),
//!             Err(e) => Err(format!("Validation failed: {:?}", e)),
//!         }
//!     }
//! }
//! impl<'a, T1, T2, AsyncFieldMarker, ValidatorOption>
//!     PersonBuilder<
//!         'a, T1, T2, (),
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     >
//! {
//!     // Setter for `gender`
//!     fn gender(
//!         self,
//!         value: Gender,
//!     ) -> PersonBuilder<
//!         'a, T1, T2, Gender,
//!         AsyncFieldMarker,
//!         ValidatorOption,
//!     > {
//!         PersonBuilder {
//!             _phantom: PhantomData,
//!             age: self.age,
//!             name: self.name,
//!             gender: Some(Setter::Value(value.into())),
//!         }
//!     }
//! }
//! ```

pub use builder_pattern_macro::Builder;

#[doc(hidden)]
pub mod setter;