#derive-builder #builder-pattern #user

macro builder_derive

A simple proc macro that allows the user to auto generate a simple builder pattern

1 unstable release

0.0.1 May 5, 2024

#35 in #derive-builder

28 downloads per month
Used in disarmv7

Custom license

19KB
367 lines

builder-derive

builder-derive provides two main macros, the builder and consumer macro, this crate mainly exists as a support crate for disarmv7 but could be used outside of that. For most cases, there exist better alternatives such as derive_builder but that one requires unwraps which, in a builder should not be needed as the type system can guarantee safe construction.

Examples

Builder

use builder_derive::Builder;

#[derive(Builder)]
pub struct CoolStruct {
    field_a: usize,
    field_b: i32
}


let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();

assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);

If any fields are not specified it will fail.

use builder_derive::Builder;

#[derive(Builder)]
pub struct CoolStruct {
    field_a: usize,
    field_b: i32
}


let implementation = CoolStruct::builder().set_field_a(2).complete();

Consumer

The consumer pattern is a bit niche but it is useful if you have a bunch of autogenerated structs and want to be certain that you do not miss any cases.

use builder_derive::{Builder,Consumer};

#[derive(Builder,Consumer,PartialEq)]
pub struct CoolStruct {
    field_a: usize,
    field_b: i32
}


let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();

assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);

let consumer = implementation.consumer();
let (field_a,consumer) = consumer.consume_field_a();
let (field_b,consumer) = consumer.consume_field_b();
consumer.consume();
assert!(field_a == 2);
assert!(field_b == 4);

If any fields are not consumed it will fail to compile.

use builder_derive::{Builder,Consumer};

#[derive(Builder,Consumer,PartialEq)]
pub struct CoolStruct {
    field_a: usize,
    field_b: i32
}


let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();

assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);

let consumer = implementation.consumer();
let (field_a,consumer) = consumer.consume_field_a();
consumer.consume();
assert!(field_a == 2);

Future extensions

It would be nice with an extension that allows for generics and an extension that allows the user to specify a conversion function that converts into the field type.

License

This repository is licensed under the MIT license and any contributions shall be licensed under the same license unless explicitly stated otherwise.

Dependencies

~245–700KB
~17K SLoC