add alternative methods for interacting with Context

This commit is contained in:
dfsek
2022-06-16 01:53:02 -07:00
parent c83924a7a4
commit 80583e1596
9 changed files with 91 additions and 22 deletions

View File

@@ -9,10 +9,15 @@ package com.dfsek.terra.api.properties;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class Context {
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
private static final AtomicInteger size = new AtomicInteger(0);
private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>();
@SuppressWarnings("unchecked")
public <T extends Properties> T get(Class<T> clazz) {
@@ -28,6 +33,26 @@ public class Context {
return this;
}
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
public <T extends Properties> Context put(PropertyKey<T> key, T properties) {
list.updateAndGet(p -> {
if(p.length == size.get()) return p;
Properties[] p2 = new Properties[size.get()];
System.arraycopy(p, 0, p2, 0, p.length);
return p2;
})[key.key] = properties;
return this;
}
@SuppressWarnings("unchecked")
public <T extends Properties> T get(PropertyKey<T> key) {
return (T) list.get()[key.key];
}
public <T extends Properties> boolean has(Class<T> test) {
return map.containsKey(test);
}

View File

@@ -0,0 +1,15 @@
package com.dfsek.terra.api.properties;
public class PropertyKey<T extends Properties> {
protected final int key;
private final Class<T> clazz;
protected PropertyKey(int key, Class<T> clazz) {
this.key = key;
this.clazz = clazz;
}
public Class<T> getTypeClass() {
return clazz;
}
}