Last active
May 25, 2024 10:20
-
-
Save dacr/1cfdaf4c1f6d0237cf4340735b44b119 to your computer and use it in GitHub Desktop.
encode/decode base64 based UUID / published by https://github.com/dacr/code-examples-manager #6e71ffd1-d711-4321-8768-01690f226600/2e1fde155ce2e0b70503935707b991a680a67d34
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
// summary : encode/decode base64 based UUID | |
// keywords : base64, encode, decode, uuid, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 6e71ffd1-d711-4321-8768-01690f226600 | |
// created-on : 2021-07-21T08:58:08+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "org.scalatest::scalatest:3.2.10" | |
//> using dep "commons-codec:commons-codec:1.15" | |
// --------------------- | |
import org.scalatest._ | |
import flatspec._ | |
import matchers._ | |
import org.apache.commons.codec.binary.Base64 | |
import java.nio.ByteBuffer | |
import java.util.UUID | |
def toBase64UUID(uuid:UUID):String = { | |
val base64 = new Base64() | |
val bb = ByteBuffer.wrap(Array.ofDim[Byte](16)) | |
bb.putLong(uuid.getMostSignificantBits()) | |
bb.putLong(uuid.getLeastSignificantBits()) | |
base64.encodeToString(bb.array()) | |
} | |
def fromBase64UUID(b64uuid:String):UUID = { | |
val base64 = new Base64() | |
val bytes = base64.decode(b64uuid) | |
val bb = ByteBuffer.wrap(bytes) | |
new UUID(bb.getLong(), bb.getLong()) | |
} | |
def generateBase64UUID():String = { | |
toBase64UUID(UUID.randomUUID()) | |
} | |
object Base64EncodeDecodeTest extends AnyFlatSpec with should.Matchers { | |
override def suiteName="Base64EncodeDecodeTest" | |
"Base64 uuid" can "generated" in { | |
val b64uuid = generateBase64UUID() | |
info(s"generated b64 UUID $b64uuid") | |
fromBase64UUID(b64uuid) | |
} | |
it can "be encoded and decoded" in { | |
val uuid = UUID.randomUUID() | |
val encoded = toBase64UUID(uuid) | |
val decoded = fromBase64UUID(encoded) | |
info(s"generated b64 UUID $encoded for $uuid") | |
decoded shouldBe uuid | |
} | |
} | |
Base64EncodeDecodeTest.execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment