getRange method

LogicValue getRange(
  1. int startIndex,
  2. [int? endIndex]
)

Returns a subset LogicValue. It is inclusive of startIndex, exclusive of endIndex.

startIndex must come before the endIndex on position. If startIndex and endIndex are equal, then a zero-width value is returned. Both negative and positive index values are allowed. Negative indexing starts from the end=width-1.

If endIndex is not provided, width of the LogicValue will be used as the default values which assign it to the last index.

LogicValue.ofString('0101').getRange(0, 2);  // LogicValue.ofString('01')
LogicValue.ofString('0101').getRange(1, -2); // LogicValue.zero
LogicValue.ofString('0101').getRange(-3, 4); // LogicValue.ofString('010')
LogicValue.ofString('0101').getRange(1);     // LogicValue.ofString('010')

// Error - negative end index and start > end! start must be less than end
LogicValue.ofString('0101').getRange(-1, -2);

// Error - bad inputs start > end
LogicValue.ofString('0101').getRange(2, 1);

// Error - bad inputs end > length-1
LogicValue.ofString('0101').getRange(0, 7);

Implementation

LogicValue getRange(int startIndex, [int? endIndex]) {
  endIndex ??= width;

  final modifiedStartIndex =
      IndexUtilities.wrapIndex(startIndex, width, allowWidth: true);
  final modifiedEndIndex =
      IndexUtilities.wrapIndex(endIndex, width, allowWidth: true);

  // if we're getting the whole thing, just return itself immediately
  if (modifiedStartIndex == 0 && modifiedEndIndex == width) {
    return this;
  }

  IndexUtilities.validateRange(modifiedStartIndex, modifiedEndIndex);

  return _getRange(modifiedStartIndex, modifiedEndIndex);
}