Add EventInterface prototype

This commit is contained in:
TheMode 2021-08-14 01:39:45 +02:00
parent e96334e315
commit a075231770
2 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package net.minestom.server.event;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public final class EventInterface<T> {
public static <T> @NotNull Builder<T> builder(@NotNull Class<T> type) {
return new Builder<>();
}
final Map<Class<? extends Event>, BiConsumer<T, Event>> mapped;
EventInterface(Map<Class<? extends Event>, BiConsumer<T, Event>> map) {
this.mapped = map;
}
public static class Builder<T> {
private final Map<Class<? extends Event>, BiConsumer<T, Event>> mapped = new HashMap<>();
@SuppressWarnings("unchecked")
public <E extends Event> Builder<T> map(@NotNull Class<E> eventType,
@NotNull BiConsumer<@NotNull T, @NotNull E> consumer) {
this.mapped.put(eventType, (BiConsumer<T, Event>) consumer);
return this;
}
public @NotNull EventInterface<T> build() {
return new EventInterface<>(Map.copyOf(mapped));
}
}
}

View File

@ -514,6 +514,13 @@ public class EventNode<T extends Event> {
return this;
}
public <I> void addInter(@NotNull EventInterface<I> inter, @NotNull I value) {
inter.mapped.forEach((eventType, consumer) -> {
// TODO cache so listeners can be removed from the EventInterface
addListener((EventListener<? extends T>) EventListener.builder(eventType).handler(event -> consumer.accept(value, event)).build());
});
}
private void increaseChildListenerCount(Class<? extends T> eventClass, int count) {
var entry = listenerMap.computeIfAbsent(eventClass, aClass -> new ListenerEntry<>());
ListenerEntry.addAndGet(entry, count);