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