Skip to content

Instantly share code, notes, and snippets.

@ebisawa
Last active September 26, 2015 07:57
Show Gist options
  • Save ebisawa/1064660 to your computer and use it in GitHub Desktop.
Save ebisawa/1064660 to your computer and use it in GitHub Desktop.
UUID
class UUID
def initialize
@timestamp = timestamp
@clockseq = clockseq
@node = node
end
def to_s
t = @timestamp
sprintf("%08x-%04x-%04x-%04x-%012x", t[0], t[1], t[2] | version, @clockseq | variant, @node)
end
def timestamp
# 60-bit value
now = Time.now
usec = (now.tv_sec * 1000 * 1000) + now.tv_usec
hsec = usec * 10 # 100-nanosecond intervals
time_low = hsec & 0x0000000ffffffff
time_mid = (hsec & 0x000ffff00000000) >> 32
time_hi = (hsec & 0xfff000000000000) >> 48
[ time_low, time_mid, time_hi ]
end
def version
0b0001 << 12
end
def clockseq
# 14-bit value
rand(0x10000) & ~0xc0000
end
def variant
0x8000
end
def node
rand(0x1000000000000) | 0x010000000000
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment