former 0.11.0

A flexible and extensible implementation of the 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
<!-- {{# generate.module_header{} #}} -->

# Module :: former

[![experimental](https://raster.shields.io/static/v1?label=stability&message=experimental&color=orange&logoColor=eee)](https://github.com/emersion/stability-badges#experimental) [![rust-status](https://github.com/Wandalen/wTools/actions/workflows/ModuleFormerPush.yml/badge.svg)](https://github.com/Wandalen/wTools/actions/workflows/ModuleFormerPush.yml) [![docs.rs](https://img.shields.io/docsrs/former?color=e3e8f0&logo=docs.rs)](https://docs.rs/former) [![Open in Gitpod](https://raster.shields.io/static/v1?label=try&message=online&color=eee&logo=gitpod&logoColor=eee)](https://gitpod.io/#RUN_PATH=.,SAMPLE_FILE=sample%2Frust%2Fformer_trivial_sample%2Fsrc%2Fmain.rs,RUN_POSTFIX=--example%20former_trivial_sample/https://github.com/Wandalen/wTools) [![discord](https://img.shields.io/discord/872391416519737405?color=eee&logo=discord&logoColor=eee&label=ask)](https://discord.gg/m3YfbXpUUY)

A flexible and extensible implementation of the builder pattern.

It offers specialized subformers for common Rust collections like `Vec`, `HashMap`, and `HashSet`, enabling the construction of complex data structures in a fluent and intuitive manner.

## How Former Works

- **Trait Derivation** : By deriving `Former` on a struct, you automatically generate builder methods for each field.
- **Fluent Interface** : Each field's builder method allows for setting the value of that field and returns a mutable reference to the builder,
  enabling method chaining.
- **Optional Fields** : Optional fields can be easily handled without needing to explicitly set them to `None`.
- **Finalization** : The `.form()` method finalizes the building process and returns the constructed struct instance.

This approach abstracts away the need for manually implementing a builder for each struct, making code more readable and maintainable.

## Basic use-case

The provided code snippet illustrates a basic use-case of the Former crate in Rust, which is used to apply the builder pattern for structured and flexible object creation. Below is a detailed explanation of each part of the markdown chapter, aimed at clarifying how the Former trait simplifies struct instantiation.

```rust
#[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
fn main()
{
  use former::Former;

  #[ derive( Debug, PartialEq, Former ) ]
  #[ perform( fn greet_user() ) ]
  pub struct UserProfile
  {
    #[default(1)]
    age : i32,

    username : String,

    #[alias(bio)]
    bio_optional : Option< String >, // Fields could be optional
  }

  impl UserProfile
  {
    fn greet_user(self) -> Self
    {
      println!("Hello, {}", self.username);
      self
    }
  }

  let profile = UserProfile::former()
  .age( 30 )
  .username( "JohnDoe".to_string() )
  .bio_optional( "Software Developer".to_string() ) // Optionally provide a bio
  .form();
  // .perform(); // same as `form()` but will execute method passed to `perform` attribute

  dbg!( &profile );
  // Expected output:
  // &profile = UserProfile {
  //   age: 30,
  //   username: "JohnDoe",
  //   bio_optional: Some("Software Developer"),
  // }

 }
 ```

<details>
<summary>The code above will be expanded to this</summary>

```rust
fn main()
{
  pub struct UserProfile
  {
    age : i32,
    username : String,
    bio_optional : Option< String >,
  }

  impl UserProfile
  {
    pub fn former() -> UserProfileFormer< UserProfile, former::ReturnContainer >
    {
      UserProfileFormer::< UserProfile, former::ReturnContainer >::new()
    }
  }

  #[ derive( Default ) ]
  pub struct UserProfileFormerContainer
  {
    pub age : Option< i32 >,
    pub username : Option< String >,
    pub bio_optional : Option< String >,
  }

  pub struct UserProfileFormer<
    __FormerContext = UserProfile,
    __FormerEnd = former::ReturnContainer,
  >
  where
    __FormerEnd : former::ToSuperFormer< UserProfile, __FormerContext >,
  {
    container : UserProfileFormerContainer,
    context : Option< __FormerContext >,
    on_end : Option< __FormerEnd >,
  }

  impl< __FormerContext, __FormerEnd > UserProfileFormer< __FormerContext, __FormerEnd >
  where
    __FormerEnd : former::ToSuperFormer< UserProfile, __FormerContext >,
  {
    pub fn form( mut self ) -> UserProfile
    {
      let age = if self.container.age.is_some()
      {
        self.container.age.take().unwrap()
      }
      else
      {
        (1).into()
      };
      let username = if self.container.username.is_some()
      {
        self.container.username.take().unwrap()
      }
      else
      {
        {
          trait MaybeDefault< T >
          {
            fn maybe_default( self : &Self ) -> T
            {
              {
                panic!( "Field \'username\' isn\'t initialized" );
              }
            }
          }

          impl< T > MaybeDefault< T > for &core::marker::PhantomData< T > {}

          impl< T > MaybeDefault< T > for core::marker::PhantomData< T >
          where
            T : ::core::default::Default,
            {
              fn maybe_default( self : &Self ) -> T
              {
                T::default()
              }
            }

          ( &core::marker::PhantomData::< String > ).maybe_default()
        }
      };
      let bio_optional = if self.container.bio_optional.is_some()
      {
        Some( self.container.bio_optional.take().unwrap() )
      }
      else
      {
        None
      };
      let result = UserProfile
      {
        age,
        username,
        bio_optional,
      };
      return result;
    }

    pub fn perform( self ) -> UserProfile
    {
      let result = self.form();
      return result.greet_user();
    }

    pub fn new() -> UserProfileFormer< UserProfile, former::ReturnContainer >
    {
      UserProfileFormer::< UserProfile, former::ReturnContainer >::begin( None, former::ReturnContainer )
    }

    pub fn begin(
      context : Option< __FormerContext >,
      on_end : __FormerEnd,
    ) -> Self
    {
      Self
      {
        container : Default::default(),
        context : context,
        on_end : Some( on_end ),
      }
    }

    pub fn end( mut self ) -> __FormerContext
    {
      let on_end = self.on_end.take().unwrap();
      let context = self.context.take();
      let container = self.form();
      on_end.call( container, context )
    }

    pub fn age< Src >( mut self, src : Src ) -> Self
    where
      Src : Into< i32 >,
    {
      if true
      {
        if !self.container.age.is_none()
        {
          panic!( "assertion failed: self.container.age.is_none()" )
        }
      }
      self.container.age = Some( src.into() );
      self
    }

    pub fn username<Src>( mut self, src : Src ) -> Self
    where
      Src : Into< String >,
    {
      if true
      {
        if !self.container.username.is_none()
        {
          panic!( "assertion failed: self.container.username.is_none()" )
        }
      }
      self.container.username = Some( src.into() );
      self
    }
    pub fn bio_optional< Src >( mut self, src : Src ) -> Self
    where
      Src : Into< String >,
    {
      if true
      {
        if !self.container.bio_optional.is_none()
        {
          panic!( "assertion failed: self.container.bio_optional.is_none()" )
        }
      }
      self.container.bio_optional = Some( src.into() );
      self
    }

    pub fn bio< Src >( mut self, src : Src ) -> Self
    where
      Src : Into< String >,
    {
      if true
      {
        if !self.container.bio_optional.is_none()
        {
          panic!( "assertion failed: self.container.bio_optional.is_none()" )
        }
      }
      self.container.bio_optional = Some( src.into() );
      self
    }
  }

  impl UserProfile
  {
    fn greet_user( self ) -> Self
    {
      println!( "Hello, {}", self.username );
      self
    }
  }

  let profile = UserProfile::former()
    .age( 30 )
    .username( "JohnDoe".to_string() )
    .bio_optional( "Software Developer".to_string() )
    .form();
}
```

</details>

### Custom and Alternative Setters

With help of `Former`, it is possible to define multiple versions of a setter for a single field, providing the flexibility to include custom logic within the setter methods. This feature is particularly useful when you need to preprocess data or enforce specific constraints before assigning values to fields. Custom setters should have unique names to differentiate them from the default setters generated by `Former`, allowing for specialized behavior while maintaining clarity in your code.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# {

use former::Former;

/// Structure with a custom setter.
#[ derive( Debug, Former ) ]
pub struct StructWithCustomSetters
{
  word : String,
}

impl StructWithCustomSettersFormer
{

  // Custom alternative setter for `word`
  pub fn word_exclaimed( mut self, value : impl Into< String > ) -> Self
  {
    debug_assert!( self.container.word.is_none() );
    self.container.word = Some( format!( "{}!", value.into() ) );
    self
  }

}

let example = StructWithCustomSetters::former()
.word( "Hello" )
.form();
assert_eq!( example.word, "Hello".to_string() );

let example = StructWithCustomSetters::former()
.word_exclaimed( "Hello" )
.form();
assert_eq!( example.word, "Hello!".to_string() );

# }
```

In the example above showcases a custom alternative setter, `word_exclaimed`, which appends an exclamation mark to the input string before storing it. This approach allows for additional processing or validation of the input data without compromising the simplicity of the builder pattern.

### Custom Setter Overriding

But it's also possible to completely override setter and write its own from scratch. For that use attribe `[ setter( false ) ]` to disable setter.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# {

use former::Former;

/// Structure with a custom setter.
#[ derive( Debug, Former ) ]
pub struct StructWithCustomSetters
{
  #[ setter( false ) ]
  word : String,
}

impl StructWithCustomSettersFormer
{

  // Custom alternative setter for `word`
  pub fn word( mut self, value : impl Into< String > ) -> Self
  {
    debug_assert!( self.container.word.is_none() );
    self.container.word = Some( format!( "{}!", value.into() ) );
    self
  }

}

let example = StructWithCustomSetters::former()
.word( "Hello" )
.form();
assert_eq!( example.word, "Hello!".to_string() );
# }
```

In the example above, the default setter for `word` is disabled, and a custom setter is defined to automatically append an exclamation mark to the string. This method allows for complete control over the data assignment process, enabling the inclusion of any necessary logic or validation steps.

## Custom Default

The `Former` crate enhances struct initialization in Rust by allowing the specification of custom default values for fields through the `default` attribute. This feature not only provides a way to set initial values for struct fields without relying on the `Default` trait but also adds flexibility in handling cases where a field's type does not implement `Default`, or a non-standard default value is desired.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# {

use former::Former;

/// Structure with default attributes.
#[ derive(  Debug, PartialEq, Former ) ]
pub struct ExampleStruct
{
  #[ default( 5 ) ]
  number : i32,
  #[ default( "Hello, Former!".to_string() ) ]
  greeting : String,
  #[ default( vec![ 10, 20, 30 ] ) ]
  numbers : Vec< i32 >,
}

let instance = ExampleStruct::former().form();
let expected = ExampleStruct
{
  number : 5,
  greeting : "Hello, Former!".to_string(),
  numbers : vec![ 10, 20, 30 ],
};
assert_eq!( instance, expected );
dbg!( &instance );
// > &instance = ExampleStruct {
// >    number: 5,
// >    greeting: "Hello, Former!",
// >    numbers: [
// >        10,
// >        20,
// >        30,
// >    ],
// > }
# }
```

The above code snippet showcases the `Former` crate's ability to initialize struct fields with custom default values:
- The `number` field is initialized to `5`.
- The `greeting` field defaults to a greeting message, "Hello, Former!".
- The `numbers` field starts with a vector containing the integers `10`, `20`, and `30`.

This approach significantly simplifies struct construction, particularly for complex types or where defaults beyond the `Default` trait's capability are required. By utilizing the `default` attribute, developers can ensure their structs are initialized safely and predictably, enhancing code clarity and maintainability.

## Concept of subformer

Subformers are specialized builders used within the `Former` framework to construct nested or collection-based data structures like vectors, hash maps, and hash sets. They simplify the process of adding elements to these structures by providing a fluent interface that can be seamlessly integrated into the overall builder pattern of a parent struct. This approach allows for clean and intuitive initialization of complex data structures, enhancing code readability and maintainability.

### Subformer example: Building a Vector

The following example illustrates how to use a `VectorSubformer` to construct a `Vec` field within a struct. The subformer enables adding elements to the vector with a fluent interface, streamlining the process of populating collection fields within structs.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# #[ cfg( not( feature = "no_std" ) ) ]
# {

#[ derive( Debug, PartialEq, former::Former ) ]
pub struct StructWithVec
{
  #[ subformer( former::VectorSubformer ) ]
  vec : Vec< &'static str >,
}

let instance = StructWithVec::former()
.vec()
  .push( "apple" )
  .push( "banana" )
  .end()
.form();

assert_eq!( instance, StructWithVec { vec: vec![ "apple", "banana" ] } );
# }
```

### Subformer example: Building a Hashmap

This example demonstrates the use of a `HashMapSubformer` to build a hash map within a struct. The subformer provides a concise way to insert key-value pairs into the map, making it easier to manage and construct hash map fields.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# #[ cfg( not( feature = "no_std" ) ) ]
# {

use test_tools::exposed::*;

#[ derive( Debug, PartialEq, former::Former ) ]
pub struct StructWithMap
{
  #[ subformer( former::HashMapSubformer ) ]
  map : std::collections::HashMap< &'static str, &'static str >,
}

let struct1 = StructWithMap::former()
.map()
  .insert( "a", "b" )
  .insert( "c", "d" )
  .end()
.form()
;
assert_eq!( struct1, StructWithMap { map : hmap!{ "a" => "b", "c" => "d" } } );
# }
```

### Subformer example: Building a Hashset

In the following example, a `HashSetSubformer` is utilized to construct a hash set within a struct. This illustrates the convenience of adding elements to a set using the builder pattern facilitated by subformers.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# #[ cfg( not( feature = "no_std" ) ) ]
# {

use test_tools::exposed::*;

#[ derive( Debug, PartialEq, former::Former ) ]
pub struct StructWithSet
{
  #[ subformer( former::HashSetSubformer ) ]
  set : std::collections::HashSet< &'static str >,
}

let instance = StructWithSet::former()
.set()
  .insert("apple")
  .insert("banana")
  .end()
.form();

assert_eq!(instance, StructWithSet { set : hset![ "apple", "banana" ] });
# }
```

### Custom Subformer

It is possible to use former of one structure to construct field of another one and integrate it into former of the last one.

The example below illustrates how to incorporate the builder pattern of one structure as a subformer in another, enabling nested struct initialization within a single fluent interface.


Example of how to use former of another structure as subformer of former of current one
function `command` integrate `CommandFormer` into `AggregatorFormer`.

```rust
# #[ cfg( all( feature = "derive_former", feature = "enabled" ) ) ]
# {

fn main()
{
  use std::collections::HashMap;
  use former::Former;

  // Command struct with Former derived for builder pattern support
  #[ derive( Debug, PartialEq, Former ) ]
  pub struct Command
  {
    name : String,
    description : String,
  }

  // Aggregator struct to hold commands
  #[ derive( Debug, PartialEq, Former ) ]
  pub struct Aggregator
  {
    #[ setter( false ) ]
    command : HashMap< String, Command >,
  }

  // Use CommandFormer as custom subformer for AggregatorFormer to add commands by name.
  impl< Context, End > AggregatorFormer< Context, End >
  where
    End : former::ToSuperFormer< Aggregator, Context >,
  {
    pub fn command< IntoName >( self, name : IntoName ) -> CommandFormer< Self, impl former::ToSuperFormer< Command, Self > >
    where
      IntoName: core::convert::Into< String >,
    {
      let on_end = | command : Command, super_former : core::option::Option< Self > | -> Self
      {
        let mut super_former = super_former.unwrap();
        if let Some( ref mut commands ) = super_former.container.command
        {
          commands.insert( command.name.clone(), command );
        }
        else
        {
          let mut commands: HashMap< String, Command > = Default::default();
          commands.insert( command.name.clone(), command );
          super_former.container.command = Some( commands );
        }
        super_former
      };
      let former = CommandFormer::begin( Some( self ), on_end );
      former.name( name )
    }
  }

  let ca = Aggregator::former()
  .command( "echo" )
    .description( "prints all subjects and properties" ) // sets additional properties using custom subformer
    .end()
  .command( "exit" )
    .description( "just exit" ) // Sets additional properties using using custom subformer
    .end()
  .form();

  dbg!( &ca );
  // > &ca = Aggregator {
  // >     command: {
  // >          "echo": Command {
  // >              name: "echo",
  // >              description: "prints all subjects and properties",
  // >          },
  // >          "exit": Command {
  // >              name: "exit",
  // >              description: "just exit",
  // >          },
  // >     },
  // > }
}
# }
```

In this example, the `Aggregator` struct functions as a container for multiple `Command` structs, each identified by a unique command name. The `AggregatorFormer` implements a custom method `command`, which serves as a subformer for adding `Command` instances into the `Aggregator`.

- **Command Definition**: Each `Command` consists of a `name` and a `description`, and we derive `Former` to enable easy setting of these properties using a builder pattern.
- **Aggregator Definition**: It holds a collection of `Command` objects in a `HashMap`. The `#[setter(false)]` attribute is used to disable the default setter, and a custom method `command` is defined to facilitate the addition of commands with specific attributes.
- **Custom Subformer Integration**: The `command` method in the `AggregatorFormer` initializes a `CommandFormer` with a closure that integrates the `Command` into the `Aggregator`'s `command` map upon completion.

This pattern of using a structure's former as a subformer within another facilitates the creation of deeply nested or complex data structures through a coherent and fluent interface, showcasing the powerful capabilities of the `Former` framework for Rust applications.

### To add to your project

```sh
cargo add former
```

### Try out from the repository

```sh
git clone https://github.com/Wandalen/wTools
cd wTools
cd examples/former_trivial
cargo run
```