Skip to content

Commit

Permalink
Improve performance for DistType conversion [skip deploy]
Browse files Browse the repository at this point in the history
Signed-off-by: TheSilkMiner <thesilkminer@outlook.com>
  • Loading branch information
TheSilkMiner committed Oct 27, 2022
1 parent d113c8e commit c32ce68
Showing 1 changed file with 27 additions and 16 deletions.
@@ -1,15 +1,13 @@
package com.blamejared.crafttweaker.platform.sides;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public enum DistributionType {
CLIENT(Set.of("client")), SERVER(Set.of("server", "dedicated_server"));

private static final Map<Enum<?>, DistributionType> CACHE = new HashMap<>();
private static final DistributionType[] VALUES = DistributionType.values();
private static final DistributionType[] CACHE = new DistributionType[VALUES.length];

private final Set<String> names;

Expand All @@ -18,6 +16,30 @@ public enum DistributionType {
this.names = names;
}

public static DistributionType from(final Enum<?> other) {

final int ordinal = other.ordinal();
final DistributionType cached = CACHE[ordinal];
if(cached != null) {
return cached;
}

final String name = other.name();
DistributionType target = null;
for(final DistributionType type : VALUES) {
if(type.matches(name)) {
CACHE[ordinal] = target = type;
break;
}
}

if(target == null) {
throw new IllegalArgumentException("Cannot create DistributionType from provided enum " + other + " of class " + other.getClass());
}

return target;
}

public boolean isServer() {

return this == SERVER;
Expand All @@ -35,17 +57,6 @@ public Set<String> getNames() {

public boolean matches(String name) {

return this.getNames().contains(name.toLowerCase(Locale.ROOT));
}

public static DistributionType from(Enum<?> other) {

return CACHE.computeIfAbsent(other, key -> {
final String name = key.name().toLowerCase(Locale.ROOT);
return Arrays.stream(values())
.filter(it -> it.getNames().contains(name))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Cannot create DistributionType from provided enum " + key + " of class " + key.getClass()));
});
return this.getNames().contains(name.toLowerCase(Locale.ENGLISH));
}
}

0 comments on commit c32ce68

Please sign in to comment.