Software / code / prosody
Comparison
util/uuid.lua @ 6377:50e5aed4eeea
util.uuid: Use util.hex and util.random
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Tue, 02 Sep 2014 17:58:12 +0100 |
| parent | 5776:bd0ff8ae98a8 |
| child | 7012:990b4ddaf582 |
comparison
equal
deleted
inserted
replaced
| 6376:bd812a7713ad | 6377:50e5aed4eeea |
|---|---|
| 4 -- | 4 -- |
| 5 -- This project is MIT/X11 licensed. Please see the | 5 -- This project is MIT/X11 licensed. Please see the |
| 6 -- COPYING file in the source package for more information. | 6 -- COPYING file in the source package for more information. |
| 7 -- | 7 -- |
| 8 | 8 |
| 9 local random = require "util.random"; | |
| 10 local random_bytes = random.bytes; | |
| 11 local hex = require "util.hex".to; | |
| 12 local m_ceil = math.ceil; | |
| 9 | 13 |
| 10 local m_random = math.random; | 14 local function get_nibbles(n) |
| 11 local tostring = tostring; | 15 return hex(random_bytes(m_ceil(n/2))):sub(1, n); |
| 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 | 16 end |
| 25 | 17 |
| 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() | 18 local function get_twobits() |
| 41 return ("%x"):format(get_nibbles(1):byte() % 4 + 8); | 19 return ("%x"):format(get_nibbles(1):byte() % 4 + 8); |
| 42 end | 20 end |
| 43 | 21 |
| 44 function generate() | 22 local function generate() |
| 45 -- generate RFC 4122 complaint UUIDs (version 4 - random) | 23 -- 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); | 24 return get_nibbles(8).."-"..get_nibbles(4).."-4"..get_nibbles(3).."-"..(get_twobits())..get_nibbles(3).."-"..get_nibbles(12); |
| 47 end | 25 end |
| 48 seed = _seed; | |
| 49 | 26 |
| 50 return _M; | 27 return { |
| 28 get_nibbles=get_nibbles; | |
| 29 generate = generate ; | |
| 30 -- COMPAT | |
| 31 seed = random.seed; | |
| 32 }; |