Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce builder trait and patterns #32

Open
soareschen opened this issue Dec 1, 2024 · 0 comments
Open

Introduce builder trait and patterns #32

soareschen opened this issue Dec 1, 2024 · 0 comments

Comments

@soareschen
Copy link
Collaborator

Summary

A context-generic builder pattern allows context-generic providers to build a generic context without direct access to the concrete type.

pub trait HasBuilder {
  type Builder;

  fn builder() -> Self::Builder;
}

pub trait CanBuildField<Tag, Value> {
  type Next;

  fn build(self, _tag: PhantomData<Tag>, value: Value) -> Self::Next;
}

pub trait MapType {
  type Map<T>;
}

pub struct Filled;

impl MapType for Filled {
  type Map<T> = T;
}

pub struct Empty;

impl MapType for Empty {
  type Map<T> = ();
}

Example

#[derive(Builder)
pub struct Foo {
  pub bar: u64,
  pub baz: String,
}

would have the following derived:

pub struct FooBuilder<F1: MapType, F2: MapType> {
  pub bar: F1::Map<u64>,
  pub baz: F2::Map<String>,
}

impl HasBuilder for Foo {
  type Builder = FooBuilder<Empty, Empty>;

  fn builder() -> Self::Builder {
    FooBuilder {
      bar: (),
      baz: (),
    }
  }
}

impl<F2: MapType> CanBuild<symbol!("bar"), u32> for FooBuilder<Empty, F2> {
  type Next = FooBuilder<Filled, F2>;

  fn build(self, _tag: PhantomData<Tag>, value: u32) -> Self::Next {
    FooBuilder {
      bar: value,
      baz: self.baz,
    }
  }
}


impl<F1: MapType> CanBuild<symbol!("baz"), String> for FooBuilder<F1, Empty> {
  type Next = FooBuilder<F1, Filled>;

  fn build(self, _tag: PhantomData<Tag>, value: String) -> Self::Next {
    FooBuilder {
      bar: self.bar,
      baz: value,
    }
  }
}

impl From<FooBuilder<Filled, Filled>> for Foo {
  fn from(builder: FooBuilder<Filled, Filled>) -> Self {
    Self {
      bar: builder.bar,
      baz: builder.baz,
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant