2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local tostring = tostring;
11 local os_time = os.time;
12 local os_clock = os.clock;
13 local sha1 = require "util.hashes".sha1;
17 local last_uniq_time = 0;
18 local function uniq_time()
19 local new_uniq_time = os_time();
20 if last_uniq_time >= new_uniq_time then new_uniq_time = last_uniq_time + 1; end
21 last_uniq_time = new_uniq_time;
25 local function new_random(x)
26 return sha1(x..os_clock()..tostring({}), true);
29 local buffer = new_random(uniq_time());
30 local function _seed(x)
31 buffer = new_random(buffer..x);
33 local function get_nibbles(n)
34 if #buffer < n then _seed(uniq_time()); end
35 local r = buffer:sub(0, n);
36 buffer = buffer:sub(n+1);
39 local function get_twobits()
40 return ("%x"):format(get_nibbles(1):byte() % 4 + 8);
44 -- generate RFC 4122 complaint UUIDs (version 4 - random)
45 return get_nibbles(8).."-"..get_nibbles(4).."-4"..get_nibbles(3).."-"..(get_twobits())..get_nibbles(3).."-"..get_nibbles(12);