Class: Cql::TimeUuid::Generator
- Inherits:
-
Object
- Object
- Cql::TimeUuid::Generator
- Defined in:
- lib/cql/time_uuid.rb
Overview
A UUID version 1, variant 1 generator. It can generate a sequence of UUIDs with reasonable uniqueness guarantees:
- The clock ID and node ID components are set to random numbers when the generator is created.
- If two calls to #next happen within the time afforded by the system clock resolution a counter is incremented and added to the time component.
- If the clock moves backwards the clock ID is reset to a new random number.
Instances of this class are absolutely not threadsafe. You should never share instances between threads.
Instance Method Summary collapse
-
#from_time(time, jitter = rand(2**16)) ⇒ Cql::TimeUuid
Returns a new UUID with a time component based on the specified Time.
-
#initialize(node_id = nil, clock_id = nil, clock = Time) ⇒ Generator
constructor
Create a new UUID generator.
-
#next ⇒ Cql::TimeUuid
Returns a new UUID with a time component that is the current time.
Constructor Details
#initialize(node_id = nil, clock_id = nil, clock = Time) ⇒ Generator
Create a new UUID generator.
63 64 65 66 67 |
# File 'lib/cql/time_uuid.rb', line 63 def initialize(node_id=nil, clock_id=nil, clock=Time) @node_id = node_id || (rand(2**47) | 0x010000000000) @clock_id = clock_id || rand(2**16) @clock = clock end |
Instance Method Details
#from_time(time, jitter = rand(2**16)) ⇒ Cql::TimeUuid
Returns a new UUID with a time component based on the specified Time. A piece of jitter is added to ensure that multiple calls with the same time do not generate the same UUID (if you want determinism you can set the second parameter to zero).
97 98 99 100 |
# File 'lib/cql/time_uuid.rb', line 97 def from_time(time, jitter=rand(2**16)) usecs = time.to_i * 1_000_000 + time.usec + jitter from_usecs(usecs) end |
#next ⇒ Cql::TimeUuid
Returns a new UUID with a time component that is the current time.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/cql/time_uuid.rb', line 73 def next now = @clock.now usecs = now.to_i * 1_000_000 + now.usec if @last_usecs && @last_usecs - @sequence <= usecs && usecs <= @last_usecs @sequence += 1 elsif @last_usecs && @last_usecs > usecs @sequence = 0 @clock_id = rand(2**16) else @sequence = 0 end @last_usecs = usecs + @sequence from_usecs(@last_usecs) end |