2018-11-20 18:39:48 +01:00
|
|
|
package org.warp.jcwdb;
|
|
|
|
|
2018-12-15 01:01:23 +01:00
|
|
|
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
|
|
|
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
|
|
|
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
|
|
|
|
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
2018-11-20 18:39:48 +01:00
|
|
|
|
|
|
|
public class TypesManager {
|
2018-12-15 01:01:23 +01:00
|
|
|
private final Int2ObjectMap<DBTypeParser<?>> types;
|
|
|
|
private final Object2ObjectMap<Class<?>, DBTypeParser<?>> typesByClass;
|
|
|
|
private DBTypedObjectParser<?> fallbackParser;
|
2018-11-21 01:02:25 +01:00
|
|
|
|
|
|
|
public TypesManager(JCWDatabase db) {
|
2018-12-15 01:01:23 +01:00
|
|
|
types = new Int2ObjectOpenHashMap<>();
|
|
|
|
typesByClass = new Object2ObjectOpenHashMap<>();
|
2018-11-21 01:02:25 +01:00
|
|
|
DBStandardTypes.registerStandardTypes(db, this);
|
2018-11-20 18:39:48 +01:00
|
|
|
}
|
2018-12-15 01:01:23 +01:00
|
|
|
|
2018-11-21 01:02:25 +01:00
|
|
|
public <T> void registerType(Class<T> clazz, int type, DBTypeParser<T> parser) {
|
2018-11-20 18:39:48 +01:00
|
|
|
this.types.put(type, parser);
|
2018-11-21 01:02:25 +01:00
|
|
|
this.typesByClass.put(clazz, parser);
|
2018-11-20 18:39:48 +01:00
|
|
|
}
|
2018-11-21 01:02:25 +01:00
|
|
|
|
2018-12-15 01:01:23 +01:00
|
|
|
/**
|
|
|
|
* Use this method with the most used classes to save disk space.
|
|
|
|
* @param clazz
|
|
|
|
* @param id
|
|
|
|
* @param <T>
|
|
|
|
*/
|
|
|
|
public <T> void registerGenericClass(Class<T> clazz, int id) {
|
|
|
|
this.fallbackParser.registerClass(clazz, id);
|
|
|
|
}
|
|
|
|
|
|
|
|
public void registerTypeFallback(DBTypedObjectParser<?> parser) {
|
2018-11-23 22:23:14 +01:00
|
|
|
this.fallbackParser = parser;
|
|
|
|
}
|
|
|
|
|
2018-11-20 18:39:48 +01:00
|
|
|
public <T> DBTypeParser<T> get(int type) {
|
2018-11-23 22:23:14 +01:00
|
|
|
if (types.containsKey(type) == false) {
|
|
|
|
if (fallbackParser == null) {
|
|
|
|
throw new NoParserFoundException("The type " + type + " can't be parsed.");
|
|
|
|
} else {
|
|
|
|
return fallbackParser.cast();
|
|
|
|
}
|
|
|
|
}
|
2018-11-20 18:39:48 +01:00
|
|
|
return types.get(type).cast();
|
|
|
|
}
|
2018-11-21 01:02:25 +01:00
|
|
|
|
|
|
|
public <T> DBTypeParser<T> get(Class<T> type) {
|
2018-11-23 22:23:14 +01:00
|
|
|
if (typesByClass.containsKey(type) == false) {
|
|
|
|
if (fallbackParser == null) {
|
|
|
|
throw new NoParserFoundException("The class " + type.getSimpleName() + " can't be parsed.");
|
|
|
|
} else {
|
|
|
|
return fallbackParser.cast();
|
|
|
|
}
|
|
|
|
}
|
2018-11-21 01:02:25 +01:00
|
|
|
return typesByClass.get(type).cast();
|
|
|
|
}
|
2018-11-20 18:39:48 +01:00
|
|
|
}
|