isRange method

bool isRange(
  1. int start,
  2. int end,
  3. bool value
)

Efficient method to check if a range of bits is set, or not set.

@param start start of range, inclusive. @param end end of range, exclusive @param value if true, checks that bits in range are set, otherwise checks that they are not set @return true iff all bits are set or not set in range, according to value argument @throws IllegalArgumentException if end is less than start or the range is not contained in the array

Implementation

bool isRange(int start, int end, bool value) {
  if (end < start || start < 0 || end > _size) {
    throw ArgumentError(r'Illegal Argument');
  }
  if (end == start) {
    return true; // empty range matches
  }
  end--; // will be easier to treat this as the last actually set bit -- inclusive
  final firstInt = start ~/ 32;
  final lastInt = end ~/ 32;
  for (int i = firstInt; i <= lastInt; i++) {
    final firstBit = i > firstInt ? 0 : start & 0x1F;
    final lastBit = i < lastInt ? 31 : end & 0x1F;
    // Ones from firstBit to lastBit, inclusive
    final mask = (2 << lastBit) - (1 << firstBit);

    // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
    // equals the mask, or we're looking for 0s and the masked portion is not all 0s
    if ((_bits[i] & mask) != (value ? mask : 0)) {
      return false;
    }
  }
  return true;
}