Skip to content

Instantly share code, notes, and snippets.

@z64
Last active July 10, 2021 15:41
Show Gist options
  • Save z64/d9b0e832a3791735dc6cf3362c93c4a9 to your computer and use it in GitHub Desktop.
Save z64/d9b0e832a3791735dc6cf3362c93c4a9 to your computer and use it in GitHub Desktop.
# Encode a time into a snowflake with the given worker ID
def snowflake(time, worker)
value = time.epoch_ms << 22
value | worker
end
# Decode a snowflake into a named tuple of its components
def decode(snowflake)
{time: Time.epoch_ms(snowflake >> 22), worker: snowflake & 0b1111}
end
# Construct some snowflakes to compare
time = Time.now
a = snowflake(time, 0b1111)
b = snowflake(time + 1.millisecond, 0b0011)
dist = b - a
# Print results
puts "Time: #{time.inspect}"
puts "Snowflake A #{a}: #{decode(a)}"
puts "Snowflake B #{b}: #{decode(b)}"
puts "B <=> A: #{b <=> a} (distance: #{dist})"
puts
puts "Binary: (. = Time portion, ^ = metadata portion)"
puts "A: #{a.to_s(2).rjust(64, '0')}"
puts "B: #{b.to_s(2).rjust(64, '0')}"
marker = "^".ljust(22, '^').rjust(64, '.')
puts " " + marker
Time: 2018-08-02 14:14:20.085877000 +00:00
Snowflake A 6430787675451555855: {time: 2018-08-02 14:14:20.085000000 UTC, worker: 15_i64}
Snowflake B 6430787675455750147: {time: 2018-08-02 14:14:20.086000000 UTC, worker: 3_i64}
B <=> A: 1 (distance: 4194292)
Binary: (. = Time portion, ^ = metadata portion)
A: 0101100100111110101111110101000110101101010000000000000000001111
B: 0101100100111110101111110101000110101101100000000000000000000011
..........................................^^^^^^^^^^^^^^^^^^^^^^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment