nextInt method

  1. @override
int nextInt(
  1. int max
)
override

Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.

Implementation

@override
int nextInt(int max) {
  // almost the same as https://bit.ly/35OH1Vh by Dart authors, BSD

  if (max <= 0 || max > _POW2_32) {
    throw RangeError.range(
        max, 1, _POW2_32, 'max', 'Must be positive and <= 2^32');
  }

  // to check whether max is a power of two we use
  // condition (https://stackoverflow.com/a/1006999/11700241)
  assert(
      max > 0); // the condition returns wrong result for 0, but it's never 0
  if ((max & -max) == max) {
    // max is a power of two
    return nextRaw32() & (max - 1);
  }

  // max is not a power of two
  int rnd32;
  int result;
  do {
    rnd32 = nextRaw32();
    result = rnd32 % max;
  } while ((rnd32 - result + max) > _POW2_32);
  return result;
}