SetBits constructor

SetBits(
  1. Logic inp,
  2. Logic count, {
  3. bool lsbs = true,
  4. bool fill = false,
  5. String name = 'set_bits',
  6. bool reserveName = false,
  7. bool reserveDefinitionName = false,
  8. String? definitionName,
})

Creates set-to-fill hardware over inp and count.

Implementation

SetBits(
  Logic inp,
  Logic count, {
  bool lsbs = true,
  bool fill = false,
  super.name = 'set_bits',
  super.reserveName,
  super.reserveDefinitionName,
  String? definitionName,
}) : super(
          definitionName: definitionName ??
              'SetBits_${lsbs ? 'Lsbs' : 'Msbs'}_'
                  'F${fill ? 1 : 0}_W${inp.width}') {
  inp = addInput('inp', inp, width: inp.width);
  count = addInput('count', count, width: count.width);
  final result = addOutput('result', width: inp.width);

  // Bit `i` is selected when its distance from the chosen end is below
  // `count`. Comparing per bit, rather than shifting, saturates correctly
  // for counts at or above the width.
  final comparisonWidth = max(count.width, (inp.width - 1).bitLength);
  final extendedCount = count.zeroExtend(comparisonWidth);
  final selectBits = [
    for (var i = inp.width - 1; i >= 0; i--)
      Const(lsbs ? i : inp.width - 1 - i, width: comparisonWidth)
          .lt(extendedCount)
  ];
  final selected = selectBits.concat();
  result <= (fill ? inp | selected : inp & ~selected);
}