Created
June 30, 2022 06:20
-
-
Save guanguans/622f7e2d7f433572a53b12f2afb0d22d to your computer and use it in GitHub Desktop.
#php #mist
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
<?php | |
/** | |
* 薄雾算法 | |
* | |
* 1 2 48 56 64 | |
* +------+-----------------------------------------------------+----------+----------+ | |
* retain | increas | salt | sequence | | |
* +------+-----------------------------------------------------+----------+----------+ | |
* 0 | 0000000000 0000000000 0000000000 0000000000 0000000 | 00000000 | 00000000 | | |
* +------+-----------------------------------------------------+------------+--------+ | |
* | |
* 0. 最高位,占 1 位,保持为 0,使得值永远为正数; | |
* 1. 自增数,占 47 位,自增数在高位能保证结果值呈递增态势,遂低位可以为所欲为; | |
* 2. 随机因子一,占 8 位,上限数值 255,使结果值不可预测; | |
* 3. 随机因子二,占 8 位,上限数值 255,使结果值不可预测; | |
* | |
* 编号上限为百万亿级,上限值计算为 140737488355327 即 int64(1 << 47 - 1),假设每天取值 10 亿,能使用 385+ 年 | |
*/ | |
class Mist | |
{ | |
/** | |
* 随机因子二进制位数 | |
*/ | |
public const SALT_BIT = 8; | |
/** | |
* 随机因子移位数 | |
*/ | |
public const SALT_SHIFT = 8; | |
/** | |
* 自增数移位数 | |
*/ | |
public const INCREASE_SHIFT = self::SALT_BIT + self::SALT_SHIFT; | |
/** | |
* @var int 自增数 | |
*/ | |
public $increase = 0; | |
/** | |
* @var int 随机因子一 | |
*/ | |
public $saltA = 0; | |
/** | |
* @var int 随机因子二 | |
*/ | |
public $saltB = 0; | |
public function __construct(int $increase = 1) | |
{ | |
$this->increase = $increase; | |
} | |
public function generate(): int | |
{ | |
$this->increase = ++$this->increase; | |
// 获取随机因子数值 | |
try { | |
$this->saltA = random_int($this->saltA, 255); | |
} catch (\Throwable $e) { | |
$this->saltA = $this->saltA++; | |
} | |
try { | |
$this->saltB = random_int($this->saltB, 255); | |
} catch (\Throwable $e) { | |
$this->saltB = $this->saltB++; | |
} | |
return ($this->increase << self::INCREASE_SHIFT) | ($this->saltA << self::SALT_SHIFT) | $this->saltB; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment