fac267a27e9df4a940d85fd0c20124e5b0d53395
[Mograsim.git] / era.mi / src / era / mi / logic / components / gates / MultiInputGate.java
1 package era.mi.logic.components.gates;
2
3 import java.util.List;
4
5 import era.mi.logic.Bit;
6 import era.mi.logic.components.BasicComponent;
7 import era.mi.logic.wires.WireArray;
8 import era.mi.logic.wires.WireArray.WireArrayEnd;
9
10 public abstract class MultiInputGate extends BasicComponent
11 {
12         protected WireArray[] in;
13         protected WireArray out;
14         protected WireArrayEnd outI;
15         protected final int length;
16         protected Operation op;
17
18         protected MultiInputGate(int processTime, Operation op, WireArray out, WireArray... in)
19         {
20                 super(processTime);
21                 this.op = op;
22                 length = out.length;
23                 this.in = in.clone();
24                 if (in.length < 1)
25                         throw new IllegalArgumentException(String.format("Cannot create gate with %d wires.", in.length));
26                 for (WireArray w : in)
27                 {
28                         if (w.length != length)
29                                 throw new IllegalArgumentException("All wires connected to the gate must be of uniform length.");
30                         w.addObserver(this);
31                 }
32                 this.out = out;
33                 outI = out.createInput();
34         }
35
36         @Override
37         public List<WireArray> getAllInputs()
38         {
39                 return List.of(in);
40         }
41
42         @Override
43         public List<WireArray> getAllOutputs()
44         {
45                 return List.of(out);
46         }
47
48         @Override
49         protected void compute()
50         {
51                 Bit[] result = in[0].getValues();
52                 for (int i = 1; i < in.length; i++)
53                         result = op.execute(result, in[i].getValues());
54                 outI.feedSignals(result);
55         }
56
57         protected interface Operation
58         {
59                 public Bit[] execute(Bit[] a, Bit[] b);
60         }
61 }