former_types 2.34.0

A flexible implementation of the Builder pattern supporting nested builders and collection-specific subformers. Its compile-time structures and traits that are not generated but reused.
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# former_types

Core trait definitions and type system integration for the Former builder pattern ecosystem.

## Overview

`former_types` provides the foundational trait definitions and compile-time structures that power the Former builder pattern implementation. Unlike the main `former` crate which provides the derive macro, this crate contains the reusable type system abstractions that are referenced by generated code but not themselves generated.

The crate establishes the conceptual framework for:
- **Formation definitions**: How entities are linked to their builders
- **Storage management**: How intermediate state is maintained during construction
- **Completion handlers**: How the building process terminates and produces results
- **Collection integration**: How standard collections participate in the builder pattern

This separation allows the macro-generated code to remain minimal while the complex type machinery lives in this stable, reusable crate.

### Scope

#### Responsibility

former_types is responsible for defining the trait hierarchy and type relationships that govern the Former builder pattern. It provides the compile-time contract that all Former implementations must satisfy, enabling type-safe builder patterns with nested structures and collection support.

#### In-Scope

- **Formation definition traits**: `FormerDefinition`, `FormerDefinitionTypes`, entity mapping traits
- **Formation process traits**: `FormingEnd`, `FormerMutator`, `FormerBegin`
- **Storage traits**: `Storage`, `StoragePreform`
- **Collection abstractions**: `Collection`, `CollectionAdd`, `CollectionAssign`, `CollectionFormer`
- **Standard collection implementations**: Vec, HashMap, HashSet, BTreeMap, BTreeSet, LinkedList, VecDeque, BinaryHeap
- **Re-export of component_model_types**: `Assign` trait for component setting

#### Out-of-Scope

- **Derive macros**: Provided by `former_meta`, not this crate
- **Code generation**: This crate provides traits referenced by generated code
- **Runtime reflection**: All operations are compile-time
- **Validation logic**: Beyond what `FormerMutator` provides

#### Boundaries

- **Upstream**: Depends on `collection_tools` and `component_model_types`
- **Downstream**: Used by `former` (main crate) and all generated Former implementations
- **Macro boundary**: This crate provides types; `former_meta` provides generation

## Architecture

### Module Structure

```
former_types/
├── src/
│   ├── lib.rs               # Crate root with namespace organization
│   ├── definition.rs        # Entity-to-definition mapping traits
│   ├── forming.rs           # Formation process management traits
│   ├── storage.rs           # Storage interface traits
│   └── collection/          # Collection-specific implementations
│       ├── mod.rs           # Collection traits and CollectionFormer
│       ├── vector.rs        # Vec implementation
│       ├── hash_map.rs      # HashMap implementation
│       ├── hash_set.rs      # HashSet implementation
│       ├── btree_map.rs     # BTreeMap implementation
│       ├── btree_set.rs     # BTreeSet implementation
│       ├── linked_list.rs   # LinkedList implementation
│       ├── vector_deque.rs  # VecDeque implementation
│       └── binary_heap.rs   # BinaryHeap implementation
├── examples/
│   └── former_types_trivial.rs  # Assign trait usage example
├── Cargo.toml
├── readme.md
└── spec.md
```

### Core Type Relationships

```
FormerDefinition
├── Types: FormerDefinitionTypes + FormerMutator
│   ├── Storage: Default
│   ├── Formed: (result type)
│   └── Context: (contextual info)
├── End: FormingEnd<Types>
├── Storage: Default
├── Formed
└── Context

Entity
├── EntityToDefinition<Context, Formed, End> → Definition
├── EntityToDefinitionTypes<Context, Formed> → Types
├── EntityToFormer<Definition> → Former
└── EntityToStorage → Storage
```

### Formation Lifecycle

```
┌─────────────────────────────────────────────────────────────────┐
│                    Formation Lifecycle                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  1. FormerBegin::former_begin(storage, context, on_end)         │
│     ↓                                                           │
│  2. Builder methods accumulate state in Storage                 │
│     ↓                                                           │
│  3. FormerMutator::form_mutation(&mut storage, &mut context)    │
│     ↓                                                           │
│  4. FormingEnd::call(storage, context) → Formed                 │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

## Public API

### Definition Traits

#### `FormerDefinitionTypes`

Specifies the fundamental types involved in formation.

```rust
pub trait FormerDefinitionTypes: Sized
{
  /// Storage type for intermediate state (must be Default)
  type Storage: Default;

  /// The fully formed entity type
  type Formed;

  /// Contextual information during formation
  type Context;
}
```

#### `FormerDefinition`

Complete formation definition linking types with end behavior.

```rust
pub trait FormerDefinition: Sized
{
  /// Types with mutator support
  type Types: FormerDefinitionTypes< Storage = Self::Storage, Formed = Self::Formed, Context = Self::Context >
            + FormerMutator;

  /// End handler for formation completion
  type End: FormingEnd< Self::Types >;

  /// Storage, Formed, Context (duplicated for convenience)
  type Storage: Default;
  type Formed;
  type Context;
}
```

### Entity Mapping Traits

#### `EntityToDefinition`

Maps an entity to its complete formation definition.

```rust
pub trait EntityToDefinition< Context, Formed, End >
{
  type Definition: FormerDefinition;
  type Types: FormerDefinitionTypes;
}
```

#### `EntityToDefinitionTypes`

Simplified mapping without end condition.

```rust
pub trait EntityToDefinitionTypes< Context, Formed >
{
  type Types: FormerDefinitionTypes;
}
```

#### `EntityToFormer`

Maps an entity to its builder implementation.

```rust
pub trait EntityToFormer< Definition >
where
  Definition: FormerDefinition,
{
  type Former;
  fn __f( _: &Definition ) {}  // Phantom type anchor
}
```

#### `EntityToStorage`

Maps an entity to its storage type.

```rust
pub trait EntityToStorage
{
  type Storage;
}
```

### Formation Process Traits

#### `FormingEnd`

Handler invoked at formation completion.

```rust
pub trait FormingEnd< Definition: FormerDefinitionTypes >
{
  fn call(
    &self,
    storage: Definition::Storage,
    context: Option< Definition::Context >
  ) -> Definition::Formed;
}

// Blanket implementation for closures
impl< Definition, F > FormingEnd< Definition > for F
where
  F: Fn( Definition::Storage, Option< Definition::Context > ) -> Definition::Formed,
  Definition: FormerDefinitionTypes,
{ /* ... */ }
```

#### Pre-built FormingEnd Implementations

```rust
/// Returns the preformed entity (most common)
#[ derive( Debug, Default ) ]
pub struct ReturnPreformed;

/// Returns the storage directly as formed
#[ derive( Debug, Default ) ]
pub struct ReturnStorage;

/// Placeholder that panics if called
#[ derive( Debug, Default ) ]
pub struct NoEnd;

/// Boxed closure for dynamic dispatch
pub struct FormingEndClosure< Definition: FormerDefinitionTypes >
{
  closure: Box< dyn Fn( ... ) -> ... >,
}
```

#### `FormerMutator`

Pre-completion mutation hook.

```rust
pub trait FormerMutator
where
  Self: FormerDefinitionTypes,
{
  /// Called immediately before FormingEnd
  fn form_mutation(
    _storage: &mut Self::Storage,
    _context: &mut Option< Self::Context >
  ) {}
}
```

#### `FormerBegin`

Initiates subform creation with context.

```rust
pub trait FormerBegin< 'storage, Definition >
where
  Definition: FormerDefinition,
  Definition::Storage: 'storage,
  Definition::Context: 'storage,
  Definition::End: 'storage,
{
  fn former_begin(
    storage: Option< Definition::Storage >,
    context: Option< Definition::Context >,
    on_end: Definition::End,
  ) -> Self;
}
```

### Storage Traits

#### `Storage`

Interface for intermediate formation state.

```rust
pub trait Storage: Default
{
  /// The preformed type (before any FormingEnd transformation)
  type Preformed;
}
```

#### `StoragePreform`

Transforms storage to final state.

```rust
pub trait StoragePreform: Storage
{
  /// Convert storage to preformed entity
  fn preform( self ) -> Self::Preformed;
}
```

### Collection Traits

#### `Collection`

Base trait for collection types.

```rust
pub trait Collection
{
  /// Entry type for addition operations
  type Entry;

  /// Value type stored in collection
  type Val;

  /// Convert entry to value
  fn entry_to_val( e: Self::Entry ) -> Self::Val;
}
```

#### `CollectionAdd`

Single-entry addition.

```rust
pub trait CollectionAdd: Collection
{
  /// Add entry, return success indicator
  fn add( &mut self, e: Self::Entry ) -> bool;
}
```

#### `CollectionAssign`

Bulk replacement.

```rust
pub trait CollectionAssign: Collection + IntoIterator< Item = Self::Entry >
{
  /// Replace all entries, return count added
  fn assign< Entries >( &mut self, entries: Entries ) -> usize
  where
    Entries: IntoIterator< Item = Self::Entry >;
}
```

#### Entry/Value Conversion Traits

```rust
/// Convert entry to value (entry perspective)
pub trait EntryToVal< Collection >
{
  type Val;
  fn entry_to_val( self ) -> Self::Val;
}

/// Convert value to entry (collection perspective)
pub trait CollectionValToEntry< Val >
{
  type Entry;
  fn val_to_entry( val: Val ) -> Self::Entry;
}

/// Convert value to entry (value perspective)
pub trait ValToEntry< Collection >
{
  type Entry;
  fn val_to_entry( self ) -> Self::Entry;
}
```

### CollectionFormer

Generic builder for any collection.

```rust
#[ derive( Default ) ]
pub struct CollectionFormer< E, Definition >
where
  Definition: FormerDefinition,
  Definition::Storage: CollectionAdd< Entry = E >,
{
  storage: Definition::Storage,
  context: Option< Definition::Context >,
  on_end: Option< Definition::End >,
}

impl< E, Definition > CollectionFormer< E, Definition >
where
  Definition: FormerDefinition,
  Definition::Storage: CollectionAdd< Entry = E >,
{
  pub fn begin( storage: Option<...>, context: Option<...>, on_end: ... ) -> Self;
  pub fn end( self ) -> Definition::Formed;
  pub fn form( self ) -> Definition::Formed;  // Alias for end
  pub fn add< IntoElement >( self, entry: IntoElement ) -> Self;
  pub fn replace( self, storage: Definition::Storage ) -> Self;
}
```

### Collection-Specific Types

Each collection has:

```rust
// Example for Vec
pub struct VectorDefinition< E, Context, Formed, End > { /* ... */ }
pub struct VectorDefinitionTypes< E, Context = (), Formed = Vec< E > > { /* ... */ }
pub type VectorFormer< E, Context, Formed, End > =
  CollectionFormer< E, VectorDefinition< E, Context, Formed, End > >;

// Extension trait for fluent API
pub trait VecExt< E >: sealed::Sealed
{
  fn former() -> VectorFormer< E, (), Vec< E >, ReturnStorage >;
}
```

Similar patterns exist for:
- `HashMap``HashMapDefinition`, `HashMapFormer`, `HashMapExt`
- `HashSet``HashSetDefinition`, `HashSetFormer`, `HashSetExt`
- `BTreeMap``BTreeMapDefinition`, `BTreeMapFormer`, `BTreeMapExt`
- `BTreeSet``BTreeSetDefinition`, `BTreeSetFormer`, `BTreeSetExt`
- `LinkedList``LinkedListDefinition`, `LinkedListFormer`, `LinkedListExt`
- `VecDeque``VectorDequeDefinition`, `VectorDequeFormer`, `VecDequeExt`
- `BinaryHeap``BinaryHeapDefinition`, `BinaryHeapFormer`, `BinaryHeapExt`

## Usage Patterns

### Implementing FormingEnd

```rust
use former_types::{ FormingEnd, FormerDefinitionTypes };

// Using a closure (blanket impl)
let end = | storage: MyStorage, _ctx: Option< () > | -> MyFormed
{
  MyFormed::from_storage( storage )
};

// Using ReturnPreformed (most common)
use former_types::ReturnPreformed;
let end = ReturnPreformed;  // Calls storage.preform()

// Using FormingEndClosure for dynamic dispatch
use former_types::FormingEndClosure;
let end = FormingEndClosure::new( | storage, ctx | { /* ... */ } );
```

### Using Collection Formers

```rust
use former_types::{ VecExt, HashMapExt, ReturnStorage };

// Direct Vec building
let vec: Vec< i32 > = Vec::former()
  .add( 1 )
  .add( 2 )
  .add( 3 )
  .form();

// HashMap with tuples
use std::collections::HashMap;
let map: HashMap< String, i32 > = HashMap::former()
  .add( ( "one".to_string(), 1 ) )
  .add( ( "two".to_string(), 2 ) )
  .form();
```

### Implementing Custom Former

```rust
use former_types::*;

// Define storage
#[ derive( Default ) ]
struct MyStorage
{
  name: Option< String >,
  value: Option< i32 >,
}

impl Storage for MyStorage
{
  type Preformed = MyStruct;
}

impl StoragePreform for MyStorage
{
  fn preform( self ) -> Self::Preformed
  {
    MyStruct
    {
      name: self.name.unwrap_or_default(),
      value: self.value.unwrap_or( 0 ),
    }
  }
}

// Define types
struct MyDefinitionTypes;

impl FormerDefinitionTypes for MyDefinitionTypes
{
  type Storage = MyStorage;
  type Formed = MyStruct;
  type Context = ();
}

impl FormerMutator for MyDefinitionTypes {}
```

### Using FormerMutator

```rust
use former_types::{ FormerDefinitionTypes, FormerMutator };

struct MyDefinitionTypes;

impl FormerDefinitionTypes for MyDefinitionTypes
{
  type Storage = MyStorage;
  type Formed = MyStruct;
  type Context = ();
}

impl FormerMutator for MyDefinitionTypes
{
  fn form_mutation(
    storage: &mut Self::Storage,
    _context: &mut Option< Self::Context >
  )
  {
    // Validate or transform storage before completion
    if storage.name.as_ref().map( | n | n.is_empty() ).unwrap_or( true )
    {
      storage.name = Some( "default".to_string() );
    }
  }
}
```

### Nested Subformers with FormerBegin

```rust
use former_types::FormerBegin;

// In generated code, subformers use FormerBegin to integrate with parent
impl< 'a, Definition > FormerBegin< 'a, Definition > for MyFormer< Definition >
where
  Definition: FormerDefinition,
{
  fn former_begin(
    storage: Option< Definition::Storage >,
    context: Option< Definition::Context >,
    on_end: Definition::End,
  ) -> Self
  {
    Self
    {
      storage: storage.unwrap_or_default(),
      context,
      on_end: Some( on_end ),
    }
  }
}
```

## Dependencies and Consumers

### Dependencies

| Dependency | Purpose |
|------------|---------|
| `collection_tools` | Collection utilities and constructors |
| `component_model_types` | `Assign` trait for component setting |

### Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `enabled` || Enable the crate |
| `types_former` || Enable core Former trait definitions |
| `no_std` | - | no_std compatibility |
| `use_alloc` | - | Enable alloc in no_std |
| `full` | - | Enable all features |

### Consumers

| Consumer | Relationship |
|----------|--------------|
| `former` | Main user-facing crate, depends on these types |
| `former_meta` | Proc macro generates code using these traits |
| User code | Generated Former implementations reference these |

## Design Rationale

### Why Separate from former?

1. **Compile time**: Types don't change; macro output changes
2. **Code size**: Shared types reduce generated code duplication
3. **Stability**: Type definitions are more stable than macro output
4. **Testing**: Types can be tested independently of macro

### Why Associated Types Over Generics?

Associated types in `FormerDefinitionTypes` provide:
- **Single instantiation**: One definition per entity
- **Type inference**: Compiler can deduce related types
- **Cleaner API**: No need to specify redundant type parameters

### Why FormingEnd as Trait?

FormingEnd as a trait (vs closure type) enables:
- **Named implementations**: `ReturnPreformed`, `ReturnStorage`
- **Type-level dispatch**: Different behaviors via types
- **Zero-cost abstraction**: Monomorphization eliminates indirection
- **Closure support**: Blanket impl for `Fn(...)`

### Why FormerMutator?

FormerMutator exists separately from FormingEnd because:
- **Different concerns**: Mutation is entity-specific; end is context-specific
- **Composition**: Can have default mutator with custom end
- **Subforms**: Mutator applies regardless of how entity is formed

## Testing Strategy

### Test Categories

1. **Trait implementation tests**: Verify implementations satisfy contracts
2. **Collection former tests**: Verify all collection types work correctly
3. **Integration tests**: Verify interaction between traits

### Example Tests

```rust
#[ test ]
fn vec_former_basic()
{
  let vec: Vec< i32 > = Vec::former()
    .add( 1 )
    .add( 2 )
    .form();
  assert_eq!( vec, vec![ 1, 2 ] );
}

#[ test ]
fn return_preformed_works()
{
  // Test that ReturnPreformed correctly calls preform()
}

#[ test ]
fn former_mutator_is_called()
{
  // Test that form_mutation is invoked before FormingEnd
}
```

## Future Considerations

### Potential Enhancements

1. **Async formation**: `AsyncFormingEnd` for async builders
2. **Validation traits**: Built-in validation during formation
3. **Serialization support**: Serde integration for storage
4. **Error handling**: `TryFormingEnd` with Result return

### Known Limitations

1. **No runtime reflection**: All type relationships are compile-time
2. **Trait complexity**: Deep trait hierarchy can confuse error messages
3. **Collection coverage**: Some exotic collections not yet supported

## Adoption Guidelines

### When to Use Directly

- Implementing custom Former without derive macro
- Extending Former for new collection types
- Building higher-level builder abstractions
- Understanding generated code behavior

### When to Use former Instead

- Normal struct/enum builder pattern usage
- Standard collection building
- Any case where derive macro suffices

### Integration Pattern

```rust
// In Cargo.toml, usually you depend on `former`
[dependencies]
former = "2.32"

// `former` re-exports `former_types`
use former::exposed::*;

// Only use `former_types` directly for advanced scenarios
[dependencies]
former_types = "2.32"
```

## Related Crates

| Crate | Relationship |
|-------|--------------|
| `former` | Main crate; re-exports this + provides derive macro |
| `former_meta` | Proc macro; generates code using these types |
| `collection_tools` | Collection utilities used by this crate |
| `component_model_types` | Provides `Assign` trait |

## References

- [Builder Pattern in Rust]https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
- [former crate documentation]https://docs.rs/former