Hacker News new | ask | show | jobs
by kristoff_it 1933 days ago
> In the Zig example, it seems to me (and I have zero knowledge of Zig, so sorry if this is inaccurate) that you can potentially introduce bugs where the same pin is used twice.

Given the code in the blog post, yes. Here's a possible solution:

  pub fn initKeyboardGPIO() void {
      comptime checkPinsAreUnique(10, rows);
      comptime checkPinsAreUnique(100, cols);
      ...
  }

  fn checkPinsAreUnique(max_pin: usize, elems: anytype) void {
      var seen = [1]bool{false} ** (max_pin + 1);
      inline for (elems) |x| {
          if (x.pin > max_pin) {
              @compileError("Found pin value higher than max pin");
          }
  
          if (seen[x.pin]) {
              @compileError("Found duplicate pin!");
          }
  
          seen[x.pin] = true;
      }
  }

If pins happen to be very sparse, one could switch from a basic array to a comptime hashmap: https://github.com/ziglang/zig/blob/master/lib/std/comptime_...

There's also other ways of approaching the implementation depending on the required level of dynamicism, I just hacked together the quickest solution I could think of.

1 comments

Would it be correct to describe this as using comptime to enforce system level constraints? To my naive understanding it looks like comptime combined with type state programming gives one user definable type systems.