Skip to content

Instantly share code, notes, and snippets.

@michbarsinai
Created November 9, 2021 21:04
Show Gist options
  • Save michbarsinai/696e46f5745835e26bc6c462625d97fb to your computer and use it in GitHub Desktop.
Save michbarsinai/696e46f5745835e26bc6c462625d97fb to your computer and use it in GitHub Desktop.
Present a 64-bit long Int in a URI-safe Base 64 encoding, in scala
/*
Usage:
> UriBase64Long(1234567891011L).mkString
val res41: String = dqTp5Kaa
> Range(0,8).map(_=>Random.nextLong()).flatMap(UriBase64Long(_)).mkString
val res42: String = 6MO_7T1drnVveBdcHYG08PcCDyx5QlyU@~T8UpTr6Go02cjd7@IJBYSHk0EttfhS
*/
class UriBase64Long(start:Long) extends Iterator[Char] {
import UriBase64Long._
var remainder = start
var nextsLeft = UriBase64Long.itrCount
override def hasNext = (nextsLeft!=0)
override def next():Char = {
val thisChar = remainder & UriBase64Long.bitMask
remainder = remainder >>> 7
nextsLeft = nextsLeft - 1;
UriBase64Long.dict(thisChar.toInt)
}
}
object UriBase64Long {
val dict = Seq( 'a'->'z', 'A'->'Z', '0'->'9').flatMap( p => Range(p._1, p._2) ).map(_.toChar).mkString + "-~_@$"
val dictSize = dict.size
private val bitMask = 63 // 7 bits
private val itrCount = 64/8 // Long is a 64-bit integer
def apply( aLong:Long ) = new UriBase64Long(aLong)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment