Crate former

Source
Expand description

§Module :: former

experimental rust-status docs.rs Open in Gitpod discord

A flexible implementation of the Builder pattern supporting nested builders and collection-specific subformers.

§What is Former?

The former crate provides a powerful derive macro, #[ derive( Former ) ], that automatically implements the Builder pattern for your Rust structs and enums.

Its primary goal is to simplify the construction of complex objects, especially those with numerous fields, optional values, default settings, collections, or nested structures, making your initialization code more readable and maintainable.

§Why Use Former?

Compared to manually implementing the Builder pattern or using other builder crates, former offers several advantages:

  • Reduced Boilerplate: #[ derive( Former ) ] automatically generates the builder struct, storage, and setters, saving you significant repetitive coding effort.
  • Fluent & Readable API: Construct objects step-by-step using clear, chainable methods (.field_name( value )).
  • Effortless Defaults & Optionals: Fields automatically use their Default implementation if not set. Option< T > fields are handled seamlessly – you only set them if you have a Some( value ). Custom defaults can be specified easily with #[ former( default = ... ) ].
  • Powerful Collection & Nested Struct Handling: former truly shines with its subformer system. Easily build Vec, HashMap, HashSet, and other collections element-by-element, or configure nested structs using their own dedicated formers within the parent’s builder chain. This is often more complex to achieve with other solutions.

§Installation

Add former to your Cargo.toml:

cargo add former

The default features enable the Former derive macro and support for standard collections, covering most common use cases.

§Basic Usage

Derive Former on your struct and use the generated ::former() method to start building:

  use former::Former;

  #[ derive( Debug, PartialEq, Former ) ]
  pub struct UserProfile
  {
    age : i32, // Required field
    username : String, // Required field
    bio : Option< String >, // Optional field
  }

  let profile = UserProfile::former()
  .age( 30 )
  .username( "JohnDoe".to_string() )
  // .bio is optional, so we don't *have* to call its setter
  .form();

  let expected = UserProfile
  {
    age : 30,
    username : "JohnDoe".to_string(),
    bio : None, // Defaults to None if not set
  };
  assert_eq!( profile, expected );
  dbg!( &profile );
  // > &profile = UserProfile {
  // >     age: 30,
  // >     username: "JohnDoe",
  // >     bio: None,
  // > }

  // Example setting the optional field:
  let profile_with_bio = UserProfile::former()
  .age( 30 )
  .username( "JohnDoe".to_string() )
  .bio( "Software Developer".to_string() ) // Set the optional bio
  .form();

  let expected_with_bio = UserProfile
  {
    age : 30,
    username : "JohnDoe".to_string(),
    bio : Some( "Software Developer".to_string() ),
  };
  assert_eq!( profile_with_bio, expected_with_bio );
  dbg!( &profile_with_bio );
  // > &profile_with_bio = UserProfile {
  // >     age: 30,
  // >     username: "JohnDoe",
  // >     bio: Some( "Software Developer" ),
  // > }

Run this example locally | Try it online

§Handling Optionals and Defaults

Former makes working with optional fields and default values straightforward:

  • Option< T > Fields: As seen in the basic example, fields of type Option< T > automatically default to None. You only need to call the setter if you have a Some( value ).

  • Custom Defaults: For required fields that don’t implement Default, or when you need a specific default value other than the type’s default, use the #[ former( default = ... ) ] attribute:

  use former::Former;

  #[ derive( Debug, PartialEq, Former ) ]
  pub struct Config
  {
    #[ former( default = 1024 ) ] // Use 1024 if .buffer_size() is not called
    buffer_size : i32,
    timeout : Option< i32 >, // Defaults to None
    #[ former( default = true ) ] // Default for bool
    enabled : bool,
  }

  // Only set the optional timeout
  let config1 = Config::former()
  .timeout( 5000 )
  .form();

  assert_eq!( config1.buffer_size, 1024 ); // Got default
  assert_eq!( config1.timeout, Some( 5000 ) );
  assert_eq!( config1.enabled, true ); // Got default

  // Set everything, overriding defaults
  let config2 = Config::former()
  .buffer_size( 4096 )
  .timeout( 1000 )
  .enabled( false )
  .form();

  assert_eq!( config2.buffer_size, 4096 );
  assert_eq!( config2.timeout, Some( 1000 ) );
  assert_eq!( config2.enabled, false );

See full example code

§Building Collections & Nested Structs (Subformers)

Where former significantly simplifies complex scenarios is in building collections (Vec, HashMap, etc.) or nested structs. It achieves this through subformers. Instead of setting the entire collection/struct at once, you get a dedicated builder for the field:

Example: Building a Vec

  use former::Former;

  #[ derive( Debug, PartialEq, Former ) ]
  pub struct Report
  {
    title : String,
    #[ subform_collection ] // Enables the `.entries()` subformer
    entries : Vec< String >,
  }

  let report = Report::former()
  .title( "Log Report".to_string() )
  .entries() // Get the subformer for the Vec
    .add( "Entry 1".to_string() ) // Use subformer methods to modify the Vec
    .add( "Entry 2".to_string() )
    .end() // Return control to the parent former (ReportFormer)
  .form(); // Finalize the Report

  assert_eq!( report.title, "Log Report" );
  assert_eq!( report.entries, vec![ "Entry 1".to_string(), "Entry 2".to_string() ] );
  dbg!( &report );
  // > &report = Report {
  // >     title: "Log Report",
  // >     entries: [
  // >         "Entry 1",
  // >         "Entry 2",
  // >     ],
  // > }

See Vec example | See HashMap example

former provides different subform attributes (#[ subform_collection ], #[ subform_entry ], #[ subform_scalar ]) for various collection and nesting patterns.

§Key Features Overview

  • Automatic Builder Generation: #[ derive( Former ) ] for structs and enums.
  • Fluent API: Chainable setter methods for a clean construction flow.
  • Defaults & Optionals: Seamless handling of Default values and Option< T > fields. Custom defaults via #[ former( default = ... ) ].
  • Subformers: Powerful mechanism for building nested structures and collections:
    • #[ subform_scalar ]: For fields whose type also derives Former.
    • #[ subform_collection ]: For collections like Vec, HashMap, HashSet, etc., providing methods like .add() or .insert().
    • #[ subform_entry ]: For collections where each entry is built individually using its own former.
  • Customization:
    • Rename setters: #[ scalar( name = ... ) ], #[ subform_... ( name = ... ) ].
    • Disable default setters: #[ scalar( setter = false ) ], #[ subform_... ( setter = false ) ].
    • Define custom setters directly in impl Former.
    • Specify collection definitions: #[ subform_collection( definition = ... ) ].
  • Advanced Control:
    • Storage-only fields: #[ storage_fields( ... ) ].
    • Custom mutation logic: #[ mutator( custom ) ] + impl FormerMutator.
    • Custom end-of-forming logic: Implement FormingEnd.
    • Custom collection support: Implement Collection traits.
  • Component Model: Separate derives (Assign, ComponentFrom, ComponentsAssign, FromComponents) for type-based field access and conversion (See former_types documentation).

§Where to Go Next

Modules§

dependency
Namespace with dependencies.
derive
exposed
Exposed namespace of the module.
orphan
Parented namespace of the module.
own
Own namespace of the module.
prelude
Prelude to use essentials: use my_module::prelude::*.

Structs§

BTreeMapDefinition
Represents the formation definition for a hash map-like collection within the former framework.
BTreeMapDefinitionTypes
Holds the generic parameters for the BTreeMapDefinition.
BTreeSetDefinition
Represents the formation definition for a binary tree set-like collection within the former framework.
BTreeSetDefinitionTypes
Holds the generic parameters for the BTreeSetDefinition.
BinaryHeapDefinition
Represents the formation definition for a binary heap-like collection within the former framework.
BinaryHeapDefinitionTypes
Holds the generic parameters for the BinaryHeapDefinition.
CollectionFormer
A builder structure for constructing collections with a fluent and flexible interface.
FormingEndClosure
A wrapper around a closure to be used as a FormingEnd.
HashMapDefinition
Represents the formation definition for a hash map-like collection within the former framework.
HashMapDefinitionTypes
Holds the generic parameters for the HashMapDefinition.
HashSetDefinition
Represents the formation definition for a hash set-like collection within the former framework.
HashSetDefinitionTypes
Holds the generic parameters for the HashSetDefinition.
LinkedListDefinition
Represents the formation definition for a list-like collection within the former framework.
LinkedListDefinitionTypes
Holds the generic parameters for the LinkedListDefinition.
NoEnd
A placeholder FormingEnd used when no end operation is required or applicable.
ReturnPreformed
A FormingEnd implementation that directly returns the formed collection as the final product of the forming process.
ReturnStorage
A FormingEnd implementation that returns the storage itself as the formed entity, disregarding any contextual data.
VecDequeDefinition
Represents the formation definition for a vector deque-like collection within the former framework.
VecDequeDefinitionTypes
Holds the generic parameters for the VecDequeDefinition.
VectorDefinition
Represents the formation definition for a vector-like collection within the former framework.
VectorDefinitionTypes
Holds the generic parameters for the VectorDefinition.

Traits§

Assign
Provides a generic interface for setting a component of a certain type on an object.
AssignWithType
The AssignWithType trait provides a mechanism to set a component on an object, utilizing the type information explicitly. This trait extends the functionality of Assign by allowing implementers to specify the component’s type at the method call site, enhancing expressiveness in code that manipulates object states.
BTreeMapExt
Provides an extension method for hash maps to facilitate the use of the builder pattern.
BTreeSetExt
Provides an extension method for binary tree sets to facilitate the use of the builder pattern.
BinaryHeapExt
Provides an extension method for binary heaps to facilitate the use of the builder pattern.
Collection
Represents a collection by defining the types of entries and values it handles.
CollectionAdd
Provides functionality to add individual entries to a collection.
CollectionAssign
Defines the capability to replace all entries in a collection with a new set of entries.
CollectionValToEntry
Provides a mechanism for transforming a value back into a collection-specific entry format.
EntityToDefinition
Maps a type of entity to its corresponding former definition. This trait provides a linkage between the entity and its definition, allowing the formation logic to understand what definition to apply during the formation process.
EntityToDefinitionTypes
Provides a mapping between a type of entity and its associated formation type definitions.
EntityToFormer
Maps a type of entity to its corresponding former. This trait binds an entity type to a specific former, facilitating the use of custom formers in complex formation scenarios.
EntityToStorage
Maps a type of entity to its storage type. This trait defines what storage structure is used to hold the interim state of an entity during its formation.
EntryToVal
Facilitates the conversion of collection entries to their corresponding value representations.
FormerBegin
A trait for initiating a structured subforming process with contextual and intermediary storage linkage.
FormerDefinition
Expands on FormerDefinitionTypes by incorporating an ending mechanism for the formation process. This trait connects the formation types with a specific endpoint, defining how the formation process concludes, including any necessary transformations or validations.
FormerDefinitionTypes
Defines the fundamental components involved in the formation of an entity. This trait specifies the types of storage, the formed entity, and the context used during the formation process.
FormerMutator
Provides a mechanism for mutating the context and storage just before the forming process is completed.
FormingEnd
Defines a handler for the end of a subforming process, enabling the return of the original context.
HashMapExt
Provides an extension method for hash maps to facilitate the use of the builder pattern.
HashSetExt
Provides an extension method for HashSet to facilitate the use of the builder pattern.
LinkedListExt
Provides an extension method for lists to facilitate the use of the builder pattern.
OptionExt
Extension trait to provide a method for setting a component on an Option<Self> if the Option is currently None. If the Option is Some, the method will delegate to the Assign trait’s assign method.
Storage
Defines the storage interface for entities being constructed using a forming pattern.
StoragePreform
Provides a mechanism to finalize the forming process by converting storage into its final formed state.
ValToEntry
Facilitates the conversion of values back into entries for specific collection types.
VecDequeExt
Provides an extension method for vector deques to facilitate the use of the builder pattern.
VecExt
Provides an extension method for vectors to facilitate the use of the builder pattern.

Type Aliases§

BTreeMapFormer
Provides a streamlined builder interface for constructing hash map-like collections.
BTreeSetFormer
Provides a streamlined builder interface for constructing binary tree set-like collections.
BinaryHeapFormer
Provides a streamlined builder interface for constructing binary heap-like collections.
HashMapFormer
Provides a streamlined builder interface for constructing hash map-like collections.
HashSetFormer
Provides a concise alias for CollectionFormer configured specifically for HashSet-like collections.
LinkedListFormer
Provides a streamlined builder interface for constructing list-like collections.
VecDequeFormer
Provides a streamlined builder interface for constructing vector deque-like collections.
VectorFormer
Provides a streamlined builder interface for constructing vector-like collections.

Derive Macros§

Assign
Derives the Assign trait for struct fields, allowing each field to be set with a value that can be converted into the field’s type.
ComponentFrom
Macro to implement From for each component (field) of a structure. This macro simplifies the creation of From trait implementations for struct fields, enabling easy conversion from a struct reference to its field types.
ComponentsAssign
Derives the ComponentsAssign trait for a struct, enabling components_assign which set all fields at once.
Former
Derive macro for generating a Former struct, applying a Builder Pattern to the annotated struct.
FromComponents
A procedural macro to automatically derive the From<T> trait implementation for a struct, enabling instances of one type to be converted from instances of another type.