aboutsummaryrefslogtreecommitdiffstats
path: root/lua/inet
diff options
context:
space:
mode:
authorAsbjørn Sloth Tønnesen <ast@2e8.dk>2019-07-20 18:19:38 +0000
committerAsbjørn Sloth Tønnesen <ast@2e8.dk>2019-07-20 18:19:38 +0000
commit9edfd0002bea4d591cb363be536c652ef3f16079 (patch)
treeac6574c09294672d5cbe79eae186588934df5d8f /lua/inet
parentd42329c948cafec31250c8cdba028d116a76a709 (diff)
downloadlua-inet-9edfd0002bea4d591cb363be536c652ef3f16079.tar.gz
lua-inet-9edfd0002bea4d591cb363be536c652ef3f16079.tar.xz
lua-inet-9edfd0002bea4d591cb363be536c652ef3f16079.zip
add inet:subnets()
Signed-off-by: Asbjørn Sloth Tønnesen <ast@2e8.dk>
Diffstat (limited to 'lua/inet')
-rw-r--r--lua/inet/core.lua13
1 files changed, 12 insertions, 1 deletions
diff --git a/lua/inet/core.lua b/lua/inet/core.lua
index f1c7c49..15dd0f9 100644
--- a/lua/inet/core.lua
+++ b/lua/inet/core.lua
@@ -6,6 +6,7 @@ local format = string.format
local floor = math.floor
local min = math.min
local max = math.max
+local pow = math.pow
local insert = table.insert
local lshift = bit32.lshift
@@ -55,6 +56,16 @@ end
inet4.__len = inet.__len
inet6.__len = inet.__len
+function inet:subnets(n)
+ if type(n) ~= 'number' then return nil, 'n must be a number' end
+ local hostmask = is_inet6(self) and 128 or 32
+ if n < 0 or n > hostmask then return nil, 'invalid mask given' end
+ local mask = self.mask
+ local bits = n - mask
+ local subnets = pow(2, bits)
+ return subnets
+end
+
function inet:family()
local mt = assert(getmetatable(self))
return assert(mt2fam[mt])
@@ -329,7 +340,7 @@ function inet4:__sub(n)
end
function inet4:__mul(n)
- local new = self.bip + (n * math.pow(2, 32 - self.mask))
+ local new = self.bip + (n * pow(2, 32 - self.mask))
return new_inet4(new, self.mask)
end