Skip to content

Instantly share code, notes, and snippets.

@goldobin
Last active November 6, 2017 08:06
Show Gist options
  • Save goldobin/373e423a33cfbf47c1c1 to your computer and use it in GitHub Desktop.
Save goldobin/373e423a33cfbf47c1c1 to your computer and use it in GitHub Desktop.
Converters for UUID and String to ByteString for Scala
object ByteStringConverters {
implicit val DefaultByteOrder = ByteOrder.BIG_ENDIAN
implicit class UUIDWithToByteString(uuid: UUID) {
def toByteString = ByteString(
ByteBuffer
.allocate(16)
.putLong(uuid.getMostSignificantBits)
.putLong(8, uuid.getLeastSignificantBits)
)
}
implicit class StringWithToByteString(s: String) {
def toByteString = ByteString(s.getBytes("UTF-8"))
}
implicit class ByteWithToByteString(x: Byte) {
def toByteString = ByteString(x)
}
implicit class ShortWithToByteString(x: Short) {
def toByteString = new ByteStringBuilder().putShort(x).result()
}
implicit class IntWithToByteString(x: Int) {
def toByteString = new ByteStringBuilder().putInt(x).result()
}
implicit class ByteStringWithToBasicTypes(bytes: ByteString) {
def toShort: Short = {
require (bytes.length == 2)
(((bytes(0) & 0xFF) << 8) | (bytes(1) & 0xFF)).asInstanceOf[Short]
}
def toInt: Int = {
require(bytes.length == 4)
((bytes(0) & 0xFF) << 24) |
((bytes(1) & 0xFF) << 16) |
((bytes(2) & 0xFF) << 8) |
(bytes(3) & 0xFF)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment