Testbench Code
`timescale 1ns/1ps
module tb_nibble_swap_task;
// 1) Inputs
reg [7:0] x;
// 2) DUT outputs
wire [7:0] y;
// 3) Expected (prefixed expected_)
reg [7:0] expected_y;
// 4) Mismatch (HIGH on fail)
reg mismatch;
wire mismatch_w = (y !== expected_y);
// Accounting
integer TOTAL_TEST_CASES = 0;
integer TOTAL_PASSED_TEST_CASES = 0;
integer TOTAL_FAILED_TEST_CASES = 0;
// VCD limit (record at most 32 cases)
integer VCD_MAX_CASES = 32;
// DUT
nibble_swap_task dut(.x(x), .y(y));
// VCD dump (Inputs -> Outputs -> Expected -> Mismatch)
initial begin
$dumpfile("tb_nibble_swap_task.vcd");
$dumpvars(0,
tb_nibble_swap_task.x, // Inputs
tb_nibble_swap_task.y, // Outputs
tb_nibble_swap_task.expected_y, // Expected
tb_nibble_swap_task.mismatch // Mismatch
);
$dumpon; // start at time 0
end
// Header + init
initial begin
x = 8'h00; expected_y = 8'h00; mismatch = 1'b0;
$display(" x | y | expected_y | mismatch");
$display("----------------------------------------");
end
// Apply + check (EXPECTED FIRST -> WAIT -> COMPARE)
task apply_and_check;
input [7:0] tx;
begin
x = tx;
// compute expected first to avoid race in waveform
expected_y = {tx[3:0], tx[7:4]};
#1; // let DUT settle
mismatch = mismatch_w;
TOTAL_TEST_CASES = TOTAL_TEST_CASES + 1;
if (!mismatch) TOTAL_PASSED_TEST_CASES = TOTAL_PASSED_TEST_CASES + 1;
else TOTAL_FAILED_TEST_CASES = TOTAL_FAILED_TEST_CASES + 1;
$display("0x%02h | 0x%02h | 0x%02h | %0d",
x, y, expected_y, mismatch);
if (TOTAL_TEST_CASES == VCD_MAX_CASES) $dumpoff;
end
endtask
integer i;
integer seed;
initial begin
seed = 32'hB1B1_C0DE ^ $time;
// Directed, compact (≤ 20 lines)
apply_and_check(8'h00); // -> 0x00
apply_and_check(8'hFF); // -> 0xFF
apply_and_check(8'hF0); // -> 0x0F
apply_and_check(8'h0F); // -> 0xF0
apply_and_check(8'hA5); // -> 0x5A
apply_and_check(8'h3C); // -> 0xC3
apply_and_check(8'h12); // -> 0x21
apply_and_check(8'h81); // -> 0x18
// Small sweep (adds 8 rows, still under 32 total)
for (i = 0; i < 8; i = i + 1)
apply_and_check({4'hF - i[3:0], i[3:0]});
// A few randoms (stay under 32 total)
repeat (8) apply_and_check($random(seed));
// Summary logs
$display("----------------------------------------");
$display("TOTAL_TEST_CASES=%0d", TOTAL_TEST_CASES);
$display("TOTAL_PASSED_TEST_CASES=%0d", TOTAL_PASSED_TEST_CASES);
$display("TOTAL_FAILED_TEST_CASES=%0d", TOTAL_FAILED_TEST_CASES);
$display("ALL_TEST_CASES_PASSED=%s", (TOTAL_FAILED_TEST_CASES==0) ? "true" : "false");
#2 $finish;
end
endmodule