Anonymous user
Module:IP: Difference between revisions
From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
move more metamethods out of the constructor, edit ipv4Address and ipv6Address for style
(try original format again) |
(move more metamethods out of the constructor, edit ipv4Address and ipv6Address for style) |
||
Line 165:
end
--------------------------------------------------------------------------------
-- IPAddress class
-- Represents a single IPv4 or IPv6 address.
--------------------------------------------------------------------------------
local IPAddress = {}
do
local dataKey = {} -- A unique key to access objects' internal data.
-- Private static methods
local function parseIPv4(ipStr)
-- If ipStr is a valid IPv4 string, return a collection of its parts.
-- Otherwise, return nil.
-- This representation is for compatibility with IPv6 addresses.
local octets = collection()
local s = ipStr:match('^%s*(.-)%s*$') .. '.'
for item in s:gmatch('(.-)%.') do
octets:add(item)
end
if octets.n == 4 then
for i, s in ipairs(octets) do
if s:match('^%d+$') then
local num = tonumber(s)
if 0 <= num and num <= 255 then
if num > 0 and s:match('^0') then
-- A redundant leading zero is for an IP in octal.
return false
end
octets[i] = num
else
return false
end
else
return false
end
end
local parts = collection()
for i = 1, 3, 2 do
parts:add(octets[i] * 256 + octets[i+1])
end
return parts
end
return nil
end
local function
ipStr, n = ipStr:gsub('::', string.rep(':', 9 - n))
parts:add(item)
for i, s in ipairs(parts) do
if s == '' then
parts[i] = 0
else
local num = tonumber('0x' .. s)
if num and 0 <= num and num <= 65535 then
parts[i] = num
else
return false
end
end
end
return parts
end
return nil
end
-- Metamethods that don't need upvalues
local function ipEquals(ip1, ip2)
local lhs = ip1[dataKey].parts
Line 268:
end
return lhs.n < rhs.n
end
local function concatIPs(ip1, ip2)
return tostring(ip1) .. tostring(ip2)
end
local function ipToString(ip)
return ipString(ip[dataKey].parts)
end
Line 279 ⟶ 287:
-- Set initial values
if not data.parts then
error('invalid IP', 2)
end
Line 331 ⟶ 340:
__eq = ipEquals,
__lt = ipLessThan,
__concat = concatIPs,
__tostring = ipToString,
__index = function (self, key)
if key == dataKey then
return data
else
return IPAddress[key]
end
end,
})
|