Method: Uniqid::ClassMethods#generate

Defined in:
lib/uniqid.rb

#generate(worker_value, server_value, timestamp = nil) ⇒ Object

Generate ID



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/uniqid.rb', line 88

def generate(worker_value, server_value, timestamp = nil)
  server_value = server_value(server_value)
  worker_value = worker_value(worker_value)

  # The reserved position is temporarily random, shifted by 7 bits to the left
  bak_value = (rand(MAX_BAK_NUM) << LOCAL_ID_LEN)

  local_timestamp =
    if timestamp
      (timestamp * 1000).to_i
    else
      (Time.now.to_f * 1000).to_i
    end

  # If the last generation time is the same as the current time, the sequence within milliseconds
  if local_timestamp == @last_timestamp

    # The sequence is self-increasing and only has 7 bits,
    # so it is ANDed with MAX_LOCAL_NUM and removes the high bits
    sequence = (@sequence + 1) & MAX_LOCAL_NUM

    # Check for overflow: whether the sequence exceeds 127 per millisecond,
    # when 127, it is equal to 0 after AND with MAX_LOCAL_NUM
    if sequence.zero?
      # Wait until the next millisecond
      local_timestamp = next_timestamp(@last_timestamp)
    end

  else
    # If it is different from the last generation time, reset the sequence
    # In order to ensure that the mantissa is more random, set a random number in the last digit
    @sequence = rand(1 << LOCAL_ID_LEN)
    sequence = @sequence
  end

  @last_timestamp = local_timestamp

  # Save the difference of timestamp(current timestamp - start timestamp)
  local_timestamp -= TIMESTAMP_START

  (local_timestamp << (TOTAL_LEN - TIMESTAMP_LEN)) | server_value | worker_value | bak_value | sequence
end