Slight improvements of Wire#fuse(...)
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / wires / Wire.java
index b26111f..4063d78 100644 (file)
@@ -4,6 +4,7 @@ import static net.mograsim.logic.core.types.Bit.U;
 import static net.mograsim.logic.core.types.Bit.Z;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 
 import net.mograsim.logic.core.LogicObservable;
@@ -21,81 +22,120 @@ import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
  */
 public class Wire
 {
-       private BitVector values;
+       public final String name;
+       private BitVector cachedValues;
        public final int travelTime;
        private List<ReadEnd> attached = new ArrayList<>();
-       public final int length;
+       public final int width;
        List<ReadWriteEnd> inputs = new ArrayList<>();
        Timeline timeline;
+       private Bit[] bitsWithoutFusions;
+       FusedBit[] fusedBits;
 
-       public Wire(Timeline timeline, int length, int travelTime)
+       public Wire(Timeline timeline, int width, int travelTime)
        {
-               if (length < 1)
+               this(timeline, width, travelTime, null);
+       }
+
+       public Wire(Timeline timeline, int width, int travelTime, String name)
+       {
+               if (width < 1)
                        throw new IllegalArgumentException(
-                                       String.format("Tried to create an array of wires with length %d, but a length of less than 1 makes no sense.", length));
+                                       String.format("Tried to create an array of wires with width %d, but a width of less than 1 makes no sense.", width));
+               this.name = name;
                this.timeline = timeline;
-               this.length = length;
+               this.width = width;
                this.travelTime = travelTime;
                initValues();
        }
 
        private void initValues()
        {
-               values = U.toVector(length);
+               cachedValues = U.toVector(width);
+               bitsWithoutFusions = cachedValues.getBits();
        }
 
-       private void recalculateSingleInput()
+       private void setNewValues(BitVector newValues)
        {
-               setNewValues(inputs.get(0).getInputValues());
+               cachedValues = newValues;
+               notifyObservers();
        }
 
-       private void recalculateMultipleInputs()
+       private void invalidateCachedValuesForAllFusedWires()
        {
-               BitVectorMutator mutator = BitVectorMutator.empty();
-               for (ReadWriteEnd wireArrayEnd : inputs)
-                       mutator.join(wireArrayEnd.getInputValues());
-               setNewValues(mutator.get());
+               invalidateCachedValues();
+               if (fusedBits != null)
+                       for (FusedBit fusion : fusedBits)
+                               if (fusion != null)
+                                       fusion.invalidateCachedValuesForAllParticipatingWires();
        }
 
-       private void setNewValues(BitVector newValues)
+       private void invalidateCachedValues()
        {
-               if (values.equals(newValues))
-                       return;
-//             BitVector oldValues = values;
-               values = newValues;
+               cachedValues = null;
                notifyObservers();
        }
 
-       void recalculate()
+       void recalculateValuesWithoutFusions()
        {
-               switch (inputs.size())
+               Bit[] bits = new Bit[width];
+               if (inputs.isEmpty())
+                       Arrays.fill(bits, U);
+               else
+               {
+                       System.arraycopy(inputs.get(0).getInputValues().getBits(), 0, bits, 0, width);
+                       for (int i = 1; i < inputs.size(); i++)
+                               Bit.join(bits, inputs.get(i).getInputValues().getBits());
+               }
+               bitsWithoutFusions = bits;
+               if (fusedBits == null)
+                       setNewValues(BitVector.of(bits));
+               else
+                       invalidateCachedValuesForAllFusedWires();
+       }
+
+       private void recalculatedCachedValues()
+       {
+               Bit[] bits;
+               if (fusedBits == null)
+                       bits = bitsWithoutFusions;
+               else
                {
-               case 0:
-                       return;
-               case 1:
-                       recalculateSingleInput();
-                       break;
-               default:
-                       recalculateMultipleInputs();
+                       bits = new Bit[width];
+                       for (int i = 0; i < width; i++)
+                       {
+                               FusedBit fusion = fusedBits[i];
+                               if (fusion == null)
+                                       bits[i] = bitsWithoutFusions[i];
+                               else
+                                       bits[i] = fusion.getValue();
+                       }
                }
+               cachedValues = BitVector.of(bits);
+       }
+
+       /**
+        * Forces a Wire to take on specific values. If the new values differ from the old ones, the observers of the Wire will be notified.
+        * WARNING! Use this with care! The preferred way of writing the values is ReadWriteEnd.feedSignals(BitVector)
+        * 
+        * @param values The values the <code>Wire</code> will have immediately after this method is called
+        */
+       public void forceValues(BitVector values)
+       {
+               setNewValues(values);
        }
 
        /**
         * The {@link Wire} is interpreted as an unsigned integer with n bits.
         * 
         * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the same
-        *         value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
+        *         value), not <code>Bit.U</code>, <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
         * 
         * @author Fabian Stemmler
         */
        public boolean hasNumericValue()
        {
-               for (Bit b : values)
-               {
-                       if (b != Bit.ZERO && b != Bit.ONE)
-                               return false;
-               }
-               return true;
+               return getValues().isBinary();
        }
 
        /**
@@ -109,7 +149,7 @@ public class Wire
        {
                long val = 0;
                long mask = 1;
-               for (Bit bit : values)
+               for (Bit bit : getValues())
                {
                        switch (bit)
                        {
@@ -137,33 +177,41 @@ public class Wire
        public long getSignedValue()
        {
                long val = getUnsignedValue();
-               long mask = 1 << (length - 1);
+               long mask = 1 << (width - 1);
                if ((mask & val) != 0)
                {
-                       int shifts = 64 - length;
+                       int shifts = 64 - width;
                        return (val << shifts) >> shifts;
                }
                return val;
        }
 
+       /**
+        * Returns the least significant bit (LSB)
+        */
        public Bit getValue()
        {
                return getValue(0);
        }
 
+       /**
+        * Returns the least significant bit (LSB) of the given index
+        */
        public Bit getValue(int index)
        {
-               return values.getBit(index);
+               return getValues().getLSBit(index);
        }
 
        public BitVector getValues(int start, int end)
        {
-               return values.subVector(start, end);
+               return getValues().subVector(start, end);
        }
 
        public BitVector getValues()
        {
-               return values;
+               if (cachedValues == null)
+                       recalculatedCachedValues();
+               return cachedValues;
        }
 
        /**
@@ -174,9 +222,9 @@ public class Wire
         * 
         * @author Fabian Stemmler
         */
-       void attachEnd(ReadEnd end)
+       boolean attachEnd(ReadEnd end)
        {
-               attached.add(end);
+               return attached.add(end);
        }
 
        void detachEnd(ReadEnd end)
@@ -186,7 +234,7 @@ public class Wire
 
        private void notifyObservers()
        {
-               attached.forEach(r -> r.update());
+               attached.forEach(ReadEnd::update);
        }
 
        /**
@@ -208,6 +256,7 @@ public class Wire
        void registerInput(ReadWriteEnd toRegister)
        {
                inputs.add(toRegister);
+               recalculateValuesWithoutFusions();
        }
 
        /**
@@ -233,7 +282,7 @@ public class Wire
                }
 
                /**
-                * Included for convenient use on {@link Wire}s of length 1.
+                * Included for convenient use on {@link Wire}s of width 1.
                 * 
                 * @return The value of bit 0.
                 * 
@@ -255,12 +304,6 @@ public class Wire
                        return Wire.this.getValue(index);
                }
 
-               /**
-                * @param index Index of the requested bit.
-                * @return The value of the indexed bit.
-                * 
-                * @author Fabian Stemmler
-                */
                public BitVector getValues()
                {
                        return Wire.this.getValues();
@@ -325,12 +368,12 @@ public class Wire
                {
                        inputs.remove(this);
                        detachEnd(this);
-                       recalculate();
+                       recalculateValuesWithoutFusions();
                }
 
-               public int length()
+               public int width()
                {
-                       return length;
+                       return width;
                }
 
                public Wire getWire()
@@ -350,6 +393,16 @@ public class Wire
                        observers.remove(ob);
                }
 
+//             void registerCloseObserver(LogicObserver ob)
+//             {
+//                     closeObserver.add(ob);
+//             }
+//             
+//             void deregisterCloseObserver(LogicObserver ob)
+//             {
+//                     closeObserver.remove(ob);
+//             }
+
                @Override
                public void notifyObservers()
                {
@@ -360,19 +413,21 @@ public class Wire
        public class ReadWriteEnd extends ReadEnd
        {
                private boolean open;
+               private boolean isWriting;
                private BitVector inputValues;
 
                ReadWriteEnd()
                {
                        super();
                        open = true;
+                       isWriting = true;
                        initValues();
                        registerInput(this);
                }
 
                private void initValues()
                {
-                       inputValues = U.toVector(length);
+                       inputValues = U.toVector(width);
                }
 
                /**
@@ -389,11 +444,11 @@ public class Wire
 
                public void feedSignals(BitVector newValues)
                {
-                       if (newValues.length() != length)
+                       if (newValues.length() != width)
                                throw new IllegalArgumentException(
-                                               String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), length));
+                                               String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), width));
                        if (!open)
-                               throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
+                               throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
                        timeline.addEvent(e -> setValues(newValues), travelTime);
                }
 
@@ -408,11 +463,15 @@ public class Wire
                public void feedSignals(int startingBit, BitVector bitVector)
                {
                        if (!open)
-                               throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
+                               throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
                        timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
                }
 
-               private void setValues(int startingBit, BitVector newValues)
+               /**
+                * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
+                * feedValues(...) with a delay.
+                */
+               void setValues(int startingBit, BitVector newValues)
                {
                        // index check covered in equals
                        if (!inputValues.equalsWithOffset(newValues, startingBit))
@@ -420,20 +479,25 @@ public class Wire
                                Bit[] vals = inputValues.getBits();
                                System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
                                inputValues = BitVector.of(vals);
-                               Wire.this.recalculate();
+                               Wire.this.recalculateValuesWithoutFusions();
                        }
                }
 
-               private void setValues(BitVector newValues)
+               /**
+                * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
+                * feedValues(...) with a delay.
+                */
+               void setValues(BitVector newValues)
                {
                        if (inputValues.equals(newValues))
                                return;
                        inputValues = newValues;
-                       Wire.this.recalculate();
+                       Wire.this.recalculateValuesWithoutFusions();
                }
 
                /**
-                * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
+                * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.Returns the least
+                *         significant bit (LSB)
                 */
                public Bit getInputValue()
                {
@@ -442,10 +506,12 @@ public class Wire
 
                /**
                 * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
+                *         Returns the least significant bit (LSB)
+                * 
                 */
                public Bit getInputValue(int index)
                {
-                       return inputValues.getBit(index);
+                       return inputValues.getLSBit(index);
                }
 
                /**
@@ -453,7 +519,7 @@ public class Wire
                 */
                public BitVector getInputValues()
                {
-                       return getInputValues(0, length);
+                       return inputValues;
                }
 
                public BitVector getInputValues(int start, int end)
@@ -466,19 +532,23 @@ public class Wire
                 */
                public void clearSignals()
                {
-                       feedSignals(Z.toVector(length));
+                       feedSignals(Z.toVector(width));
                }
 
                public BitVector wireValuesExcludingMe()
                {
                        BitVectorMutator mutator = BitVectorMutator.empty();
+                       boolean modified = false;
                        for (ReadWriteEnd wireEnd : inputs)
                        {
                                if (wireEnd == this)
                                        continue;
+                               modified = true;
                                mutator.join(wireEnd.inputValues);
                        }
-                       return mutator.get();
+                       if (!modified)
+                               mutator.join(BitVector.of(Bit.Z, width));
+                       return mutator.toBitVector();
                }
 
                @Override
@@ -486,12 +556,38 @@ public class Wire
                {
                        return inputValues.toString();
                }
+
+               @Override
+               public void close()
+               {
+                       super.close();
+                       open = false;
+               }
+
+               void setWriting(boolean isWriting)
+               {
+                       if (this.isWriting != isWriting)
+                       {
+                               this.isWriting = isWriting;
+                               if (isWriting)
+                                       inputs.add(this);
+                               else
+                                       inputs.remove(this);
+                               Wire.this.recalculateValuesWithoutFusions();
+                       }
+               }
+
+               boolean isWriting()
+               {
+                       return isWriting;
+               }
        }
 
        @Override
        public String toString()
        {
-               return String.format("wire 0x%08x value: %s inputs: %s", hashCode(), values, inputs);
+               String name = this.name == null ? String.format("0x%08x", hashCode()) : this.name;
+               return String.format("wire %s value: %s inputs: %s", name, getValues(), inputs);
        }
 
        public static ReadEnd[] extractEnds(Wire[] w)
@@ -501,4 +597,127 @@ public class Wire
                        inputs[i] = w[i].createReadWriteEnd();
                return inputs;
        }
+
+       /**
+        * 
+        * Fuses two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning: The bits are
+        * permanently fused together.
+        * 
+        * @param a The {@link Wire} to be fused with b
+        * @param b The {@link Wire} to be fused with a
+        */
+       public static void fuse(Wire a, Wire b)
+       {
+               fuse(a, b, 0, 0, a.width);
+       }
+
+       /**
+        * Fuses the selected bits of two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning:
+        * The bits are permanently fused together.
+        * 
+        * @param a     The {@link Wire} to be (partially) fused with b
+        * @param b     The {@link Wire} to be (partially) fused with a
+        * @param fromA The first bit of {@link Wire} a to be fused
+        * @param fromB The first bit of {@link Wire} b to be fused
+        * @param width The amount of bits to fuse
+        */
+       public static void fuse(Wire a, Wire b, int fromA, int fromB, int width)
+       {
+               // iterate in this direction to be fail-fast (rely on the checks in fuse(Wire, Wire, int, int)
+               for (int i = width - 1; i >= 0; i--)
+                       fuse(a, b, fromA + i, fromB + i);
+       }
+
+       /**
+        * Fuses one bit of two wires together. If this bit changes in one Wire, the other is changed accordingly immediately. Warning: The bits
+        * are permanently fused together.
+        * 
+        * @param a    The {@link Wire} to be (partially) fused with b
+        * @param b    The {@link Wire} to be (partially) fused with a
+        * @param bitA The bit of {@link Wire} a to be fused
+        * @param bitB The bit of {@link Wire} b to be fused
+        */
+       private static void fuse(Wire a, Wire b, int bitA, int bitB)
+       {
+               if (bitA >= a.width)
+                       throw new IllegalArgumentException("No bit " + bitA + " in " + a + " (width " + a.width + ")");
+               if (bitB >= b.width)
+                       throw new IllegalArgumentException("No bit " + bitB + " in " + b + " (width " + b.width + ")");
+               if (a.fusedBits == null)
+                       a.fusedBits = new FusedBit[a.width];
+               if (b.fusedBits == null)
+                       b.fusedBits = new FusedBit[b.width];
+               FusedBit oldFusionA = a.fusedBits[bitA];
+               FusedBit oldFusionB = b.fusedBits[bitB];
+               if (oldFusionA == null)
+                       if (oldFusionB == null)
+                       {
+                               FusedBit fusion = new FusedBit();
+                               fusion.addParticipatingWireBit(a, bitA);
+                               fusion.addParticipatingWireBit(b, bitB);
+                       } else
+                               oldFusionB.addParticipatingWireBit(a, bitA);
+               else if (oldFusionB == null)
+                       oldFusionA.addParticipatingWireBit(b, bitB);
+               else
+                       oldFusionA.mergeOtherIntoThis(oldFusionB);
+       }
+
+       private static class FusedBit
+       {
+               private final List<WireBit> participatingWireBits;
+
+               public FusedBit()
+               {
+                       this.participatingWireBits = new ArrayList<>();
+               }
+
+               public void addParticipatingWireBit(Wire w, int bit)
+               {
+                       addParticipatingWireBit(new WireBit(w, bit));
+               }
+
+               private void addParticipatingWireBit(WireBit wb)
+               {
+                       wb.wire.fusedBits[wb.bit] = this;
+                       participatingWireBits.add(wb);
+                       wb.wire.invalidateCachedValuesForAllFusedWires();
+               }
+
+               public void mergeOtherIntoThis(FusedBit other)
+               {
+                       for (WireBit wb : other.participatingWireBits)
+                               addParticipatingWireBit(wb);
+               }
+
+               public void invalidateCachedValuesForAllParticipatingWires()
+               {
+                       for (WireBit wb : participatingWireBits)
+                               wb.wire.invalidateCachedValues();
+               }
+
+               public Bit getValue()
+               {
+                       Bit result = null;
+                       for (WireBit wb : participatingWireBits)
+                               if (!wb.wire.inputs.isEmpty())
+                               {
+                                       Bit bit = wb.wire.bitsWithoutFusions[wb.bit];
+                                       result = result == null ? bit : result.join(bit);
+                               }
+                       return result == null ? U : result;
+               }
+       }
+
+       private static class WireBit
+       {
+               public final Wire wire;
+               public final int bit;
+
+               public WireBit(Wire wire, int bit)
+               {
+                       this.wire = wire;
+                       this.bit = bit;
+               }
+       }
 }
\ No newline at end of file