package org.graalvm.compiler.debug.internal;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import org.graalvm.compiler.debug.DebugHistogram;
import org.graalvm.compiler.debug.DebugHistogram.CountedValue;
import org.graalvm.compiler.debug.DebugHistogram.Printer;
public class DebugHistogramAsciiPrinter implements Printer {
public static final int NumberSize = 10;
public static final int DefaultNameSize = 50;
public static final int DefaultBarSize = 100;
public static final int DefaultScale = 1;
private final PrintStream os;
private final int limit;
private final int nameSize;
private final int barSize;
private final int scale;
public DebugHistogramAsciiPrinter(PrintStream os) {
this(os, Integer.MAX_VALUE, DefaultNameSize, DefaultBarSize, DefaultScale);
}
public DebugHistogramAsciiPrinter(PrintStream os, int limit, int nameSize, int barSize, int scale) {
this.os = os;
this.limit = limit;
this.nameSize = nameSize;
this.barSize = barSize;
this.scale = scale;
}
@Override
public void print(DebugHistogram histogram) {
List<CountedValue> list = histogram.getValues();
if (list.isEmpty()) {
os.printf("%s is empty.%n", histogram.getName());
return;
}
long total = list.stream().mapToLong(CountedValue::getCount).sum();
os.printf("%s has %d unique elements and %d total elements:%n", histogram.getName(), list.size(), total / scale);
long max = list.get(0).getCount() / scale;
final int lineSize = nameSize + NumberSize + barSize + 10;
printLine(os, '-', lineSize);
String formatString = "| %-" + nameSize + "s | %-" + NumberSize + "d | %-" + barSize + "s |\n";
for (int i = 0; i < list.size() && i < limit; ++i) {
CountedValue cv = list.get(i);
long value = cv.getCount() / scale;
char[] bar = new char[(int) (((double) value / (double) max) * barSize)];
Arrays.fill(bar, '=');
String objectString = String.valueOf(cv.getValue());
if (objectString.length() > nameSize) {
objectString = objectString.substring(0, nameSize - 3) + "...";
}
os.printf(formatString, objectString, value, new String(bar));
}
printLine(os, '-', lineSize);
}
private static void printLine(PrintStream printStream, char c, int lineSize) {
char[] charArr = new char[lineSize];
Arrays.fill(charArr, c);
printStream.printf("%s%n", new String(charArr));
}
}