Skip to content

Commit 772b800

Browse files
authored
Merge pull request #721 from pylonmc/balugaq/config-adapter-primitive-fix
fix primitives checks
2 parents e482496 + e3549aa commit 772b800

1 file changed

Lines changed: 24 additions & 6 deletions

File tree

rebar/src/main/kotlin/io/github/pylonmc/rebar/config/adapter/ConfigAdapter.kt

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,13 @@ interface ConfigAdapter<T> {
2828
@Suppress("unused")
2929
companion object {
3030
// @formatter:off
31-
@JvmField val BYTE = ConfigAdapter { if (it is String) it.toByte() else (it as Number).toByte() }
32-
@JvmField val SHORT = ConfigAdapter { if (it is String) it.toShort() else (it as Number).toShort() }
33-
@JvmField val INTEGER = ConfigAdapter { if (it is String) it.toInt() else (it as Number).toInt() }
31+
@JvmField val BYTE = numberAdapter(Byte.MIN_VALUE, Byte.MAX_VALUE, Number::toByte)
32+
@JvmField val SHORT = numberAdapter(Short.MIN_VALUE, Short.MAX_VALUE, Number::toShort)
33+
@JvmField val INTEGER = numberAdapter(Int.MIN_VALUE, Int.MAX_VALUE, Number::toInt)
34+
@JvmField val LONG = numberAdapter(Long.MIN_VALUE, Long.MAX_VALUE, Number::toLong)
35+
@JvmField val FLOAT = numberAdapter(Float.MIN_VALUE, Float.MAX_VALUE, Number::toFloat)
36+
@JvmField val DOUBLE = numberAdapter(Double.MIN_VALUE, Double.MAX_VALUE, Number::toDouble)
3437
@JvmField val INT_RANGE = IntRangeAdapter
35-
@JvmField val LONG = ConfigAdapter { if (it is String) it.toLong() else (it as Number).toLong() }
36-
@JvmField val FLOAT = ConfigAdapter { if (it is String) it.toFloat() else (it as Number).toFloat() }
37-
@JvmField val DOUBLE = ConfigAdapter { if (it is String) it.toDouble() else (it as Number).toDouble() }
3838
@JvmField val CHAR = ConfigAdapter { (it as String).single() }
3939
@JvmField val BOOLEAN = ConfigAdapter { it as Boolean }
4040
@JvmField val ANY = ConfigAdapter { it }
@@ -141,6 +141,24 @@ interface ConfigAdapter<T> {
141141
@JvmField val CONTRIBUTOR = ContributorConfigAdapter
142142
@JvmField val TEXT_COLOR = TextColorConfigAdapter
143143
// @formatter:on
144+
145+
private inline fun <reified T : Number> numberAdapter(
146+
min: T,
147+
max: T,
148+
crossinline toType: Number.() -> T
149+
): ConfigAdapter<T> = ConfigAdapter { value ->
150+
if (value is String) return@ConfigAdapter value.toDouble().toType()
151+
152+
check (value is Number) { "Expected ${Number::class.java}, got ${value::class.java}" }
153+
if (value is Float || value is Double) {
154+
check(min is Float || min is Double) { "Expected ${T::class.java.canonicalName}, got ${value::class.java.canonicalName}" }
155+
}
156+
157+
if (min !is Double) {
158+
check(value.toDouble() in (min.toDouble())..(max.toDouble())) { "Expected value between $min and $max, got $value" }
159+
}
160+
return@ConfigAdapter value.toDouble().toType()
161+
}
144162
}
145163
}
146164

0 commit comments

Comments
 (0)