util.random: Ensure at least 4 bytes of previous random state is used when generating...
[prosody.git] / util / random.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2014 Matthew Wild
3 -- Copyright (C) 2008-2014 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 local tostring = tostring;
10 local os_time = os.time;
11 local os_clock = os.clock;
12 local ceil = math.ceil;
13 local H = require "util.hashes".sha512;
14
15 local last_uniq_time = 0;
16 local function uniq_time()
17         local new_uniq_time = os_time();
18         if last_uniq_time >= new_uniq_time then new_uniq_time = last_uniq_time + 1; end
19         last_uniq_time = new_uniq_time;
20         return new_uniq_time;
21 end
22
23 local function new_random(x)
24         return H(x..os_clock()..tostring({}));
25 end
26
27 local buffer = new_random(uniq_time());
28
29 local function seed(x)
30         buffer = new_random(buffer..x);
31 end
32
33 local function bytes(n)
34         if #buffer < n+4 then seed(uniq_time()); end
35         local r = buffer:sub(1, n);
36         buffer = buffer:sub(n+1);
37         return r;
38 end
39
40 return {
41         seed = seed;
42         bytes = bytes;
43 };