feat: add getValue & setValue for PatchOption

This commit is contained in:
Sculas 2022-08-02 23:30:38 +02:00
parent 5eb8b428b9
commit 2572cd04b5
No known key found for this signature in database
GPG Key ID: 1530BFF96D1EEB89
2 changed files with 34 additions and 3 deletions

View File

@ -1,11 +1,14 @@
@file:Suppress("CanBeParameter", "MemberVisibilityCanBePrivate")
@file:Suppress("CanBeParameter", "MemberVisibilityCanBePrivate", "UNCHECKED_CAST")
package app.revanced.patcher.patch
import kotlin.reflect.KProperty
class NoSuchOptionException(val option: String) : Exception("No such option: $option")
class IllegalValueException(val value: Any?) : Exception("Illegal value: $value")
class InvalidTypeException(val got: String, val expected: String) :
Exception("Invalid option value type: $got, expected $expected")
class RequirementNotMetException : Exception("null was passed into an option that requires a value")
/**
@ -82,6 +85,24 @@ sealed class PatchOption<T>(
field = value
}
/**
* Gets the value of the option.
* Please note that using the wrong value type results in a runtime error.
*/
operator fun <T> getValue(thisRef: Nothing?, property: KProperty<*>) = value as T
/**
* Gets the value of the option.
* Please note that using the wrong value type results in a runtime error.
*/
inline operator fun <reified V> setValue(thisRef: Any?, property: KProperty<*>, new: V) {
if (value !is V) throw InvalidTypeException(
V::class.java.canonicalName,
value?.let { it::class.java.canonicalName } ?: "null"
)
value = new as T
}
/**
* A [PatchOption] representing a [String].
* @see PatchOption

View File

@ -3,6 +3,7 @@ package app.revanced.patcher.patch
import app.revanced.patcher.usage.bytecode.ExampleBytecodePatch
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertNotEquals
internal class PatchOptionsTest {
private val options = ExampleBytecodePatch().options
@ -31,9 +32,18 @@ internal class PatchOptionsTest {
}
}
}
println(options["key1"].value)
val option = options["key1"]
println(option.value)
options["key1"] = "Hello, world!"
println(options["key1"].value)
println(option.value)
}
@Test
fun `should return a different value when changed`() {
var value: String by options["key1"]
val current = value + "" // force a copy
value = "Hello, world!"
assertNotEquals(current, value)
}
@Test