Last active
June 5, 2020 00:09
-
-
Save bjeanes/e75120fd6c44a3040a033a3dee0f8d00 to your computer and use it in GitHub Desktop.
Compact URL-safe UUID representation. It might almost be worth having a base66 version (there are 66 url-safe chars)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
require 'base64' | |
module UUID64 | |
extend self | |
def generate | |
encode SecureRandom.uuid | |
end | |
def encode(uuid) | |
bytes = uuid.downcase.scan(/[0-9a-f]{4}/).map { |x| x.to_i(16) } | |
Base64.urlsafe_encode64(bytes.pack('n*')).delete('=') | |
end | |
def decode(string) | |
string = string.gsub(/(==)?$/, '==') # re-pad, if necessary | |
bytes = Base64.urlsafe_decode64(string).unpack('NnnnnN') | |
"%08x-%04x-%04x-%04x-%04x%08x" % bytes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
e.g.