veryl-std 0.20.3

A modern hardware description language
Documentation
/// Converts a binary encoded bit vector to a Gray encoded bit-vector
/// * Space Complexity: O(WIDTH)
/// * Time Complexity: O(1)
pub module gray_encoder #(
    /// Input and output bit vector width
    param WIDTH: u32 = 32,
) (
    /// Input Binary encoded Bit Vector
    i_bin: input logic<WIDTH>,
    /// Output Gray encoded Bit Vector
    o_gray: output logic<WIDTH>,
) {
    assign o_gray = i_bin ^ (i_bin >> 1);
}

#[test(test_gray)]
embed (inline) sv{{{
module test_gray;
  localparam WIDTH = 16;
  logic [WIDTH-1:0] i_bin;
  logic [WIDTH-1:0] o_gray;
  logic [WIDTH-1:0] o_bin;
  logic [WIDTH-1:0] g_bin;

  always_comb begin
    g_bin = '0;
    for (int i = 0; i < WIDTH; ++i) begin
      g_bin ^= o_gray >> i;
    end
  end

  std_gray_encoder #(WIDTH) dut2(.i_bin, .o_gray);
  std_gray_decoder #(WIDTH) dut1(.i_gray(o_gray), .o_bin);

  initial begin
    for (longint i = 0; i < (1 << WIDTH); ++i) begin
      i_bin = i;
      #1;
      assert(o_bin == g_bin) else $error("error detected");
      assert(i_bin == o_bin) else $error("error detected");
      #1;
    end
  end

endmodule
}}}