v7 static method

String v7()

Generates a version 7 UUID: a 48-bit Unix timestamp in milliseconds followed by random bits. Unlike v1/v4, v7 UUIDs generated in increasing time order sort in increasing lexicographic/byte order too - useful as a database primary key where index locality matters.

Implementation

static String v7() {
  final bytes = List<int>.filled(16, 0);
  final ms = DateTime.now().millisecondsSinceEpoch; // ~1.7e12 today

  // Split the 48-bit ms value into two 24-bit halves via integer
  // division/modulo - NOT bit shifts - before doing any bitwise byte
  // extraction. Dividing/mod'ing a double-safe value stays exact on
  // every platform, but *shifting* a value past 32 bits is not
  // reliably exact on dart2js (its native bitwise ops truncate through
  // JS's ToInt32 first, same class of issue documented on Uint64's
  // _safeShl32). Splitting first keeps every subsequent shift
  // comfortably under 32 bits, so plain `int` bitwise ops are safe.
  final msHi = ms ~/ 0x1000000; // top 24 bits
  final msLo = ms % 0x1000000; // bottom 24 bits

  bytes[0] = msHi ~/ 0x10000;
  bytes[1] = (msHi ~/ 0x100) % 0x100;
  bytes[2] = msHi % 0x100;
  bytes[3] = msLo ~/ 0x10000;
  bytes[4] = (msLo ~/ 0x100) % 0x100;
  bytes[5] = msLo % 0x100;

  final randA = QuickCrypto.generateRandomInt(4096); // 12 random bits
  bytes[6] =
      ((randA ~/ 0x100) & 0x0F) | 0x70; // version nibble + top of rand_a
  bytes[7] = randA % 0x100;

  // 62-bit rand_b: 8 random bytes with the variant bits folded into
  // the top of the first one - same pattern as v4's byte 8.
  final randB = QuickCrypto.generateRandom(length: 8);
  randB[0] = (randB[0] & 0x3F) | 0x80;
  for (var i = 0; i < 8; i++) {
    bytes[8 + i] = randB[i];
  }

  return _bytesToUuidString(bytes);
}