Skip to content

Commit

Permalink
Improve memory efficency of IP generation (#675)
Browse files Browse the repository at this point in the history
* Improve mem efficency with final ip range generation

* Improve range memory efficency
  • Loading branch information
inverse committed Oct 6, 2022
1 parent 0029852 commit 46d18d1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
38 changes: 32 additions & 6 deletions tasmoadmin/src/Helper/IpHelper.php
Expand Up @@ -17,14 +17,19 @@ public function fetchIps(string $fromIp, string $toIp, array $excludedIps = []):
throw new InvalidArgumentException(sprintf('%s is an invalid IPv4 address', $toIp));
}

$ips = [];
foreach ($this->xrange(ip2long($fromIp), ip2long($toIp)) as $ip) {
$ip = long2ip($ip);
if (in_array($ip, $excludedIps)) {
continue;
}

$ips[] = $ip;

$ips = array_map('long2ip', range(ip2long($fromIp), ip2long($toIp)));
if (count($ips) > self::MAX_IPS) {
throw new InvalidArgumentException('The defined IP range is too large, please specify a smaller range');
}


$ips = array_diff($ips, $excludedIps);

if (count($ips) > self::MAX_IPS) {
throw new InvalidArgumentException('The defined IP range is too large, please specify a smaller range');
}

return $ips;
Expand All @@ -35,4 +40,25 @@ private function isIpValid(string $ip): bool
{
return ip2long($ip) !== false;
}

private function xrange(int $start, int $limit, int $step = 1) {
if ($start <= $limit) {
if ($step <= 0) {
throw new InvalidArgumentException('Step must be positive');
}

for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new InvalidArgumentException('Step must be negative');
}

for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}

}
2 changes: 1 addition & 1 deletion tasmoadmin/tests/Helper/IpHelperTest.php
Expand Up @@ -30,7 +30,7 @@ public function testFetchIpsTooLargeRange(): void
{
$this->expectException(InvalidArgumentException::class);
$ipHelper = new IpHelper();
$ipHelper->fetchIps('127.0.0.1', '127.0.8.2');
$ipHelper->fetchIps('127.0.0.1', '127.255.8.2');
}

public function testFetchIpsSingleIp(): void
Expand Down

0 comments on commit 46d18d1

Please sign in to comment.