Renamed mograsim to net.mograsim
[Mograsim.git] / era.mi / src / net / mograsim / logic / core / components / Merger.java
1 package net.mograsim.logic.core.components;
2
3 import java.util.List;
4
5 import net.mograsim.logic.core.timeline.Timeline;
6 import net.mograsim.logic.core.types.BitVector;
7 import net.mograsim.logic.core.wires.Wire;
8 import net.mograsim.logic.core.wires.WireObserver;
9 import net.mograsim.logic.core.wires.Wire.ReadEnd;
10 import net.mograsim.logic.core.wires.Wire.ReadWriteEnd;
11
12 public class Merger extends Component implements WireObserver
13 {
14         private ReadWriteEnd out;
15         private ReadEnd[] inputs;
16         private int[] beginningIndex;
17
18         /**
19          * 
20          * @param union  The output of merging n {@link Wire}s into one. Must have length = a1.length() + a2.length() + ... + an.length().
21          * @param inputs The inputs to be merged into the union
22          */
23         public Merger(Timeline timeline, ReadWriteEnd union, ReadEnd... inputs)
24         {
25                 super(timeline);
26                 this.inputs = inputs;
27                 this.out = union;
28                 this.beginningIndex = new int[inputs.length];
29
30                 int length = 0;
31                 for (int i = 0; i < inputs.length; i++)
32                 {
33                         beginningIndex[i] = length;
34                         length += inputs[i].length();
35                         inputs[i].addObserver(this);
36                 }
37
38                 if (length != union.length())
39                         throw new IllegalArgumentException(
40                                         "The output of merging n WireArrays into one must have length = a1.length() + a2.length() + ... + an.length().");
41         }
42
43         public ReadEnd getInput(int index)
44         {
45                 return inputs[index];
46         }
47
48         public ReadEnd getUnion()
49         {
50                 return out;
51         }
52
53         @Override
54         public void update(ReadEnd initiator, BitVector oldValues)
55         {
56                 int index = find(initiator);
57                 int beginning = beginningIndex[index];
58                 out.feedSignals(beginning, inputs[index].getValues());
59         }
60
61         private int find(ReadEnd r)
62         {
63                 for (int i = 0; i < inputs.length; i++)
64                         if (inputs[i] == r)
65                                 return i;
66                 return -1;
67         }
68
69         public ReadEnd[] getInputs()
70         {
71                 return inputs.clone();
72         }
73
74         @Override
75         public List<ReadEnd> getAllInputs()
76         {
77                 return List.of(inputs);
78         }
79
80         @Override
81         public List<ReadWriteEnd> getAllOutputs()
82         {
83                 return List.of(out);
84         }
85 }