Integrated new types, tests still work, not used yet
[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.components.BasicComponent;
6 import era.mi.logic.types.Bit;
7 import era.mi.logic.wires.Wire.WireEnd;
8
9 public abstract class MultiInputGate extends BasicComponent
10 {
11         protected WireEnd[] in;
12         protected WireEnd out;
13         protected final int length;
14         protected Operation op;
15
16         protected MultiInputGate(int processTime, Operation op, WireEnd out, WireEnd... in)
17         {
18                 super(processTime);
19                 this.op = op;
20                 length = out.length();
21                 this.in = in.clone();
22                 if (in.length < 1)
23                         throw new IllegalArgumentException(String.format("Cannot create gate with %d wires.", in.length));
24                 for (WireEnd w : in)
25                 {
26                         if (w.length() != length)
27                                 throw new IllegalArgumentException("All wires connected to the gate must be of uniform length.");
28                         w.addObserver(this);
29                 }
30                 this.out = out;
31         }
32
33         @Override
34         public List<WireEnd> getAllInputs()
35         {
36                 return List.of(in);
37         }
38
39         @Override
40         public List<WireEnd> getAllOutputs()
41         {
42                 return List.of(out);
43         }
44
45         @Override
46         protected void compute()
47         {
48                 Bit[] result = in[0].getValues();
49                 for (int i = 1; i < in.length; i++)
50                         result = op.execute(result, in[i].getValues());
51                 out.feedSignals(result);
52         }
53
54         protected interface Operation
55         {
56                 public Bit[] execute(Bit[] a, Bit[] b);
57         }
58 }