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