1efcf8ad276cf0d6d4922ed92bda4a466af458fc
[Mograsim.git] / era.mi / src / era / mi / logic / components / Merger.java
1 package era.mi.logic.components;
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.wires.WireArray;
9 import era.mi.logic.wires.WireArray.WireArrayInput;
10 import era.mi.logic.wires.WireArrayObserver;
11
12 public class Merger implements WireArrayObserver, Component {
13         private WireArrayInput outI;
14         private WireArray[] inputs;
15         private int[] beginningIndex;
16
17         /**
18          * 
19          * @param union  The output of merging n {@link WireArray}s into one. Must have length = a1.length() + a2.length() + ... + an.length().
20          * @param inputs The inputs to be merged into the union
21          */
22         public Merger(WireArray union, WireArray... inputs) {
23                 this.inputs = inputs;
24                 this.outI = union.createInput();
25                 this.beginningIndex = new int[inputs.length];
26
27                 int length = 0;
28                 for (int i = 0; i < inputs.length; i++) {
29                         beginningIndex[i] = length;
30                         length += inputs[i].length;
31                         inputs[i].addObserver(this);
32                 }
33
34                 if (length != union.length)
35                         throw new IllegalArgumentException(
36                                         "The output of merging n WireArrays into one must have length = a1.length() + a2.length() + ... + an.length().");
37         }
38
39         public WireArray getInput(int index) {
40                 return inputs[index];
41         }
42
43         public WireArray getUnion() {
44                 return outI.owner;
45         }
46
47         @Override
48         public void update(WireArray initiator, Bit[] oldValues) {
49                 int index = find(initiator);
50                 int beginning = beginningIndex[index];
51                 outI.feedSignals(beginning, initiator.getValues());
52         }
53
54         private int find(WireArray w) {
55                 for (int i = 0; i < inputs.length; i++)
56                         if (inputs[i] == w)
57                                 return i;
58                 return -1;
59         }
60
61         public WireArray[] getInputs() {
62                 return inputs.clone();
63         }
64
65         @Override
66         public List<WireArray> getAllInputs() {
67                 return Collections.unmodifiableList(Arrays.asList(inputs));
68         }
69
70         @Override
71         public List<WireArray> getAllOutputs() {
72                 return Collections.unmodifiableList(Arrays.asList(outI.owner));
73         }
74 }