6b183e37651dd2cdc79dfa59b93d7894816db73d
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / components / gates / MultiInputGate.java
1 package net.mograsim.logic.core.components.gates;
2
3 import java.util.List;
4
5 import net.mograsim.logic.core.components.BasicComponent;
6 import net.mograsim.logic.core.timeline.Timeline;
7 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
8 import net.mograsim.logic.core.types.MutationOperation;
9 import net.mograsim.logic.core.wires.Wire.ReadEnd;
10 import net.mograsim.logic.core.wires.Wire.ReadWriteEnd;
11
12 public abstract class MultiInputGate extends BasicComponent
13 {
14         protected ReadEnd[] in;
15         protected ReadWriteEnd out;
16         protected final int length;
17         protected MutationOperation op;
18
19         protected MultiInputGate(Timeline timeline, int processTime, MutationOperation op, ReadWriteEnd out, ReadEnd... in)
20         {
21                 super(timeline, processTime);
22                 this.op = op;
23                 length = out.length();
24                 this.in = in.clone();
25                 if (in.length < 1)
26                         throw new IllegalArgumentException(String.format("Cannot create gate with %d wires.", in.length));
27                 for (ReadEnd w : in)
28                 {
29                         if (w.length() != length)
30                                 throw new IllegalArgumentException("All wires connected to the gate must be of uniform length.");
31                         w.registerObserver(this);
32                 }
33                 this.out = out;
34         }
35
36         @Override
37         public List<ReadEnd> getAllInputs()
38         {
39                 return List.of(in);
40         }
41
42         @Override
43         public List<ReadWriteEnd> getAllOutputs()
44         {
45                 return List.of(out);
46         }
47
48         @Override
49         protected void compute()
50         {
51                 BitVectorMutator mutator = BitVectorMutator.empty();
52                 for (ReadEnd w : in)
53                         op.apply(mutator, w.getValues());
54                 out.feedSignals(mutator.get());
55         }
56 }