Anonymous user
Module:IP: Difference between revisions
From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
add IPAddress and Subnet validation functions
(allow strings to isInSubnet) |
(add IPAddress and Subnet validation functions) |
||
Line 25:
'invalid %s object. Did you call %s with a dot instead of a colon, i.e. %s.%s() instead of %s:%s()?',
className, methodName, objectName, methodName, objectName, methodName
), 3)
end▼
end
local function makeValidationFunc(className, isObjectFunc)
-- Make a function for validating
return function (methodName, argIdx, arg)
if not isObjectFunc(arg) then
error(string.format(
"bad argument #%d to '%s' (not a valid %s object)",
argIdx, methodName, className
), 3)
end
Line 320 ⟶ 332:
--------------------------------------------------------------------------------
-- Initialize private
--------------------------------------------------------------------------------▼
-- Both IPAddress and Subnet need access to each others' private constructor
-- functions. IPAddress must be able to make Subnet objects from CIDR strings
Line 329 ⟶ 342:
-- to worry about RawIP objects. Because they are private, they must be
-- initialized here.
▲--------------------------------------------------------------------------------
local makeIPAddress, makeIPAddressFromRaw, makeSubnet, makeSubnetFromRaw
-- IPAddress and Subnet also need to be able to validate Subnet and IPAddress
-- objects that they are passed as input, so initialize those functions here
-- as well.
local validateIPAddress, validateSubnet
--------------------------------------------------------------------------------
Line 359 ⟶ 375:
isIPAddressObject
)
validateIPAddress = makeValidationFunc('IPAddress', isIPAddressObject)
-- Metamethods that don't need upvalues
Line 417 ⟶ 435:
subnet = makeSubnet(subnet)
elseif tp == 'table' then
validateSubnet('isInSubnet', 1, subnet)
else
checkTypeMulti('isInSubnet', 1, subnet, {'string', 'table'})
Line 478 ⟶ 496:
do
local dataKey = {} -- A unique key for accessing Subnet objects' internal data.
-- Private static methods
local function isSubnetObject(val)
return type(val) == 'table' and val[dataKey] ~= nil
end
validateSubnet = makeValidationFunc('Subnet', isSubnetObject)
-- Constructors
makeSubnetFromRaw = function (rawIP, bitLength)
-- Set up structure
local obj =
local data = {
rawIP = rawIP,
Line 565 ⟶ 589:
end
return setmetatable(obj, {
__index = function (self, key)
if key == dataKey then
return data
end
end,
__eq = function (self, obj)
return self:getCIDR() == obj:getCIDR()▼
end,
__tostring = function (self)
return self:getCIDR()▼
end,
})
end
Line 587 ⟶ 623:
checkType('Subnet.new', 1, cidr, 'string')
return makeSubnet(cidr)
▲ end
▲ return self:getCIDR() == obj:getCIDR()
▲ end
▲ return self:getCIDR()
end
end
|