logoalt Hacker News

J_Shelby_Jtoday at 7:47 PM1 replyview on HN

Like set an generic marker struct IsEncrypted<T> where T is yes or now and only allow its state to change when proven and then write the shutdown function to only take the yes variant?


Replies

estebanktoday at 11:15 PM

Yes, that would be one way of doing it. You can model off of the Typed Builder pattern:

  struct Builder<const A: bool, const B: bool> {
    a: Option<u32>,
    b: Option<u32>,
  }
  struct Val {
    a: u32,
    b: u32,
  }
  impl<const B: bool> Builder<false, B> {
    fn set_a(self, a: u32) -> Builder<true, B> {
      Builder {
        a: Some(a),
        b: self.b,
      }
    }
  }
  impl<const A: bool> Builder<A, false> {
    fn set_b(self, b: u32) -> Builder<A, true> {
      Builder {
        a: self.a,
        b: Some(b),
      }
    }
  }
  impl Builder<true, true> {
    fn build(self) -> Val {
      Val {
        a: self.a.unwrap(),
        b: self.b.unwrap(),
      }
    }
  }
This won't work for everything, but it is a pattern that I find useful to ensure that things can't happen out of order.