Uuid.timeBasedUuid constructor
Uuid.timeBasedUuid()
Generates a time-based UUID (version 1).
Returns:
- A new time-based UUID with version 1 and variant 2 (RFC 4122)
Time-Based Properties
- Incorporates current timestamp with 100-nanosecond precision
- Includes clock sequence to handle clock adjustments
- Uses random node identifier (no MAC address exposure)
- Sortable by generation time
Privacy Considerations
This implementation uses a random node identifier instead of the actual MAC address to protect privacy while maintaining UUID uniqueness.
Example
final uuid1 = Uuid.timeBasedUuid();
await Future.delayed(Duration(milliseconds: 1));
final uuid2 = Uuid.timeBasedUuid();
print(uuid1.compareTo(uuid2) < 0); // true (uuid1 generated first)
print(uuid1.version); // 1
Implementation
factory Uuid.timeBasedUuid() {
// Get current time in 100-nanosecond intervals since UUID epoch
final now = DateTime.now().millisecondsSinceEpoch;
final uuidEpoch = DateTime(1582, 10, 15).millisecondsSinceEpoch;
final timestamp = BigInteger.fromInt(now - uuidEpoch) * BigInteger.fromInt(10000); // 100ns intervals
// Generate 14-bit clock sequence
final clockSeq = BigInteger.fromInt(_secureRandom.nextInt(0x4000));
// Generate 48-bit node ID from secure random bytes
BigInteger node = BigInteger.ZERO;
for (var i = 0; i < 6; i++) {
node = (node << 8) | BigInteger.fromInt(_secureRandom.nextInt(256));
}
// Build UUID components
final timeLow = timestamp & BigInteger.fromInt(0xFFFFFFFF);
final timeMid = (timestamp >> 32) & BigInteger.fromInt(0xFFFF);
final timeHiAndVersion = ((timestamp >> 48) & BigInteger.fromInt(0x0FFF)) | BigInteger.fromInt(0x1000); // v1
final clockSeqHiAndReserved = ((clockSeq >> 8) | BigInteger.fromInt(0x80)) & BigInteger.fromInt(0xFF); // variant 2
final clockSeqLow = clockSeq & BigInteger.fromInt(0xFF);
final mostSigBits = (timeLow << 32) | (timeMid << 16) | timeHiAndVersion;
final leastSigBits = (clockSeqHiAndReserved << 56) | (clockSeqLow << 48) | node;
return Uuid._(mostSigBits, leastSigBits);
}