Mercurial > prosody-hg
comparison util/random.lua @ 6376:bd812a7713ad
util.random: Generic util lib for generating strings of random bytes
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Tue, 02 Sep 2014 17:57:18 +0100 |
| parents | |
| children | 0c070e30a7db |
comparison
equal
deleted
inserted
replaced
| 6375:76d8907d5301 | 6376:bd812a7713ad |
|---|---|
| 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 sha1 = require "util.hashes".sha1; | |
| 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 sha1(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 then seed(uniq_time()); end | |
| 35 local r = buffer:sub(0, n); | |
| 36 buffer = buffer:sub(n+1); | |
| 37 return r; | |
| 38 end | |
| 39 | |
| 40 return { | |
| 41 seed = seed; | |
| 42 bytes = bytes; | |
| 43 }; |
