Skip to content

Commit

Permalink
feat(spi): Added highlight function to hex to highlight byte positions
Browse files Browse the repository at this point in the history
  • Loading branch information
sruehl committed Jan 14, 2022
1 parent 576d7ae commit 9450441
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

import com.github.jinahya.bit.io.ArrayByteInput;
import com.github.jinahya.bit.io.DefaultBitInput;
import org.apache.plc4x.java.spi.utils.hex.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

Expand All @@ -28,6 +31,8 @@
*/
public class MyDefaultBitInput extends DefaultBitInput<ArrayByteInput> {

private static final Logger LOGGER = LoggerFactory.getLogger(MyDefaultBitInput.class);

public MyDefaultBitInput(ArrayByteInput delegate) {
super(delegate);
}
Expand All @@ -38,11 +43,19 @@ public long getPos() {
}

public void reset(int pos) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Before\n{}", Hex.dump(delegate.getSource(), Hex.DefaultWidth, delegate.getIndex()));
}
try {
align(1);
long align = align(1);
LOGGER.debug("aligned {}", align);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
delegate.setIndex(pos);
LOGGER.debug("set to index {}", pos);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("After\n{}", Hex.dump(delegate.getSource(), Hex.DefaultWidth, pos));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Hex {

Expand Down Expand Up @@ -75,10 +77,11 @@ public static String dump(byte[] data) {
}

// DumpFixedWidth dumps hex as hex string. Min width of string returned is 18 up to supplied charWidth
public static String dump(byte[] data, int desiredCharWidth) {
public static String dump(byte[] data, int desiredCharWidth, int... highlights) {
if (data == null || data.length < 1) {
return "";
}
Set<Integer> highlightsSet = Arrays.stream(highlights).boxed().collect(Collectors.toSet());
// We copy the array to avoid mutations
data = Arrays.copyOf(data, data.length);
StringBuilder hexString = new StringBuilder();
Expand All @@ -91,7 +94,13 @@ public static String dump(byte[] data, int desiredCharWidth) {
for (int columnIndex = 0; columnIndex < maxBytesPerRow; columnIndex++) {
int absoluteIndex = byteIndex + columnIndex;
if (absoluteIndex < data.length) {
if(highlightsSet.contains(absoluteIndex)) {
hexString.append("\033[0;31m");
}
hexString.append(String.format("%02x ", data[absoluteIndex]));
if(highlightsSet.contains(absoluteIndex)) {
hexString.append("\033[0m");
}
} else {
// align with empty byte representation
hexString.append(StringUtils.repeat(" ", byteWidth));
Expand Down

0 comments on commit 9450441

Please sign in to comment.