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