Module: UUIDv7::MonotonicGenerator

Defined in:
lib/uuidv7/monotonic_generator.rb

Constant Summary collapse

COUNTER_MAX =

12 bits = 4095

0xFFF

Class Method Summary collapse

Class Method Details

.generate(&clock) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/uuidv7/monotonic_generator.rb', line 14

def generate(&clock)
  @mutex.synchronize do
    timestamp = clock ? clock.call : (Time.now.to_f * 1000).to_i
    counter_value = nil

    if timestamp == @last_timestamp
      @counter = (@counter + 1) & COUNTER_MAX

      if @counter.zero?
        loop do
          timestamp = clock ? clock.call : (Time.now.to_f * 1000).to_i
          break if timestamp != @last_timestamp

          sleep(0.0001) unless clock
        end
        @counter = SecureRandom.random_number(COUNTER_MAX + 1)
      end
      counter_value = @counter
    else
      @counter = SecureRandom.random_number(COUNTER_MAX + 1)
      counter_value = @counter
      @last_timestamp = timestamp
    end

    rand_b = SecureRandom.random_number(2**62)
    Generator.build(timestamp, counter_value, rand_b)
  end
end

.generate_compact(&clock) ⇒ Object



43
44
45
# File 'lib/uuidv7/monotonic_generator.rb', line 43

def generate_compact(&clock)
  Base62.encode(generate(&clock))
end

.reset_state! ⇒ Object



47
48
49
50
51
52
# File 'lib/uuidv7/monotonic_generator.rb', line 47

def reset_state!
  @mutex.synchronize do
    @last_timestamp = 0
    @counter = 0
  end
end