Hacker News new | ask | show | jobs
by bombela 17 days ago

  pub trait Payloads {
      type Read;
      type Write;
  }

  pub enum FileOp<P: Payloads> {
      Read(P::Read),
      Write(P::Write),
  }

  pub struct Inputs;

  impl Payloads for Inputs {
      type Read = ();
      type Write = u8;
  }

  pub type Request = FileOp<Inputs>;

  pub struct Outputs;

  impl Payloads for Outputs {
      type Read = u8;
      type Write = ();
  }

  pub type Reply = FileOp<Outputs>;

  pub fn execute(request: Request) -> Reply {
      match request {
          Request::Read(()) => Reply::Read(42),
          Request::Write(_) => Reply::Write(()),
      }
  }
1 comments

This looks like it would handle synchronizing multiple variant records/enums, and if you just wanted the "plain" enum without any payload, you'd need to do:

  pub struct Bare;
  impl Payloads for Bare {
    type Read = ();
    type Write = ();
  }

  pub type BareFileOp = FileOp<Bare>
Correct? So you'd need to create it with BareFileOp::Read(()), but at least it wouldn't carry any overhead of actually containing data.
Yes, all correct. "()" the unit type, is a zero sized type (zst).

And you don't have to have 1:1 type to enum discriminant:

  trait Payloads {
      type Read;
      type Write;
  }

  enum FileOp<P: Payloads> {
      Flush,
      Read(P::Read),
      Write { data: P::Write },
  }

  struct Inputs;

  impl Payloads for Inputs {
      type Read = ();
      type Write = u8;
  }

  type Request = FileOp<Inputs>;

  // enum item construction
  Request::Flush;
  Request::Read(());
  Request::Write { data: 42 };

You can also make an item impossible to exist using the never type:

  struct WriteOnly;

  impl Payloads for WriteOnly {
      type Read = !;
      type Write = u8;
  }