Last active
June 24, 2016 10:09
-
-
Save rauhs/b93bcf0d676f0335fd483d7c7c77303d to your computer and use it in GitHub Desktop.
Generate a squuid in nginx (openresty)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Datomic SQUUID layout: | |
-- xxxxxxxx-xxxx-4xxx-Vxxx-xxxxxxxxxxxx | |
-- ^^^^^^^^ ^^^^ ^ | |
-- | | |^^^ ^ | |
-- | | | | |^^^-^^^^^^^^^^^^ | |
-- | | | | | | | |
-- | | | | | |- random | |
-- | | | | |- IETF variant {8,9,a,b} | |
-- | | | |- random | |
-- | | |- Version 4 | |
-- | |- random | |
-- |- ms since epoch rounded to seconds | |
local str = require "resty.string" | |
local random = require "resty.random" | |
ngx.say("-----------------------------------------------------") | |
function squuid(hash) | |
-- elapsed seconds from the epoch | |
local t_epoch = ngx.time() | |
local p1 = bit.tohex(t_epoch, 8) | |
local p2 = string.sub(hash, 9, 12) | |
local p3 = "4" .. string.sub(hash, 14, 16) | |
local variant = "0x" .. string.sub(hash,17,18); | |
variant = bit.band( variant , 0x3f) -- clear variant | |
variant = bit.bor( variant, 0x80) -- set to IETF variant | |
local p4 = bit.tohex(variant,2) .. string.sub(hash, 19, 20) | |
local p5 = string.sub(hash, 21) | |
return p1 .. "-" .. p2 .. "-" .. p3 .. "-" .. p4 .. "-" .. p5 | |
--return p1 .. p2 .. p3 .. p4 .. p5 | |
end | |
-- A random filename for upload before renaming: | |
local rnd_file = str.to_hex( random.bytes(16) ) | |
local md5 = ngx.md5(rnd_file) | |
ngx.say(md5) | |
ngx.say(squuid(md5)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment