builder_derive

Crates.iobuilder_derive
lib.rsbuilder_derive
version0.0.1
sourcesrc
created_at2024-05-05 16:35:49.216979
updated_at2024-05-05 16:35:49.216979
descriptionA simple proc macro that allows the user to auto generate a simple builder pattern.
homepage
repositoryhttps://github.com/ivario123/builder_derive
max_upload_size
id1230342
size20,008
Ivar Jönsson (ivario123)

documentation

README

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.

Commit count: 7

cargo fmt