// CD4532B: 8-bit priority encoder.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// With EI = 1, Q2 Q1 Q0 is the number of the highest input that is 1, and
// GS = 1; when no input is 1, Q = 0, GS = 0 and EO = 1, which enables the
// next, lower encoder of a cascade.  EI = 0 sets all outputs to 0.

module cd4532
(
    input  logic d4,  // Pin 1
    input  logic d5,  // Pin 2
    input  logic d6,  // Pin 3
    input  logic d7,  // Pin 4:  highest priority
    input  logic ei,  // Pin 5:  enable in
    output logic q2,  // Pin 6
    output logic q1,  // Pin 7
                      // Pin 8:  VSS
    output logic q0,  // Pin 9
    input  logic d0,  // Pin 10: lowest priority
    input  logic d1,  // Pin 11
    input  logic d2,  // Pin 12
    input  logic d3,  // Pin 13
    output logic gs,  // Pin 14: group select
    output logic eo   // Pin 15: enable out
                      // Pin 16: VDD
);

    wire [7:0] d = { d7, d6, d5, d4, d3, d2, d1, d0 };

    logic [2:0] q;

    always_comb
    begin
        q = 3'd0;

        for (int i = 0; i < 8; i ++)
            if (d [i])
                q = 3'(i);
    end

    assign { q2, q1, q0 } = ei ? q : 3'd0;
    assign gs = ei &   (| d);
    assign eo = ei & ~ (| d);

endmodule
