module TwitterSnowflake

TwitterSnowflake is a library to parse snowflake IDs.

Constants

INCREMENT_MASK

Mask to extract increment.

PROCESS_ID_BINARY_OFFSET

Process ID offset (low-order bit of the process ID collection)

PROCESS_ID_MASK

Mask to extract process ID.

TIMESTAMP_BINARY_OFFSET

Timestamp offset (low-order bit of the timestamp collection)

TWITTER_EPOCH

Twitter's epoch in milliseconds. Used as default epoch to parse IDs.

VERSION
WORKER_ID_BINARY_OFFSET

Worker ID offset (low-order bit of the worker ID collection)

WORKER_ID_MASK

Mask to extract worker ID.

Public Class Methods

increment(id) click to toggle source

Extracts the increment from a snowflake ID.

@param id [Integer] the snowflake ID.

@return [Integer] the increment.

# File lib/twitter_snowflake.rb, line 88
def increment(id)
  id & INCREMENT_MASK
end
parse(id, epoch: TWITTER_EPOCH) click to toggle source

Parses a snowflake ID.

@param id [Integer] the snowflake ID. @param epoch [Integer] base epoch in milliseconds to perform calculations.

@return [Snowflake] a snowflake object.

# File lib/twitter_snowflake.rb, line 51
def parse(id, epoch: TWITTER_EPOCH)
  Snowflake.new(id: id, epoch: epoch)
end
process_id(id) click to toggle source

Extracts the process ID from a snowflake ID.

@param id [Integer] the snowflake ID.

@return [Integer] the process ID.

# File lib/twitter_snowflake.rb, line 79
def process_id(id)
  (id & PROCESS_ID_MASK) >> PROCESS_ID_BINARY_OFFSET
end
synthesize(timestamp:, worker_id: 0, process_id: 0, increment: 0, epoch: TWITTER_EPOCH) click to toggle source

Creates a snowflake object for any given timestamp, worker ID, process ID and increment.

@param epoch [Integer] base epoch in milliseconds to perform calculations. @param timestamp [Integer] the timestamp in milliseconds.

@return [Snowflake] the generated snowflake.

# File lib/twitter_snowflake.rb, line 36
def synthesize(timestamp:, worker_id: 0, process_id: 0, increment: 0, epoch: TWITTER_EPOCH)
  id  = (timestamp - epoch) << TIMESTAMP_BINARY_OFFSET
  id += (worker_id << WORKER_ID_BINARY_OFFSET)
  id += (process_id << PROCESS_ID_BINARY_OFFSET)
  id += increment

  Snowflake.new(id: id, epoch: epoch)
end
timestamp(id, epoch: TWITTER_EPOCH) click to toggle source

Extracts the timestamp from a snowflake ID.

@param id [Integer] the snowflake ID. @param epoch [Integer] base epoch in milliseconds to perform calculations.

@return [Integer] the timestamp in milliseconds.

# File lib/twitter_snowflake.rb, line 61
def timestamp(id, epoch: TWITTER_EPOCH)
  (id >> TIMESTAMP_BINARY_OFFSET) + epoch
end
worker_id(id) click to toggle source

Extracts the worker ID from a snowflake ID.

@param id [Integer] the snowflake ID.

@return [Integer] the worker ID.

# File lib/twitter_snowflake.rb, line 70
def worker_id(id)
  (id & WORKER_ID_MASK) >> WORKER_ID_BINARY_OFFSET
end