Mercurial > prosody-hg
comparison util/ip.lua @ 8431:a5a03d40a20c
util.ip: Make bit string function into a method
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Fri, 01 Dec 2017 04:37:33 +0100 |
| parents | a58d560aa8d5 |
| children | da807f4f706c |
comparison
equal
deleted
inserted
replaced
| 8430:a58d560aa8d5 | 8431:a5a03d40a20c |
|---|---|
| 49 end | 49 end |
| 50 | 50 |
| 51 return setmetatable({ addr = ipStr, packed = packed, proto = proto, zone = zone }, ip_mt); | 51 return setmetatable({ addr = ipStr, packed = packed, proto = proto, zone = zone }, ip_mt); |
| 52 end | 52 end |
| 53 | 53 |
| 54 local function toBits(ip) | 54 function ip_methods.bits(ip) |
| 55 local result = ""; | |
| 56 local fields = {}; | |
| 57 if ip.proto == "IPv4" then | |
| 58 ip = ip.toV4mapped; | |
| 59 end | |
| 60 ip = (ip.addr):upper(); | 55 ip = (ip.addr):upper(); |
| 61 ip:gsub("([^:]*):?", function (c) fields[#fields + 1] = c end); | 56 ip:gsub("([^:]*):?", function (c) fields[#fields + 1] = c end); |
| 62 if not ip:match(":$") then fields[#fields] = nil; end | 57 if not ip:match(":$") then fields[#fields] = nil; end |
| 63 for i, field in ipairs(fields) do | 58 for i, field in ipairs(fields) do |
| 64 if field:len() == 0 and i ~= 1 and i ~= #fields then | 59 if field:len() == 0 and i ~= 1 and i ~= #fields then |
| 75 end | 70 end |
| 76 end | 71 end |
| 77 return result; | 72 return result; |
| 78 end | 73 end |
| 79 | 74 |
| 75 function ip_methods.bits_full(ip) | |
| 76 if ip.proto == "IPv4" then | |
| 77 ip = ip.toV4mapped; | |
| 78 end | |
| 79 return ip.bits; | |
| 80 end | |
| 81 | |
| 80 local function commonPrefixLength(ipA, ipB) | 82 local function commonPrefixLength(ipA, ipB) |
| 81 ipA, ipB = toBits(ipA), toBits(ipB); | 83 ipA, ipB = ipA.bits_full, ipB.bits_full; |
| 82 for i = 1, 128 do | 84 for i = 1, 128 do |
| 83 if ipA:sub(i,i) ~= ipB:sub(i,i) then | 85 if ipA:sub(i,i) ~= ipB:sub(i,i) then |
| 84 return i-1; | 86 return i-1; |
| 85 end | 87 end |
| 86 end | 88 end |
