diff --git a/eco-core/core-plugin/build.gradle b/eco-core/core-plugin/build.gradle index f8d64013..6a6b84bd 100644 --- a/eco-core/core-plugin/build.gradle +++ b/eco-core/core-plugin/build.gradle @@ -2,7 +2,7 @@ group 'com.willfp' version rootProject.version dependencies { - implementation 'com.github.Redempt:Crunch:1.0' + implementation 'com.github.Redempt:Crunch:1.1.2' compileOnly 'net.kyori:adventure-platform-bukkit:4.1.0' compileOnly 'org.apache.maven:maven-artifact:3.8.1' compileOnly 'com.google.code.gson:gson:2.8.8' diff --git a/eco-core/core-plugin/src/main/kotlin/com/willfp/eco/internal/spigot/math/CrunchHandler.kt b/eco-core/core-plugin/src/main/kotlin/com/willfp/eco/internal/spigot/math/CrunchHandler.kt index c96919c1..d7fc0b45 100644 --- a/eco-core/core-plugin/src/main/kotlin/com/willfp/eco/internal/spigot/math/CrunchHandler.kt +++ b/eco-core/core-plugin/src/main/kotlin/com/willfp/eco/internal/spigot/math/CrunchHandler.kt @@ -1,5 +1,7 @@ package com.willfp.eco.internal.spigot.math +import com.github.benmanes.caffeine.cache.Cache +import com.github.benmanes.caffeine.cache.Caffeine import com.willfp.eco.core.integrations.placeholder.PlaceholderManager import org.bukkit.entity.Player import redempt.crunch.CompiledExpression @@ -7,32 +9,21 @@ import redempt.crunch.Crunch import redempt.crunch.data.FastNumberParsing import redempt.crunch.functional.EvaluationEnvironment -private val cache = mutableMapOf() +private val cache: Cache = Caffeine.newBuilder().build() private val goToZero = Crunch.compileExpression("0") fun evaluateExpression(expression: String, player: Player?): Double { val placeholderValues = PlaceholderManager.findPlaceholdersIn(expression) - .map { PlaceholderManager.translatePlaceholders(expression, player) } + .map { PlaceholderManager.translatePlaceholders(it, player) } .map { runCatching { FastNumberParsing.parseDouble(it) }.getOrDefault(0.0) } .toDoubleArray() - val compiled = generateExpression(expression) - return runCatching { compiled.evaluate(*placeholderValues) }.getOrDefault(0.0) -} - -private fun generateExpression(expression: String): CompiledExpression { - val cached = cache[expression] - - if (cached != null) { - return cached + val compiled = cache.get(expression) { + val placeholders = PlaceholderManager.findPlaceholdersIn(it) + val env = EvaluationEnvironment() + env.setVariableNames(*placeholders.toTypedArray()) + runCatching { Crunch.compileExpression(expression, env) }.getOrDefault(goToZero) } - val placeholders = PlaceholderManager.findPlaceholdersIn(expression) - - val env = EvaluationEnvironment() - env.setVariableNames(*placeholders.toTypedArray()) - - val compiled = runCatching { Crunch.compileExpression(expression, env) }.getOrDefault(goToZero) - cache[expression] = compiled - return compiled + return runCatching { compiled.evaluate(*placeholderValues) }.getOrDefault(0.0) }