require 'luabit.bit';
require 'luabit.hex';
do
local function shift(s)
s1 = tonumber((string.sub(s, 1, 2)), 16);
s2 = bit.blshift(tonumber((string.sub(s, 3, 4)), 16), 8);
s3 = bit.blshift(tonumber((string.sub(s, 5, 6)), 16), 16);
s4 = bit.blshift(tonumber((string.sub(s, 7, 8)), 16), 24);
sa = bit.bor(bit.bor(bit.bor(s1, s2), s3), s4);
return sa;
end
local function bitwise(m)
s1 = shift(string.sub(m, 1, 8));
s2 = shift(string.sub(m, 9, 16));
s3 = shift(string.sub(m, 17, 24));
s4 = shift(string.sub(m, 25, 32));
sa = s1 + s2 + s3 + s4;
return sa;
end
local function str2point(str)
md5 = ngx.md5(str);
point = bitwise(md5);
return point;
end
-- sps = aring
-- sp = point
local function search(sp, sps, pstart, pend, n)
n = n + 1;
local mid, mod = math.modf((pstart + pend) / 2);
if n > 20 then
ngx.log(ngx.ERR, 'the point ' .. sp .. ' cycle index exceed 20');
ngx.exit(509);
end
if sps[mid] >= sp and sps[mid - 1] < sp then
return sps[mid];
elseif sps[mid + 1] >= sp and sps[mid] < sp then
return sps[mid + 1];
elseif sps[mid] > sp then
pend = mid;
return search(sp, sps, pstart, pend, n);
elseif sps[mid] < sp then
pstart = mid;
return search(sp, sps, pstart, pend, n);
end
end
-- fps = points
-- frs = rings
-- fnode = node name
local function findhost(fp, fps, ffls, fsgls, fls, frs, fnode)
local fflag = ffls.get(fnode);
if fflag == 's' then
--ngx.say('single
');
return fsgls.get(fnode);
elseif fflag == 'h' then
local ps = fps.get(fnode);
local fend = table.getn(ps);
if fp <= ps[1] or ps[fend] < fp then
return frs.get(fnode).get(ps[1]);
else
tp = search(fp, ps, 1, fend, 0);
if tp ~= nil then
return frs.get(fnode).get(tp);
else
ngx.log(ngx.ERR, 'search ring error ' .. fp .. '
');
end
end
elseif fflag == 'l' then
floops = fls.get(fnode);
total = table.getn(floops);
math.randomseed(os.time());
rp = math.random(1, total);
return floops[rp];
end
end
ring = {
shift = shift,
bitwise = bitwise,
str2point = str2point,
findhost = findhost,
}
end