Skip to content

Instantly share code, notes, and snippets.

@jsgriffin jsgriffin/juuid.rb
Created Jan 4, 2019

Embed
What would you like to do?
Java, UUIDs, Mongo, & Ruby
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
You can’t perform that action at this time.