feat: 결정론적 난수 생성기 ts 버전 구현
This commit is contained in:
+13
-12
@@ -21,14 +21,14 @@ class LiteHashDRBG implements RNG
|
||||
|
||||
protected string $buffer;
|
||||
protected int $bufferIdx;
|
||||
protected function __construct(protected string $seed, protected int $stateIdx = 0)
|
||||
public function __construct(protected string $seed, protected int $stateIdx = 0)
|
||||
{
|
||||
$this->genNextBlock();
|
||||
}
|
||||
|
||||
protected function genNextBlock(): void
|
||||
{
|
||||
$hq = $this->seed . pack('P', $this->stateIdx);
|
||||
$hq = $this->seed . pack('V', $this->stateIdx);
|
||||
$this->buffer = hash('sha512', $hq, true);
|
||||
$this->bufferIdx = 0;
|
||||
$this->stateIdx += 1;
|
||||
@@ -149,9 +149,10 @@ class LiteHashDRBG implements RNG
|
||||
$headBits = $bits & 0x7;
|
||||
|
||||
$buffer = $this->nextBytes($bytes);
|
||||
if ($headBits != 0) {
|
||||
$buffer[$bytes - 1] = chr(ord($buffer[$bytes - 1]) & (0xff >> (8 - $headBits))) ;
|
||||
if ($headBits === 0) {
|
||||
return $buffer;
|
||||
}
|
||||
$buffer[$bytes - 1] = chr(ord($buffer[$bytes - 1]) & (0xff >> (8 - $headBits)));
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
@@ -161,11 +162,8 @@ class LiteHashDRBG implements RNG
|
||||
return unpack('P', $value)[1];
|
||||
}
|
||||
|
||||
private function _nextInt(int $max): int
|
||||
private function _nextInt(int $bits): int
|
||||
{
|
||||
$mask = self::calcBitMask($max);
|
||||
$bits = self::INT_BIT_MASK_MAP[$mask];
|
||||
|
||||
$buffer = $this->nextBits($bits) . "\x00\x00\x00\x00\x00\x00\x00";
|
||||
|
||||
return self::parseU64($buffer);
|
||||
@@ -186,9 +184,12 @@ class LiteHashDRBG implements RNG
|
||||
return -$this->nextInt(-$max);
|
||||
}
|
||||
|
||||
$n = $this->_nextInt($max);
|
||||
$mask = self::calcBitMask($max);
|
||||
$bits = self::INT_BIT_MASK_MAP[$mask];
|
||||
|
||||
$n = $this->_nextInt($bits);
|
||||
while ($n > $max) {
|
||||
$n = $this->_nextInt($max);
|
||||
$n = $this->_nextInt($bits);
|
||||
}
|
||||
|
||||
return $n;
|
||||
@@ -197,10 +198,10 @@ class LiteHashDRBG implements RNG
|
||||
public function nextFloat1(): float
|
||||
{
|
||||
$max = 1 << MAX_RNG_SUPPORT_BIT;
|
||||
while(true){
|
||||
while (true) {
|
||||
$buffer = $this->nextBits(MAX_RNG_SUPPORT_BIT + 1) . "\x00";
|
||||
$nInt = self::parseU64($buffer);
|
||||
if($nInt <= $max){
|
||||
if ($nInt <= $max) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ class RandUtil
|
||||
return $this->rng->nextInt($range) + $min;
|
||||
}
|
||||
|
||||
public function nextInt(?int $max = null): int{
|
||||
return $this->rng->nextInt($max);
|
||||
}
|
||||
|
||||
public function nextBit(): bool
|
||||
{
|
||||
return $this->rng->nextBits(1) !== "\0";
|
||||
|
||||
@@ -809,5 +809,4 @@ class Util extends \utilphp\util
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user