Skip to content

Commit

Permalink
feat: add getValue & setValue for PatchOption
Browse files Browse the repository at this point in the history
  • Loading branch information
Sculas committed Aug 2, 2022
1 parent 5eb8b42 commit 2572cd0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
23 changes: 22 additions & 1 deletion 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")

/**
Expand Down Expand Up @@ -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
Expand Down
14 changes: 12 additions & 2 deletions src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 2572cd0

Please sign in to comment.