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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

World's smallest micro-optimization #2318

Open
wants to merge 1 commit into
base: series/2.x
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
23 changes: 17 additions & 6 deletions core/src/main/scala/caliban/wrappers/ApolloPersistedQueries.scala
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,26 @@ object ApolloPersistedQueries {
case _ => None
}

private def hex(bytes: Array[Byte]): String = {
val builder = new mutable.StringBuilder(bytes.length * 2)
bytes.foreach(byte => builder.append(f"$byte%02x".toLowerCase))
builder.mkString
}
private val HexArray: Array[Char] = "0123456789abcdef".toCharArray

private def checkHash(hash: String, query: String): Boolean = {
val sha256 = java.security.MessageDigest.getInstance("SHA-256")
val digest = sha256.digest(query.getBytes(StandardCharsets.UTF_8))
hex(digest) == hash
digestMatchesHash(digest, hash)
}

private def digestMatchesHash(digest: Array[Byte], hash: String): Boolean = {
val chars = hash.toCharArray
val size = digest.length
var j = 0
var res = chars.length == size * 2
while (j < size && res) {
val v = digest(j) & 0xff
if (chars(j * 2) == HexArray(v >>> 4) && chars(j * 2 + 1) == HexArray(v & 0xf)) ()
else res = false
j += 1
}
res
}

}