Reformatted everything. Eclipse built-in Linewrapping/Comments 140 chars
[Mograsim.git] / era.mi / src / era / mi / logic / components / gates / MultiInputGate.java
1 package era.mi.logic.components.gates;
2
3 import java.util.Arrays;
4 import java.util.Collections;
5 import java.util.List;
6
7 import era.mi.logic.Bit;
8 import era.mi.logic.components.BasicComponent;
9 import era.mi.logic.wires.WireArray;
10 import era.mi.logic.wires.WireArray.WireArrayInput;
11
12 public abstract class MultiInputGate extends BasicComponent {
13         protected WireArray[] in;
14         protected WireArray out;
15         protected WireArrayInput outI;
16         protected final int length;
17         protected Operation op;
18
19         protected MultiInputGate(int processTime, Operation op, WireArray out, WireArray... in) {
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                         if (w.length != length)
28                                 throw new IllegalArgumentException("All wires connected to the gate must be of uniform length.");
29                         w.addObserver(this);
30                 }
31                 this.out = out;
32                 outI = out.createInput();
33         }
34
35         @Override
36         public List<WireArray> getAllInputs() {
37                 return Collections.unmodifiableList(Arrays.asList(in));
38         }
39
40         @Override
41         public List<WireArray> getAllOutputs() {
42                 return Collections.unmodifiableList(Arrays.asList(out));
43         }
44
45         protected void compute() {
46                 Bit[] result = in[0].getValues();
47                 for (int i = 1; i < in.length; i++)
48                         result = op.execute(result, in[i].getValues());
49                 outI.feedSignals(result);
50         }
51
52         protected interface Operation {
53                 public Bit[] execute(Bit[] a, Bit[] b);
54         }
55 }