Skip to content

Commit

Permalink
feat: added a LRU cache for filter string -> compiled SmartFilter object
Browse files Browse the repository at this point in the history
  • Loading branch information
desht committed Dec 1, 2023
1 parent 6f9894f commit b0e478a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package dev.ftb.mods.ftbfiltersystem.util;

import dev.ftb.mods.ftbfiltersystem.api.FilterException;
import dev.ftb.mods.ftbfiltersystem.api.filter.SmartFilter;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;

/**
* An LRU cache to store known filter strings and the SmartFilter objects created from them.
*/
public enum FilterCache {
INSTANCE;

private static final int MAX_SIZE = 1000;
private final Object2ObjectLinkedOpenHashMap<String,SmartFilter> cache = new Object2ObjectLinkedOpenHashMap<>();

public SmartFilter getOrCreateFilter(String filterStr) throws FilterException {
if (cache.containsKey(filterStr)) {
return cache.getAndMoveToFirst(filterStr);
} else {
SmartFilter filter;
try {
filter = FilterParser.parseRaw(filterStr);
} catch (FilterException e) {
filter = null;
}
if (cache.size() >= MAX_SIZE) {
cache.removeLast();
}
cache.put(filterStr, filter);
return filter;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@

public class FilterParser {
public static SmartFilter parse(String str) throws FilterException {
return FilterCache.INSTANCE.getOrCreateFilter(str);
}

static SmartFilter parseRaw(String str) throws FilterException {
RootFilter root = new RootFilter();
root.getChildren().addAll(parseFilterList(root, str));
return root;
Expand Down

0 comments on commit b0e478a

Please sign in to comment.