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
|