generate method

  1. @override
Uuid generate()
override

Creates a new UUID.

Implementation

@override
Uuid generate() {
  // https://datatracker.ietf.org/doc/html/rfc4122#section-4.2.2
  var clockSequence = _clockSequence;

  // Approximate higher-resoluton timestamps.
  var ms = _now().millisecondsSinceEpoch;
  var ns = ++_lastNs;

  // Time since last UUID creation (in ms).
  final dt = ms - _lastMs + (ns - _lastNs) / 10000;

  // Per 4.2.1.2, bump on clock regression.
  if (dt < 0) {
    clockSequence = (clockSequence + 1) & 0x3fff;
  }

  // Reset simulated nano-seconds if clock regresses or new time interval.
  if (dt < 0 || ms > _lastMs) {
    ns = 0;
  }

  // Per 4.2.1.2 throw an error if too many UUIDs are requested.
  if (ns >= 10000) {
    throw StateError('Cannot create more than 10M UUIDs/sec');
  }

  _lastMs = ms;
  _lastNs = ns;
  _clockSequence = clockSequence;

  // Per 4.1.4, convert from Unix epoch to Gregorian epoch.
  ms += _gregorianToUnix;

  return _generate(ms, ns, clockSequence, _uniqueId);
}