Comparison

util/uuid.lua @ 13317:e6a5f196fc1f

util.uuid: Add UUIDv7 Allows sorting by id as a substitute for sorting by timestamp since it has the timestamp in the encoded in the first part, and only things that happen extremely close together may get out of order by such a sort, which might not matter. From draft-ietf-uuidrev-rfc4122bis formerly draft-peabody-dispatch-new-uuid-format
author Kim Alvefur <zash@zash.se>
date Sun, 15 Aug 2021 14:44:21 +0200
parent 12975:d10957394a3c
comparison
equal deleted inserted replaced
13316:a27a329e93ca 13317:e6a5f196fc1f
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 "prosody.util.random"; 9 local random = require "prosody.util.random";
10 local random_bytes = random.bytes; 10 local random_bytes = random.bytes;
11 local time = require "prosody.util.time";
11 local hex = require "prosody.util.hex".encode; 12 local hex = require "prosody.util.hex".encode;
12 local m_ceil = math.ceil; 13 local m_ceil = math.ceil;
14 local m_floor = math.floor;
13 15
14 local function get_nibbles(n) 16 local function get_nibbles(n)
15 return hex(random_bytes(m_ceil(n/2))):sub(1, n); 17 return hex(random_bytes(m_ceil(n/2))):sub(1, n);
16 end 18 end
17 19
22 local function generate() 24 local function generate()
23 -- generate RFC 4122 complaint UUIDs (version 4 - random) 25 -- generate RFC 4122 complaint UUIDs (version 4 - random)
24 return get_nibbles(8).."-"..get_nibbles(4).."-4"..get_nibbles(3).."-"..(get_twobits())..get_nibbles(3).."-"..get_nibbles(12); 26 return get_nibbles(8).."-"..get_nibbles(4).."-4"..get_nibbles(3).."-"..(get_twobits())..get_nibbles(3).."-"..get_nibbles(12);
25 end 27 end
26 28
29 local function generate_v7()
30 -- Sortable based on time and random
31 -- https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-01#section-4.4
32 local t = time.now();
33 local unixts = m_floor(t);
34 local unixts_a = m_floor(unixts / 16);
35 local unixts_b = m_floor(unixts % 16);
36 local subsec = t % 1;
37 local subsec_a = m_floor(subsec * 0x1000);
38 local subsec_b = m_floor(subsec * 0x1000000) % 0x1000;
39 return ("%08x-%x%03x-7%03x-%4s-%12s"):format(unixts_a, unixts_b, subsec_a, subsec_b, get_twobits() .. get_nibbles(3), get_nibbles(12));
40 end
41
27 return { 42 return {
43 v4 = generate;
44 v7 = generate_v7;
28 get_nibbles=get_nibbles; 45 get_nibbles=get_nibbles;
29 generate = generate ; 46 generate = generate ;
30 -- COMPAT 47 -- COMPAT
31 seed = random.seed; 48 seed = random.seed;
32 }; 49 };