nextUint52 method

  1. @nonVirtual
int nextUint52([
  1. int? max
])

Returns a random cross-platform unsigned 52-bit integer.

Note that 52-bit integers, unlike 64-bit integers, can always be accurately represented in JavaScript.

Implementation

@nonVirtual
int nextUint52([int? max]) {
  if (max != null && (max < 0 || max > _bit52)) {
    throw ArgumentError.value(max, 'max');
  }
  var attempts = 0;
  while (true) {
    // Generate a 52-bit integer from two 32-bit integers.
    final high = nextUint32();
    final low = nextUint32();
    final x = ((_bit32 * (0xFFFFF & high)) + low);
    if (max == null) {
      return x;
    }
    // To avoid modulo bias, we only accept values
    // that are within a multiple of [max].
    final nonAcceptedRange = _bit52 % max;
    if (x < _bit52 - nonAcceptedRange) {
      return x % max;
    }
    if (attempts == 128) {
      // Give up and accept the value anyway.
      // This should never happen.
      assert(false);
      return x % max;
    }
    attempts++;
  }
}