Generalized WireObserver to LogicObserver
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / components / Splitter.java
1 package net.mograsim.logic.core.components;\r
2 \r
3 import java.util.List;\r
4 \r
5 import net.mograsim.logic.core.LogicObservable;\r
6 import net.mograsim.logic.core.LogicObserver;\r
7 import net.mograsim.logic.core.timeline.Timeline;\r
8 import net.mograsim.logic.core.types.BitVector;\r
9 import net.mograsim.logic.core.wires.Wire.ReadEnd;\r
10 import net.mograsim.logic.core.wires.Wire.ReadWriteEnd;\r
11 \r
12 public class Splitter extends Component implements LogicObserver\r
13 {\r
14         private ReadEnd input;\r
15         private ReadWriteEnd[] outputs;\r
16 \r
17         public Splitter(Timeline timeline, ReadEnd input, ReadWriteEnd... outputs)\r
18         {\r
19                 super(timeline);\r
20                 this.input = input;\r
21                 this.outputs = outputs;\r
22                 input.registerObserver(this);\r
23                 int length = 0;\r
24                 for (ReadEnd out : outputs)\r
25                         length += out.length();\r
26 \r
27                 if (input.length() != length)\r
28                         throw new IllegalArgumentException(\r
29                                         "The input of splitting one into n WireArrays must have length = a1.length() + a2.length() + ... + an.length().");\r
30         }\r
31 \r
32         protected void compute()\r
33         {\r
34                 BitVector inputBits = input.getValues();\r
35                 int startIndex = 0;\r
36                 for (int i = 0; i < outputs.length; i++)\r
37                 {\r
38                         outputs[i].feedSignals(inputBits.subVector(startIndex, startIndex + outputs[i].length()));\r
39                         startIndex += outputs[i].length();\r
40                 }\r
41         }\r
42 \r
43         @Override\r
44         public void update(LogicObservable initiator)\r
45         {\r
46                 compute();\r
47         }\r
48 \r
49         @Override\r
50         public List<ReadEnd> getAllInputs()\r
51         {\r
52                 return List.of(input);\r
53         }\r
54 \r
55         @Override\r
56         public List<ReadWriteEnd> getAllOutputs()\r
57         {\r
58                 return List.of(outputs);\r
59         }\r
60 }\r