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
use rust_hdl_core::prelude::*;

use crate::dff::DFF;

#[derive(Clone, Debug, LogicBlock)]
pub struct Accum<const N: usize, const M: usize, const P: usize> {
    pub clock: Signal<In, Clock>,
    pub strobe_in: Signal<In, Bit>,
    pub data_in: Signal<In, Bits<N>>,
    pub strobe_out: Signal<Out, Bit>,
    pub data_out: Signal<Out, Bits<M>>,
    accum: DFF<Bits<M>>,
    counter: DFF<Bits<P>>,
    max_count: Constant<Bits<P>>,
}

impl<const N: usize, const M: usize, const P: usize> Logic for Accum<N, M, P> {
    fn update(&mut self) {
        self.accum.clock.next = self.clock.val();
        self.counter.clock.next = self.clock.val();
        self.strobe_out.next = false;
        self.data_out.next = self.accum.q.val();
        self.accum.d.next = self.accum.q.val();
        if self.strobe_in.val() {
            self.accum.d.next = self.accum.q.val() + bit_cast::<M, N>(self.data_in.val());
            self.counter.d.next = self.counter.q.val() + 1;
        }
        if self.counter.q.val() == self.max_count.val() {
            self.strobe_out.next = true;
            self.counter.d.next = 0.into();
            self.accum.d.next = 0.into();
        }
    }
}

impl<const N: usize, const M: usize, const P: usize> Accum<N, M, P> {
    pub fn new(count: usize) -> Self {
        assert!(P >= clog2(count));
        assert!(M >= N + P);
        Self {
            clock: Default::default(),
            strobe_in: Default::default(),
            data_in: Default::default(),
            strobe_out: Default::default(),
            accum: DFF::default(),
            counter: DFF::default(),
            max_count: Constant::new(count.to_bits()),
            data_out: Default::default(),
        }
    }
}

#[test]
fn test_accum_synthesizes() {
    let _p = TopWrap::new(Accum::<32, 40, 6>::new(50));
}