case.sv 1.42 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
`default_nettype none

module Example(
    input logic [1:0] select,
    // This is an array of 3 (4-bit wide) elements
    output logic [2:0][3:0] data
);
    UniqueCase case0(.select, .data(data[0]));
    WildcardCase case1(.select, .data(data[1]));
    DefaultCase case2(.select, .data(data[2]));

endmodule

module UniqueCase(
    input logic [1:0] select,
    output logic [3:0] data
);

    always_comb begin
        data = 4'b0;
        unique case(select)
            2'd0: data = 4'ha;
            2'd1: data = 4'h6;
            2'd2: data = 4'h3;
            /* unique means that the toolchain can assume 2'd3 will never happen */
        endcase
    end

endmodule

module WildcardCase(
    input logic [1:0] select,
    output logic [3:0] data
);

    always_comb begin
        data = 4'b0;
        unique casez(select)
            2'b00: data = 4'h3;
            2'b1?: data = 4'hd;
            // Unique means that the toolchain can assume 2'b01 will never happen
        endcase
    end

endmodule

module DefaultCase(
    input logic [1:0] select,
    output logic [3:0] data
);

    always_comb begin
        data = 4'b0;
        case (select)
            2'b00: data = 4'h7;
            2'b01: data = 4'h9;
            default: data = 4'h8;
        endcase
    end

endmodule

// There is also a casex construct, but it is very dangerous and not recommend to be used in real designs.
// https://www.verilogpro.com/verilog-case-casez-casex/