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