Skip to content

Commit fb913d9

Browse files
bug #52367 [Uid] Fix UuidV7 collisions within the same ms (nicolas-grekas)
This PR was merged into the 6.3 branch. Discussion ---------- [Uid] Fix UuidV7 collisions within the same ms | Q | A | ------------- | --- | Branch? | 6.3 | Bug fix? | yes | New feature? | no | Deprecations? | no | Issues | Fix #52338 | License | MIT Off-by-one errors... Commits ------- e3bf65b [Uid] Fix UuidV7 collisions within the same ms
2 parents 6c62a62 + e3bf65b commit fb913d9

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/Symfony/Component/Uid/UuidV7.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,17 @@ public static function generate(\DateTimeInterface $time = null): string
6464
self::$rand[1] &= 0x03FF;
6565
self::$time = $time;
6666
} else {
67+
// Within the same ms, we increment the rand part by a random 24-bit number.
68+
// Instead of getting this number from random_bytes(), which is slow, we get
69+
// it by sha512-hashing self::$seed. This produces 64 bytes of entropy,
70+
// which we need to split in a list of 24-bit numbers. unpack() first splits
71+
// them into 16 x 32-bit numbers; we take the first byte of each of these
72+
// numbers to get 5 extra 24-bit numbers. Then, we consume those numbers
73+
// one-by-one and run this logic every 21 iterations.
74+
// self::$rand holds the random part of the UUID, split into 5 x 16-bit
75+
// numbers for x86 portability. We increment this random part by the next
76+
// 24-bit number in the self::$seedParts list and decrement self::$seedIndex.
77+
6778
if (!self::$seedIndex) {
6879
$s = unpack('l*', self::$seed = hash('sha512', self::$seed, true));
6980
$s[] = ($s[1] >> 8 & 0xFF0000) | ($s[2] >> 16 & 0xFF00) | ($s[3] >> 24 & 0xFF);
@@ -75,7 +86,7 @@ public static function generate(\DateTimeInterface $time = null): string
7586
self::$seedIndex = 21;
7687
}
7788

78-
self::$rand[5] = 0xFFFF & $carry = self::$rand[5] + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
89+
self::$rand[5] = 0xFFFF & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
7990
self::$rand[4] = 0xFFFF & $carry = self::$rand[4] + ($carry >> 16);
8091
self::$rand[3] = 0xFFFF & $carry = self::$rand[3] + ($carry >> 16);
8192
self::$rand[2] = 0xFFFF & $carry = self::$rand[2] + ($carry >> 16);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy