util.uuid: Now generates RFC 4122 complaint UUIDs (version 4 - random)
[prosody.git] / util / uuid.lua
1 -- Prosody IM v0.4
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
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;
15
16 module "uuid"
17
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;
23         return new_uniq_time;
24 end
25
26 local function new_random(x)
27         return sha1(x..os_clock()..tostring({}), true);
28 end
29
30 local buffer = new_random(uniq_time());
31 local function get_nibbles(n)
32         if #buffer < n then
33                 buffer = new_random(buffer..uniq_time());
34         end
35         local r = buffer:sub(0, n);
36         buffer = buffer:sub(n+1);
37         return r;
38 end
39 local function get_twobits()
40         return ("%x"):format(get_nibbles(1):byte() % 4 + 8);
41 end
42
43 function generate()
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);
46 end
47
48 return _M;