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 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 _seed(x)
32
	buffer = new_random(buffer..x);
33
end
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);
38
	return r;
39
end
40
local function get_twobits()
41
	return ("%x"):format(get_nibbles(1):byte() % 4 + 8);
42
end
43
 
44
function generate()
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);
47
end
48
seed = _seed;
49
 
50
return _M;