Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/1cfdaf4c1f6d0237cf4340735b44b119 to your computer and use it in GitHub Desktop.
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/180d02629c7e6cb404de4ba17401f0b320b1a3e1
// 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.1.1"
//> 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