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