v1 static method
Generates a version 1 (time-based) UUID: a 60-bit timestamp (100ns intervals since 1582-10-15) plus a random clock sequence and node ID.
The node ID is meant to be an IEEE 802 (MAC) address per the RFC, but there's no portable way to read one in pure Dart across native and web - so per RFC 4122 ยง4.1.6's own fallback, this uses a random 48-bit value with the multicast bit set, which marks it as explicitly not a real hardware address (avoiding any risk of colliding with one).
Implementation
static String v1() {
final bytes = List<int>.filled(16, 0);
// The timestamp is computed via BigInt: at today's date it's already
// past 2^53 (~1.4e17), well beyond what's exact as a plain
// double/int on every platform.
final microsSinceUnixEpoch = BigInt.from(
DateTime.now().microsecondsSinceEpoch,
);
final timestamp100ns =
microsSinceUnixEpoch * BigInt.from(10) + _v1EpochOffset100ns;
final timeLow = (timestamp100ns & BigInt.from(0xFFFFFFFF)).toInt();
final timeMid = ((timestamp100ns >> 32) & BigInt.from(0xFFFF)).toInt();
final timeHiAndVersion =
(((timestamp100ns >> 48) & BigInt.from(0x0FFF)) | BigInt.from(0x1000))
.toInt();
// Extracting bytes from these already-bounded plain-int values (timeLow
// is < 2^32, timeMid/timeHiAndVersion < 2^16) via division/modulo
// rather than shifts - after getting burned once already by a wrong
// assumption about which bitwise ops dart2js handles exactly near the
// 32-bit boundary (see bch_bech32.dart's doc comment for the full
// story), plain arithmetic is the option that doesn't require being
// sure about that boundary at all.
bytes[0] = timeLow ~/ 0x1000000;
bytes[1] = (timeLow ~/ 0x10000) % 0x100;
bytes[2] = (timeLow ~/ 0x100) % 0x100;
bytes[3] = timeLow % 0x100;
bytes[4] = timeMid ~/ 0x100;
bytes[5] = timeMid % 0x100;
bytes[6] = timeHiAndVersion ~/ 0x100; // version nibble lives in here
bytes[7] = timeHiAndVersion % 0x100;
// 14-bit clock sequence: random, since this is a stateless generator
// with no persisted "last timestamp" to compare against and bump on
// a same-millisecond collision (the RFC's documented fallback for
// that situation).
final clockSeq = QuickCrypto.generateRandomInt(16384); // 0..2^14-1
bytes[8] = ((clockSeq ~/ 0x100) & 0x3F) | 0x80; // variant bits folded in
bytes[9] = clockSeq % 0x100;
final node = QuickCrypto.generateRandom(length: 6);
node[0] |= 0x01; // multicast bit - "this is not a real MAC address"
for (var i = 0; i < 6; i++) {
bytes[10 + i] = node[i];
}
return _bytesToUuidString(bytes);
}