+ // 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
+ */
+ public 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);
+ }