util.uuid: Remove unused import
[prosody.git] / util / uuid.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 tostring = tostring;
11 local os_time = os.time;
12 local os_clock = os.clock;
13 local sha1 = require "util.hashes".sha1;
14
15 module "uuid"
16
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;
22         return new_uniq_time;
23 end
24
25 local function new_random(x)
26         return sha1(x..os_clock()..tostring({}), true);
27 end
28
29 local buffer = new_random(uniq_time());
30 local function _seed(x)
31         buffer = new_random(buffer..x);
32 end
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);
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 seed = _seed;
48
49 return _M;