lib: ip: add 'nthInRange4'

And use it to refactor 'rangeIp4'
This commit is contained in:
Bruno BELANYI 2021-04-24 23:07:44 +00:00
parent 509332270e
commit 1968285d0a

View file

@ -86,27 +86,29 @@ rec {
# Pretty print a parsed subnet into a human readable form # Pretty print a parsed subnet into a human readable form
prettySubnet4 = { baseIp, cidr, ... }: "${prettyIp4 baseIp}/${toString cidr}"; prettySubnet4 = { baseIp, cidr, ... }: "${prettyIp4 baseIp}/${toString cidr}";
# Get the nth address from an IPv4 range, without checking if it is in range
nthInRange4 = { from, to }: n:
let
carry = lhs: { carry, acc }:
let
totVal = lhs + carry;
in
{
carry = totVal / 256;
acc = [ (mod totVal 256) ] ++ acc;
};
carried = foldr carry { carry = n; acc = [ ]; } from;
in
carried.acc;
# Convert an IPv4 range into a list of all its constituent addresses # Convert an IPv4 range into a list of all its constituent addresses
rangeIp4 = rangeIp4 =
{ from, to }: { from, to } @ arg:
let let
numAddresses = numAddresses =
builtins.foldl' (acc: rhs: acc * 256 + rhs) builtins.foldl' (acc: rhs: acc * 256 + rhs)
0 0
(zipListsWith (lhs: rhs: lhs - rhs) to from); (zipListsWith (lhs: rhs: lhs - rhs) to from);
addToBase = n:
let
carry = lhs: { carry, acc }:
let
totVal = lhs + carry;
in
{
carry = totVal / 256;
acc = [ (mod totVal 256) ] ++ acc;
};
carried = foldr carry { carry = n; acc = [ ]; } from;
in
carried.acc;
in in
map addToBase (range 0 numAddresses); map (nthInRange4 arg) (range 0 numAddresses);
} }