UuidV7.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Uid;
  11. use Symfony\Component\Uid\Exception\InvalidArgumentException;
  12. /**
  13. * A v7 UUID is lexicographically sortable and contains a 58-bit timestamp and 64 extra unique bits.
  14. *
  15. * Within the same millisecond, the unique bits are incremented by a 24-bit random number.
  16. * This method provides microsecond precision for the timestamp, and minimizes both the
  17. * risk of collisions and the consumption of the OS' entropy pool.
  18. *
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. class UuidV7 extends Uuid implements TimeBasedUidInterface
  22. {
  23. protected const TYPE = 7;
  24. private static string $time = '';
  25. private static int $subMs = 0;
  26. private static array $rand = [];
  27. private static string $seed;
  28. private static array $seedParts;
  29. private static int $seedIndex = 0;
  30. public function __construct(?string $uuid = null)
  31. {
  32. if (null === $uuid) {
  33. $this->uid = static::generate();
  34. } else {
  35. parent::__construct($uuid, true);
  36. }
  37. }
  38. public function getDateTime(): \DateTimeImmutable
  39. {
  40. $time = substr($this->uid, 0, 8).substr($this->uid, 9, 4);
  41. $time = \PHP_INT_SIZE >= 8 ? (string) hexdec($time) : BinaryUtil::toBase(hex2bin($time), BinaryUtil::BASE10);
  42. if (4 > \strlen($time)) {
  43. $time = '000'.$time;
  44. }
  45. $time .= substr(1000 + (hexdec(substr($this->uid, 14, 4)) >> 2 & 0x3FF), -3);
  46. return \DateTimeImmutable::createFromFormat('U.u', substr_replace($time, '.', -6, 0));
  47. }
  48. public static function generate(?\DateTimeInterface $time = null): string
  49. {
  50. if (null === $mtime = $time) {
  51. $time = microtime(false);
  52. $subMs = (int) substr($time, 5, 3);
  53. $time = substr($time, 11).substr($time, 2, 3);
  54. } elseif (0 > $time = $time->format('Uu')) {
  55. throw new InvalidArgumentException('The timestamp must be positive.');
  56. } else {
  57. $subMs = (int) substr($time, -3);
  58. $time = substr($time, 0, -3);
  59. }
  60. if ($time > self::$time || (null !== $mtime && $time !== self::$time)) {
  61. randomize:
  62. self::$rand = unpack(\PHP_INT_SIZE >= 8 ? 'L*' : 'S*', isset(self::$seed) ? random_bytes(8) : self::$seed = random_bytes(16));
  63. self::$time = $time;
  64. } else {
  65. // Within the same ms, we increment the rand part by a random 24-bit number.
  66. // Instead of getting this number from random_bytes(), which is slow, we get
  67. // it by sha512-hashing self::$seed. This produces 64 bytes of entropy,
  68. // which we need to split in a list of 24-bit numbers. unpack() first splits
  69. // them into 16 x 32-bit numbers; we take the first byte of each of these
  70. // numbers to get 5 extra 24-bit numbers. Then, we consume those numbers
  71. // one-by-one and run this logic every 21 iterations.
  72. // self::$rand holds the random part of the UUID, split into 2 x 32-bit numbers
  73. // or 4 x 16-bit for x86 portability. We increment this random part by the next
  74. // 24-bit number in the self::$seedParts list and decrement self::$seedIndex.
  75. if (!self::$seedIndex) {
  76. $s = unpack(\PHP_INT_SIZE >= 8 ? 'L*' : 'l*', self::$seed = hash('sha512', self::$seed, true));
  77. $s[] = ($s[1] >> 8 & 0xFF0000) | ($s[2] >> 16 & 0xFF00) | ($s[3] >> 24 & 0xFF);
  78. $s[] = ($s[4] >> 8 & 0xFF0000) | ($s[5] >> 16 & 0xFF00) | ($s[6] >> 24 & 0xFF);
  79. $s[] = ($s[7] >> 8 & 0xFF0000) | ($s[8] >> 16 & 0xFF00) | ($s[9] >> 24 & 0xFF);
  80. $s[] = ($s[10] >> 8 & 0xFF0000) | ($s[11] >> 16 & 0xFF00) | ($s[12] >> 24 & 0xFF);
  81. $s[] = ($s[13] >> 8 & 0xFF0000) | ($s[14] >> 16 & 0xFF00) | ($s[15] >> 24 & 0xFF);
  82. self::$seedParts = $s;
  83. self::$seedIndex = 21;
  84. }
  85. if (\PHP_INT_SIZE >= 8) {
  86. self::$rand[2] = 0xFFFFFFFF & $carry = self::$rand[2] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
  87. self::$rand[1] = 0xFFFFFFFF & $carry = self::$rand[1] + ($carry >> 32);
  88. $carry >>= 32;
  89. } else {
  90. self::$rand[4] = 0xFFFF & $carry = self::$rand[4] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
  91. self::$rand[3] = 0xFFFF & $carry = self::$rand[3] + ($carry >> 16);
  92. self::$rand[2] = 0xFFFF & $carry = self::$rand[2] + ($carry >> 16);
  93. self::$rand[1] = 0xFFFF & $carry = self::$rand[1] + ($carry >> 16);
  94. $carry >>= 16;
  95. }
  96. if ($carry && $subMs <= self::$subMs) {
  97. usleep(1);
  98. if (1024 <= ++$subMs) {
  99. if (\PHP_INT_SIZE >= 8 || 10 > \strlen($time = self::$time)) {
  100. $time = (string) (1 + $time);
  101. } elseif ('999999999' === $mtime = substr($time, -9)) {
  102. $time = (1 + substr($time, 0, -9)).'000000000';
  103. } else {
  104. $time = substr_replace($time, str_pad(++$mtime, 9, '0', \STR_PAD_LEFT), -9);
  105. }
  106. goto randomize;
  107. }
  108. }
  109. $time = self::$time;
  110. }
  111. self::$subMs = $subMs;
  112. if (\PHP_INT_SIZE >= 8) {
  113. return substr_replace(\sprintf('%012x-%04x-%04x-%04x%08x',
  114. $time,
  115. 0x7000 | ($subMs << 2) | (self::$rand[1] >> 30),
  116. 0x8000 | (self::$rand[1] >> 16 & 0x3FFF),
  117. self::$rand[1] & 0xFFFF,
  118. self::$rand[2],
  119. ), '-', 8, 0);
  120. }
  121. return substr_replace(\sprintf('%012s-%04x-%04x-%04x%04x%04x',
  122. bin2hex(BinaryUtil::fromBase($time, BinaryUtil::BASE10)),
  123. 0x7000 | ($subMs << 2) | (self::$rand[1] >> 14),
  124. 0x8000 | (self::$rand[1] & 0x3FFF),
  125. self::$rand[2],
  126. self::$rand[3],
  127. self::$rand[4],
  128. ), '-', 8, 0);
  129. }
  130. }