Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Uid] improve logic in BinaryUtil::timeToFloat() #40009

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions src/Symfony/Component/Uid/BinaryUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ class BinaryUtil
// 0x01b21dd213814000 is the number of 100-ns intervals between the
// UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
private const TIME_OFFSET_INT = 0x01b21dd213814000;
private const TIME_OFFSET_BIN = "\x01\xb2\x1d\xd2\x13\x81\x40\x00";
private const TIME_OFFSET_COM1 = "\xfe\x4d\xe2\x2d\xec\x7e\xbf\xff";
private const TIME_OFFSET_COM2 = "\xfe\x4d\xe2\x2d\xec\x7e\xc0\x00";

public static function toBase(string $bytes, array $map): string
Expand Down Expand Up @@ -114,20 +116,24 @@ public static function add(string $a, string $b): string
return $a;
}

/**
* @param string $time Count of 100-nanosecond intervals since the UUID epoch 1582-10-15 00:00:00 in hexadecimal
*/
public static function timeToFloat(string $time): float
{
if (\PHP_INT_SIZE >= 8) {
return (hexdec($time) - self::TIME_OFFSET_INT) / 10000000;
}

$time = str_pad(hex2bin($time), 8, "\0", \STR_PAD_LEFT);
$time = self::add($time, self::TIME_OFFSET_COM2);

if ($time >= self::TIME_OFFSET_COM2) {
$time = -1 * (self::toBase($time ^ "\xff\xff\xff\xff\xff\xff\xff\xff", self::BASE10) + 1);
$time = hexdec($time) - self::TIME_OFFSET_INT;
} else {
$time[0] = $time[0] & "\x7F";
$time = self::toBase($time, self::BASE10);
$time = str_pad(hex2bin($time), 8, "\0", \STR_PAD_LEFT);

if (self::TIME_OFFSET_BIN <= $time) {
$time = self::add($time, self::TIME_OFFSET_COM2);
$time[0] = $time[0] & "\x7F";
$time = self::toBase($time, self::BASE10);
} else {
$time = self::add($time, self::TIME_OFFSET_COM1);
$time = '-'.self::toBase($time ^ "\xff\xff\xff\xff\xff\xff\xff\xff", self::BASE10);
}
}

return $time / 10000000;
Expand Down