From 1968285d0aebbf3b731d0433a7e1543cef71eb8e Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 24 Apr 2021 23:07:44 +0000 Subject: [PATCH] lib: ip: add 'nthInRange4' And use it to refactor 'rangeIp4' --- lib/ip.nix | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/lib/ip.nix b/lib/ip.nix index 223d403..f499072 100644 --- a/lib/ip.nix +++ b/lib/ip.nix @@ -86,27 +86,29 @@ rec { # Pretty print a parsed subnet into a human readable form 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 rangeIp4 = - { from, to }: + { from, to } @ arg: let numAddresses = builtins.foldl' (acc: rhs: acc * 256 + rhs) 0 (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 - map addToBase (range 0 numAddresses); + map (nthInRange4 arg) (range 0 numAddresses); }