printHistogram function Null safety

void printHistogram(
  1. ProgramInfo info,
  2. Histogram histogram,
  3. {Iterable<String> prefix = const [],
  4. Iterable<String> suffix = const [],
  5. String sizeHeader = 'Size (Bytes)',
  6. int maxWidth = 0}
)

Implementation

void printHistogram(ProgramInfo info, Histogram histogram,
    {Iterable<String> prefix = const [],
    Iterable<String> suffix = const [],
    String sizeHeader = 'Size (Bytes)',
    int maxWidth = 0}) {
  final totalSize = info.totalSize;
  final wasFiltered = totalSize != histogram.totalSize;
  final table = AsciiTable(header: [
    for (var col in histogram.bucketInfo.nameComponents) Text.left(col),
    Text.right(sizeHeader),
    Text.right('Percent'),
    if (wasFiltered) Text.right('Of total'),
  ], maxWidth: maxWidth);

  final visibleRows = [prefix, suffix].expand((l) => l).toList();
  final visibleSize =
      visibleRows.fold<int>(0, (sum, key) => sum + histogram.buckets[key]!);
  final numRestRows = histogram.length - (suffix.length + prefix.length);
  final hiddenRows = Set<String>.from(histogram.bySize)
      .difference(Set<String>.from(visibleRows));
  final interestingHiddenRows =
      hiddenRows.any((k) => histogram.buckets[k] != 0);

  if (prefix.isNotEmpty) {
    for (var key in prefix) {
      final size = histogram.buckets[key]!;
      table.addRow([
        ...histogram.bucketInfo.namesFromBucket(key),
        size.toString(),
        formatPercent(size, histogram.totalSize),
        if (wasFiltered) formatPercent(size, totalSize),
      ]);
    }
    table.addSeparator(interestingHiddenRows ? Separator.Wave : Separator.Line);
  }

  if (interestingHiddenRows) {
    final totalRestBytes = histogram.totalSize - visibleSize;
    table.addTextSeparator(
        '$numRestRows more rows accounting for ${totalRestBytes}'
        ' (${formatPercent(totalRestBytes, totalSize)} of total) bytes');
    final avg = (totalRestBytes / numRestRows).round();
    table.addTextSeparator(
        'on average that is ${avg} (${formatPercent(avg, histogram.totalSize)})'
        ' bytes per row');
    table.addSeparator(suffix.isNotEmpty ? Separator.Wave : Separator.Line);
  }

  if (suffix.isNotEmpty) {
    for (var key in suffix) {
      table.addRow([
        ...histogram.bucketInfo.namesFromBucket(key),
        histogram.buckets[key].toString(),
        formatPercent(histogram.buckets[key]!, histogram.totalSize),
      ]);
    }
    table.addSeparator(Separator.Line);
  }

  table.render();

  if (wasFiltered || visibleSize != histogram.totalSize) {
    print('In visible rows: ${visibleSize}'
        ' (${formatPercent(visibleSize, totalSize)} of total)');
  }
  print('Total: ${totalSize} bytes');
}