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