Last active
May 15, 2020 09:00
-
-
Save lt/891d4f66a71fe6d16c72a1c475a7dd9b to your computer and use it in GitHub Desktop.
PHP Fast UUIDv4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uuid4(): string | |
{ | |
return bin2hex( | |
// 18 bytes encodes to 36 bytes. 32 for UUID + 4 for hyphens. | |
// Bitwise AND to mask where static bits will be set | |
// Mask and set UUID specific bits | |
// In 00112233-4455-m677-n899-aabbccddeeff, m (4 bits) = version (4), n (2 bits) = variant (2) | |
// 00 11 22 33 -4 45 5- m6 77 -n 89 9- aa bb cc dd ee ff | |
(random_bytes(18) & "\xff\xff\xff\xff\x0f\xff\xf0\x0f\xff\x03\xff\xf0\xff\xff\xff\xff\xff\xff") | | |
// Bitwise OR the version and varient fields of UUIDv4 | |
// m=4 6 - n=2 | |
// Mask 0000 1111 1111 0011 | |
// Bits 0100 0000 0000 1000 | |
// ^^^4 ^^^0 ^^^0 ^^^8 | |
// ^2 | |
"\0\0\0\0\0\0\0\x40\0\x08\0\0\0\0\0\0\0\0" | |
// Set hyphens at the correct positions. Hyphen locations are hex "0". "\x1d" is "0" ^ "-" | |
) ^ "\0\0\0\0\0\0\0\0\x1d\0\0\0\0\x1d\0\0\0\0\x1d\0\0\0\0\x1d\0\0\0\0\0\0\0\0\0\0\0\0"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment