Use single shared method for return code checking.

This defers the return code logic to a named method `isLibsodiumSuccessCode`
to reduce the liklihood of error when checking codes.
This will also now throw an `IllegalStateException` in the event that an
unknown code is returned.
This commit is contained in:
Renee Vandervelde committed 2024-07-02 11:00:22 -05:00
1 parent c9c5f320af
commit c2b91c2c69
18 files changed
+85 -49

No files matched your search

@@ -1,11 +1,19 @@
package com.ionspin.kotlin.crypto
import com.ionspin.kotlin.crypto.util.isLibsodiumSuccessCode
class GeneralLibsodiumException : RuntimeException("Libsodium reported error! Returned value was -1") {
companion object {
/**
* Throws a [GeneralLibsodiumException] if the return code is not
* successful.
*
* This will throw an [IllegalStateException] if the return code is invalid/unknown.
*/
fun Int.ensureLibsodiumSuccess() {
if (this == -1) {
if (!isLibsodiumSuccessCode()) {
throw GeneralLibsodiumException()
}
}
}
}
}
@@ -36,3 +36,16 @@ fun UByteArray.hexColumnsPrint(chunk: Int = 16) {
val printout = this.map { it.toString(16).padStart(2, '0') }.chunked(chunk)
printout.forEach { println(it.joinToString(separator = " ") { it.uppercase() }) }
}
/**
* Functions returning an int return 0 on success and -1 to indicate an error.
*
* This will throw an [IllegalStateException] if the return code is invalid/unknown.
*/
fun Int.isLibsodiumSuccessCode(): Boolean {
return when (this) {
0 -> true
-1 -> false
else -> throw IllegalStateException("Libsodium returned an unexpected return code $this")
}
}