Class: Philiprehberger::IdGen::Snowflake::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/id_gen/snowflake.rb

Instance Method Summary collapse

Constructor Details

#initialize(worker_id: 0, epoch: nil) ⇒ Generator

Returns a new instance of Generator.

Raises:



19
20
21
22
23
24
25
26
27
# File 'lib/philiprehberger/id_gen/snowflake.rb', line 19

def initialize(worker_id: 0, epoch: nil)
  raise Error, "Worker ID must be between 0 and #{MAX_WORKER_ID}" unless worker_id.between?(0, MAX_WORKER_ID)

  @worker_id = worker_id
  @epoch_ms = epoch ? (epoch.to_f * 1000).to_i : CUSTOM_EPOCH
  @sequence = 0
  @last_timestamp = -1
  @mutex = Mutex.new
end

Instance Method Details

#generateObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/philiprehberger/id_gen/snowflake.rb', line 29

def generate
  @mutex.synchronize do
    timestamp_ms = current_timestamp

    if timestamp_ms == @last_timestamp
      @sequence = (@sequence + 1) & MAX_SEQUENCE
      timestamp_ms = wait_next_millis(@last_timestamp) if @sequence.zero?
    else
      @sequence = 0
    end

    @last_timestamp = timestamp_ms

    (timestamp_ms << TIMESTAMP_SHIFT) |
      (@worker_id << WORKER_ID_SHIFT) |
      @sequence
  end
end