Created
January 4, 2019 10:49
-
-
Save jsgriffin/45cc822f731a78263802f2b536c98079 to your computer and use it in GitHub Desktop.
Java, UUIDs, Mongo, & Ruby
This file contains 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 'base64' | |
# Adapted from https://github.com/mongodb/mongo-csharp-driver/blob/master/uuidhelpers.js | |
def hexToBase64(hex) | |
base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
base64 = "" | |
for i in (0..29).step(6) | |
group = hex[i..i+5].to_i(base=16) | |
base64 += base64Digits[(group >> 18) & 0x3f] | |
base64 += base64Digits[(group >> 12) & 0x3f] | |
base64 += base64Digits[(group >> 6) & 0x3f] | |
base64 += base64Digits[group & 0x3f] | |
end | |
group = hex[30..31].to_i(base=16) | |
base64 += base64Digits[(group >> 2) & 0x3f] | |
base64 += base64Digits[(group << 4) & 0x3f] | |
return base64 + "==" | |
end | |
def juuid(uuid) | |
hex = uuid.gsub(/[{}-]/, "") | |
msb = hex[0..15] | |
lsb = hex[16..32] | |
msb = msb[14..15] + msb[12..13] + msb[10..11] + msb[8..9] + msb[6..7] + msb[4..5] + msb[2..3] + msb[0..1] | |
lsb = lsb[14..15] + lsb[12..13] + lsb[10..11] + lsb[8..9] + lsb[6..7] + lsb[4..5] + lsb[2..3] + lsb[0..1] | |
hex = msb + lsb | |
base64 = hexToBase64(hex) | |
return BSON::Binary.new Base64.decode64(base64), :uuid_old | |
end | |
# Example: | |
mongo = Mongo::Client.new("mongo://localhost:27017") | |
client[:test].insert_one({ | |
"java-readable-uuid" => juuid("cd48e156-e068-4a4f-becc-f5ea72b0b6c2") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this
"cd48e156-e068-4a4f-becc-f5ea72b0b6c2"
SecureRandom.uuid?