1 package net.mograsim.logic.core.types;
3 import java.math.BigInteger;
5 import net.mograsim.logic.core.wires.CoreWire.ReadEnd;
6 import net.mograsim.preferences.ColorDefinition;
7 import net.mograsim.preferences.ColorDefinition.BuiltInColor;
8 import net.mograsim.preferences.Preferences;
10 public class BitVectorFormatter
12 public static String formatValueAsString(ReadEnd end)
14 return formatAsString(end == null ? null : end.getValues());
17 public static String toBitstring(BitVector bitVector)
19 return bitVector.toBitstring();
22 public static String formatAsString(BitVector bitVector)
24 if (bitVector == null)
26 if (bitVector.isBinary())
28 String hexdigits = bitVector.getUnsignedValue().toString(16);
29 StringBuilder sb = new StringBuilder();
31 sb.append("0".repeat((bitVector.length() + 3) / 4 - hexdigits.length()));
35 if (bitVector.isHighImpedance())
37 return bitVector.toBitstring();
40 // TODO this method overlaps in functionality with AsmNumberUtil (in plugin.core)
41 public static BitVector parseUserBitVector(String userInput, int width)
43 BitVector bitvector = null;
44 if (width > 0 && userInput.matches("0x[0-9a-fA-F]+"))
45 // TODO should we check for overflows?
46 bitvector = BitVector.from(new BigInteger(userInput.substring(2), 16), width);
47 else if (width <= 0 || userInput.length() == width)
48 // TODO do this without exceptions
51 bitvector = BitVector.parseBitstring(userInput);
53 catch (@SuppressWarnings("unused") NullPointerException x)
57 if (bitvector == null && width > 0)
60 // TODO should we check for overflows?
61 bitvector = BitVector.from(new BigInteger(userInput), width);
63 catch (@SuppressWarnings("unused") NumberFormatException x)
70 // TODO doesn't this belong to logic.model?
71 public static ColorDefinition formatAsColor(ReadEnd end)
73 return formatAsColor(end == null ? null : end.getValues());
76 public static ColorDefinition formatAsColor(BitVector bitVector)
78 // TODO maybe find a color assignment for multiple-bit bit vectors?
79 if (bitVector == null || bitVector.length() != 1)
80 return new ColorDefinition(BuiltInColor.COLOR_BLACK);
81 switch (bitVector.getLSBit(0))
84 return Preferences.current().getColorDefinition("net.mograsim.logic.model.color.bit.one");
86 return Preferences.current().getColorDefinition("net.mograsim.logic.model.color.bit.u");
88 return Preferences.current().getColorDefinition("net.mograsim.logic.model.color.bit.x");
90 return Preferences.current().getColorDefinition("net.mograsim.logic.model.color.bit.z");
92 return Preferences.current().getColorDefinition("net.mograsim.logic.model.color.bit.zero");
94 throw new IllegalArgumentException("Unknown enum constant: " + bitVector.getLSBit(0));
98 private BitVectorFormatter()
100 throw new UnsupportedOperationException("No BitVectorFormatter instances");