Module: UUID7::Generator Private

Defined in:
lib/uuid7/generator.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

UUIDv7 with millisecond precision layout

48 bits for unix timestamp with millisecond precision 74 bits for random data

Constant Summary collapse

VERSION_7 =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

0x7000
VARIANT_RFC4122 =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

0x8000

Class Method Summary collapse

Class Method Details

.generate(timestamp) ⇒ Array<Integer>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Instantiates a new layout

Examples:

Generate a new UUID v7 layout for the millisecond

UUID::V7.generate(timestamp)

Parameters:

  • timestamp (Integer)

    the timestamp to use for the layout

Returns:

  • (Array<Integer>)

    the generated UUID v7 layout



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/uuid7/generator.rb', line 22

def self.generate(timestamp)
  unix_ts_ms = timestamp & 0xffffffffffff # take 48 least significant bits of timestamp
  unix_ts_ms1 = (unix_ts_ms >> 16) & 0xffffffff # take 32 most significant bits of timestamp
  unix_ts_ms2 = (unix_ts_ms & 0xffff) # take 16 least significant bits of timestamp

  rand_a, rand_b1, rand_b2, rand_b3 = SecureRandom.gen_random(10).unpack("nnnN")
  rand_a &= 0xfff # take 12 bits of 16
  rand_b1 &= 0x3fff # take 14 bits of 16

  # https://www.ietf.org/id/draft-peabody-dispatch-new-uuid-format-03.txt#section-5.2
  #  0                   1                   2                   3
  #  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  # |                           unix_ts_ms                          |
  # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  # |          unix_ts_ms           |  ver  |       rand_a          |
  # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  # |var|                        rand_b                             |
  # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  # |                            rand_b                             |
  # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

  # layout in bits [32, 16, 16, 16, 16, 32]
  [
    unix_ts_ms1,
    unix_ts_ms2,
    (VERSION_7 | rand_a),
    (VARIANT_RFC4122 | rand_b1),
    rand_b2,
    rand_b3
  ]
end