Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Bytes: add hashCode and better toString #86

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions geny/src/geny/Bytes.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package geny

import java.math.BigInteger
import java.nio.ByteBuffer
import java.nio.charset.{CodingErrorAction, StandardCharsets}

/**
* Trivial wrapper around `Array[Byte]` with sane equality and useful toString
*/
Expand All @@ -8,5 +12,15 @@ class Bytes(val array: Array[Byte]){
case otherBytes: Bytes => java.util.Arrays.equals(array, otherBytes.array)
case _ => false
}
override def toString = new String(array, java.nio.charset.StandardCharsets.UTF_8)
}

override def hashCode(): Int = java.util.Arrays.hashCode(array)

override def toString = try {
StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(array))
.toString
} catch (_ => s"0x${new BigInteger(1, array).toString(16).toUpperCase}")
}