Skip to content

Commit

Permalink
Add RandomDevice
Browse files Browse the repository at this point in the history
  • Loading branch information
emonkak committed Jun 11, 2016
1 parent 4ba55ee commit 965253e
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/Engine/RandomDevice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Emonkak\Random\Engine;

class RandomDevice extends AbstractEngine
{
/**
* {@inheritDoc}
*/
public function max()
{
return 0x7fffffff;
}

/**
* {@inheritDoc}
*/
public function min()
{
return 0;
}

/**
* {@inheritDoc}
*/
public function next()
{
$bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
if ($bytes === false || strlen($bytes) !== 4) {
throw new RuntimeException('Unable to get 4 bytes');
}
$array = unpack('Nint', $bytes);
return $array['int'] & 0x7FFFFFFF; // 32-bit safe
}
}
33 changes: 33 additions & 0 deletions tests/Engine/RandomDeviceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Emonkak\Random\Tests\Engine;

use Emonkak\Random\Engine\RandomDevice;

/**
* @requires extension mcrypt
*/
class RandomDeviceTest extends \PHPUnit_Framework_TestCase
{
public function testMax()
{
return $this->assertSame(0x7fffffff, (new RandomDevice())->max());
}

public function testMin()
{
return $this->assertSame(0, (new RandomDevice())->min());
}

public function testNext()
{
$engine = new RandomDevice();

for ($i = 0; $i < 1000; $i++) {
$n = $engine->next();

$this->assertGreaterThanOrEqual($engine->min(), $n);
$this->assertLessThanOrEqual($engine->max(), $n);
}
}
}

0 comments on commit 965253e

Please sign in to comment.