diff --git a/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt b/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt index 83a50833..b14c93f8 100644 --- a/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt +++ b/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt @@ -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( field = value } + /** + * Gets the value of the option. + * Please note that using the wrong value type results in a runtime error. + */ + operator fun 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 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 diff --git a/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt b/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt index 10534303..c7d20399 100644 --- a/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt +++ b/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt @@ -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