Skip to content

Commit

Permalink
perf(uuid) generate v4 UUIDs from a smaller set of rand ints
Browse files Browse the repository at this point in the history
Generate V4 UUIDs from various offsets of a 32 bit integer (generated
via the existing `random` call), as opposed to 16 incarnations of an
8 bit integer.
  • Loading branch information
p0pr0ck5 committed Feb 24, 2019
1 parent b1d4458 commit 43bc84d
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions lib/resty/jit-uuid.lua
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ local bit = require 'bit'
local tohex = bit.tohex
local band = bit.band
local bor = bit.bor
local rshift = bit.rshift


local _M = {
Expand Down Expand Up @@ -149,27 +150,32 @@ do
-- local u1 = uuid() ---> __call metamethod
-- local u2 = uuid.generate_v4()
function _M.generate_v4()
local n1 = random(4294967295)
local n2 = random(4294967295)
local n3 = random(4294967295)
local n4 = random(4294967295)

return (fmt('%s%s%s%s-%s%s-%s%s-%s%s-%s%s%s%s%s%s',
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),

tohex(random(0, 255), 2),
tohex(random(0, 255), 2),

tohex(bor(band(random(0, 255), 0x0F), 0x40), 2),
tohex(random(0, 255), 2),

tohex(bor(band(random(0, 255), 0x3F), 0x80), 2),
tohex(random(0, 255), 2),

tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2)))
tohex(band(n1, 0x000000FF), 2),
tohex(rshift(band(n1, 0x0000FF00), 8), 2),
tohex(rshift(band(n1, 0x00FF0000), 16), 2),
tohex(rshift(band(n1, 0xFF000000), 24), 2),

tohex(band(n2, 0x000000FF), 2),
tohex(rshift(band(n2, 0x0000FF00), 8), 2),

tohex(bor(band(rshift(band(n2, 0x00FF0000), 16), 0x0F), 0x40), 2),
tohex(rshift(band(n2, 0xFF000000), 24), 2),

tohex(bor(band(band(n3, 0x000000FF), 0x3F), 0x80), 2),
tohex(rshift(band(n3, 0x0000FF00), 8), 2),

tohex(rshift(band(n3, 0x00FF0000), 16), 2),
tohex(rshift(band(n3, 0xFF000000), 24), 2),
tohex(band(n4, 0x000000FF), 2),
tohex(rshift(band(n4, 0x0000FF00), 8), 2),
tohex(rshift(band(n4, 0x00FF0000), 16), 2),
tohex(rshift(band(n4, 0xFF000000), 24), 2)))
end
end

Expand Down

0 comments on commit 43bc84d

Please sign in to comment.