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:
18 files changed
+85
-49
No files matched your search
+10
-2
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user