// CD74HC40105: FIFO of sixteen 4-bit words.
//
// Ports in pin order, named as in the datasheet.  The power pins, GND (8)
// and VCC (16), are left out.
//
// A rising edge on SI (shift in) puts D0-D3 at the end of the queue while
// DIR (data-in ready) is 1; with all sixteen places full DIR is 0 and SI is
// ignored.  While DOR (data-out ready) is 1, Q0-Q3 show the word at the
// head of the queue; a falling edge on SO (shift out) drops it and the next
// word moves up.  With the queue empty DOR is 0 and SO is ignored.  MR
// (master reset) is active high and asynchronous: it empties the queue at
// once.  OE (three-state control) 1 turns Q0-Q3 off.
//
// The chip passes a word from place to place inside, so a word takes up to
// about half a microsecond at 5 V to reach the output, and DIR drops for a
// moment after every load.  The model leaves these delays out: a word is at
// the output right after the edge that loads it.  It also leaves out two
// details: if SI rises while the queue is full, the chip loads the word as
// soon as a place frees, if SI is still 1; and if SI is 1 at the end of MR,
// the chip loads D0-D3.  The model ignores both.
//
// Synthesizable, with SI and SO as two clocks.

module cd40105
(
    input  logic oe,   // Pin 1:  1 = Q0-Q3 off
    output logic dir,  // Pin 2:  1 = room for a word
    input  logic si,   // Pin 3:  rising edge = load
    input  logic d0,   // Pin 4
    input  logic d1,   // Pin 5
    input  logic d2,   // Pin 6
    input  logic d3,   // Pin 7
                       // Pin 8:  GND
    input  logic mr,   // Pin 9:  1 = empty the queue at once
    output logic q3,   // Pin 10
    output logic q2,   // Pin 11
    output logic q1,   // Pin 12
    output logic q0,   // Pin 13
    output logic dor,  // Pin 14: 1 = a word on Q0-Q3
    input  logic so    // Pin 15: falling edge = drop the head
                       // Pin 16: VCC
);

    logic [3:0] word [0:15];

    // Write and read counters with one extra bit: equal when the queue is
    // empty, 16 apart when it is full

    logic [4:0] wr, rd;

    always_ff @ (posedge si or posedge mr)
        if (mr)
            wr <= '0;
        else if (dir)
            wr <= wr + 5'd1;

    always_ff @ (posedge si)
        if (dir & ~ mr)
            word [wr [3:0]] <= { d3, d2, d1, d0 };

    always_ff @ (negedge so or posedge mr)
        if (mr)
            rd <= '0;
        else if (dor)
            rd <= rd + 5'd1;

    assign dor = wr != rd;
    assign dir = wr != { ~ rd [4], rd [3:0] };

    assign { q3, q2, q1, q0 } = oe ? 4'bz : word [rd [3:0]];

endmodule
