CommonCore/src/de/steamwar/command/TabCompletionCache.java

66 Zeilen
2.7 KiB
Java

2022-06-20 13:16:13 +02:00
package de.steamwar.command;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.UtilityClass;
import java.util.*;
import java.util.function.Supplier;
@UtilityClass
public class TabCompletionCache {
private Map<Key, TabCompletions> tabCompletionCache = new HashMap<>();
Set<AbstractTypeMapper<?, ?>> cached = new HashSet<>();
Set<AbstractTypeMapper<?, ?>> global = new HashSet<>();
Map<AbstractTypeMapper<?, ?>, Long> cacheDuration = new HashMap<>();
2022-06-20 19:35:02 +02:00
void add(AbstractTypeMapper<?, ?> typeMapper, AbstractSWCommand.Cached cached) {
if (cached != null) {
TabCompletionCache.cached.add(typeMapper);
if (cached.global()) TabCompletionCache.global.add(typeMapper);
TabCompletionCache.cacheDuration.put(typeMapper, cached.timeUnit().toMillis(cached.cacheDuration()));
}
}
2022-06-20 13:16:13 +02:00
@EqualsAndHashCode
@AllArgsConstructor
private static class Key {
private Object sender;
private AbstractTypeMapper<?, ?> typeMapper;
}
@AllArgsConstructor
private static class TabCompletions {
private AbstractSWCommand<?> command;
private long timestamp;
private Collection<String> tabCompletions;
}
Collection<String> tabComplete(Object sender, AbstractTypeMapper<?, ?> typeMapper, AbstractSWCommand<?> command, Supplier<Collection<String>> tabCompleteSupplier) {
if (!cached.contains(typeMapper)) return tabCompleteSupplier.get();
Key key = global.contains(typeMapper) ? new Key(null, typeMapper) : new Key(sender, typeMapper);
TabCompletions tabCompletions = tabCompletionCache.computeIfAbsent(key, ignore -> {
return new TabCompletions(command, System.currentTimeMillis(), tabCompleteSupplier.get());
});
2022-06-20 13:26:33 +02:00
if (tabCompletions.command != command || System.currentTimeMillis() - tabCompletions.timestamp > cacheDuration.get(typeMapper)) {
2022-06-20 13:16:13 +02:00
tabCompletions = new TabCompletions(command, System.currentTimeMillis(), tabCompleteSupplier.get());
tabCompletionCache.put(key, tabCompletions);
}
tabCompletions.timestamp = System.currentTimeMillis();
return tabCompletions.tabCompletions;
}
public void invalidateOldEntries() {
Set<Key> toRemove = new HashSet<>();
for (Map.Entry<Key, TabCompletions> tabCompletionsEntry : tabCompletionCache.entrySet()) {
if (System.currentTimeMillis() - tabCompletionsEntry.getValue().timestamp > cacheDuration.get(tabCompletionsEntry.getKey().typeMapper)) {
toRemove.add(tabCompletionsEntry.getKey());
}
}
for (Key key : toRemove) {
tabCompletionCache.remove(key);
}
}
}