Skip to content

Instantly share code, notes, and snippets.

@sahandevs
Last active July 3, 2022 07:19
Show Gist options
  • Save sahandevs/0bf0bf448fc4324b5b3089c11383a5f6 to your computer and use it in GitHub Desktop.
Save sahandevs/0bf0bf448fc4324b5b3089c11383a5f6 to your computer and use it in GitHub Desktop.
Compile-time safe Builder pattern / idea: https://github.com/maminrayej
pub mod ItemBuilder {
pub struct ItemBuilder<const A_SET: bool, const C_SET: bool, const F_SET: bool> {
a: Option<usize>,
b: Option<usize>,
c: Option<usize>,
d: Option<usize>,
e: Option<usize>,
f: Option<usize>,
}
pub fn new() -> ItemBuilder<false, false, false> {
ItemBuilder { a: None, b: None, c: None, d: None, e: None, f: None }
}
impl<const A: bool, const B: bool, const F: bool> ItemBuilder<A, B, F> {
pub fn a(self, value: usize) -> ItemBuilder<true, B, F> {
ItemBuilder {
a: Some(value),
b: self.b,
c: self.c,
d: self.d,
e: self.e,
f: self.f,
}
}
pub fn b(mut self, value: usize) -> Self {
self.b = Some(value);
self
}
pub fn c(self, value: usize) -> ItemBuilder<A, true, F> {
ItemBuilder {
a: self.a,
b: self.b,
c: Some(value),
d: self.d,
e: self.e,
f: self.f,
}
}
pub fn d(mut self, value: usize) -> Self {
self.d = Some(value);
self
}
pub fn e(mut self, value: usize) -> Self {
self.e = Some(value);
self
}
pub fn f(self, value: usize) -> ItemBuilder<A, B, true> {
ItemBuilder {
a: self.a,
b: self.b,
c: self.c,
d: self.d,
e: self.e,
f: Some(value),
}
}
}
impl ItemBuilder<true, true, true> {
pub fn build(self) -> super::Item {
unsafe {
super::Item {
a: self.a.unwrap_unchecked(),
b: self.b,
c: self.c.unwrap_unchecked(),
d: self.d,
e: self.e,
f: self.f.unwrap_unchecked(),
}
}
}
}
}
pub struct Item {
pub a: usize,
pub b: Option<usize>,
pub c: usize,
pub d: Option<usize>,
pub e: Option<usize>,
pub f: usize,
}
fn test() {
let builder = ItemBuilder::new()
.a(1)
.c(3)
.a(3)
.f(4)
.a(1)
.build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment