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