Persist retired block and item ids per world and resolve transformers through them

This commit is contained in:
Ruling-0 committed 2026-08-27 20:00:19 -05:00
1 parent 4f8e73f915
commit ccdd37c38f
5 files changed
+418 -115

No files matched your search

@@ -1,5 +1,7 @@
package com.gtnewhorizons.postea;
import java.io.File;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
@@ -12,12 +14,15 @@ import com.gtnewhorizons.postea.utility.MissingMappingHandler;
import com.gtnewhorizons.postea.utility.SimpleTransformationRegistry;
import com.gtnewhorizons.postea.utility.TransformerRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent;
import cpw.mods.fml.common.event.FMLModIdMappingEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Mod(
@@ -49,6 +54,21 @@ public class Postea {
ChunkFixerUtility.onChunkLoaded(event.getChunk());
}
@Mod.EventHandler
public void serverAboutToStart(FMLServerAboutToStartEvent event) {
IDRegistry.beginWorld(
new File(
FMLCommonHandler.instance()
.getSavesDirectory(),
event.getServer()
.getFolderName()));
}
@Mod.EventHandler
public void serverStopped(FMLServerStoppedEvent event) {
IDRegistry.endWorld();
}
@Mod.EventHandler
public void onIdMappingsChanged(FMLModIdMappingEvent event) {
SimpleTransformationRegistry.onIdMappingsChanged();
@@ -1,17 +1,27 @@
package com.gtnewhorizons.postea.utility;
import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.function.Consumer;
import com.google.common.collect.LinkedHashMultimap;
import com.gtnewhorizons.postea.Postea;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.registry.GameData;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
/**
* A simple utility to resolve the IDs of any namepsaced ID that has ever been registered to an active world's id list.
* Resolves a namespaced id to the numeric ids it holds or held in the active world: the live registry id, the id
* the world's own saved map assigns it, and the ids recorded in the world's {@link WorldIdTable} for content that
* has since been removed.
*/
public abstract class IDRegistry {
@@ -24,6 +34,25 @@ public abstract class IDRegistry {
private static final LinkedHashMultimap<String, Consumer<Integer>> BLOCK_ID_RESOLVERS = LinkedHashMultimap.create();
private static final LinkedHashMultimap<String, Consumer<Integer>> ITEM_ID_RESOLVERS = LinkedHashMultimap.create();
private static File tableFile;
private static WorldIdTable table = new WorldIdTable();
/**
* Opens the retired id table of the world about to load. Until {@link #endWorld()} the saved id map is captured
* and merged into it.
*/
public static void beginWorld(File worldDirectory) {
tableFile = new File(new File(worldDirectory, Postea.MODID), WorldIdTable.FILE_NAME);
table = WorldIdTable.load(tableFile);
}
public static void endWorld() {
tableFile = null;
table = new WorldIdTable();
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
}
/**
* Triggers all the callbacks registered by other mods that wish to identify a block that may no longer exist.
* These callbacks effectively remove the need for dummies, and should help improve performance at runtime.
@@ -33,58 +62,114 @@ public abstract class IDRegistry {
// some space memory we can just ignore adding stuff safely.
if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// we should be fine to execute those in parallel I think?
BLOCK_ID_RESOLVERS.asMap()
.entrySet()
.parallelStream()
.forEach(kv -> {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
});
ITEM_ID_RESOLVERS.asMap()
.entrySet()
.parallelStream()
.forEach(kv -> {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
});
}
/**
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function is used to register all
* the previously registered namespaced to numeric id mappings that have ever been seen into a world.<br>
* <br>
* This function executes before the game starts remapping it's own internal IDs, so we can be sure that any
* existing will remain while the world is loaded.
*/
public static void registerWorldSpecificIDs(Map<String, Integer> map) {
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
for (Map.Entry<String, Integer> kv : map.entrySet()) {
String name = kv.getKey()
.substring(1);
int id = kv.getValue();
if (kv.getKey()
.charAt(0) == '\u0001') {
BLOCK_NAME_TO_ID.put(name, id);
} else {
ITEM_NAME_TO_ID.put(name, id);
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : BLOCK_ID_RESOLVERS.asMap()
.entrySet()) {
int id = getBlockId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
}
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : ITEM_ID_RESOLVERS.asMap()
.entrySet()) {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
}
}
/**
* Fetches the block numeric ID associated with the namespaced ID.
*
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function captures the world's
* saved name-to-id map before FML remaps the live registries onto it, and records it in the world's retired id
* table. Ignored outside a server world and off the server thread, since the client side of the FML handshake
* also injects a map.
*/
public static void registerWorldSpecificIDs(Map<String, Integer> map) {
if (tableFile == null || !FMLCommonHandler.instance()
.getEffectiveSide()
.isServer()) return;
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
for (Map.Entry<String, Integer> kv : map.entrySet()) {
String name = kv.getKey()
.substring(1);
if (kv.getKey()
.charAt(0) == '\u0001') {
BLOCK_NAME_TO_ID.put(name, (int) kv.getValue());
} else {
ITEM_NAME_TO_ID.put(name, (int) kv.getValue());
}
}
if (table.merge(map)) table.save(tableFile);
}
/**
* The block id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
public static int getBlockId(String name) {
int id = liveBlockId(name);
if (id >= 0) return id;
IntList retired = table.blockIds(name);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* The item id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
public static int getItemId(String name) {
int id = liveItemId(name);
if (id >= 0) return id;
IntList retired = table.itemIds(name);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* Every block id {@code name} holds or held in this world: the live id, plus retired ids that FML still blocks
* and no block occupies. Empty when the world never mapped the name.
*/
public static IntList getBlockIds(String name) {
int live = liveBlockId(name);
IntList ids = new IntArrayList();
if (live >= 0) ids.add(live);
IntSet blocked = new IntOpenHashSet(GameData.getBlockedIds());
for (int id : table.blockIds(name)) {
if (id != live && blocked.contains(id)
&& GameData.getBlockRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
if (live < 0 && !ids.isEmpty()) {
Postea.LOG.info("Block {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
/**
* Every item id {@code name} holds or held in this world: the live id, plus retired ids that FML still blocks
* and no item occupies. Empty when the world never mapped the name.
*/
public static IntList getItemIds(String name) {
int live = liveItemId(name);
IntList ids = new IntArrayList();
if (live >= 0) ids.add(live);
IntSet blocked = new IntOpenHashSet(GameData.getBlockedIds());
for (int id : table.itemIds(name)) {
if (id != live && blocked.contains(id)
&& GameData.getItemRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
if (live < 0 && !ids.isEmpty()) {
Postea.LOG.info("Item {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
private static int liveBlockId(String name) {
int id = BLOCK_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) {
id = GameData.getBlockRegistry()
@@ -94,14 +179,7 @@ public abstract class IDRegistry {
return id;
}
/**
* Fetches the item numeric ID associated with the namespaced ID.
*
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
*/
public static int getItemId(String name) {
private static int liveItemId(String name) {
int id = ITEM_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) {
id = GameData.getItemRegistry()
@@ -1,5 +1,6 @@
package com.gtnewhorizons.postea.utility;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -13,6 +14,7 @@ import net.minecraft.world.chunk.Chunk;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.LinkedListMultimap;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.api.IBlockTransformationHandler;
import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler;
@@ -21,6 +23,7 @@ import com.gtnewhorizons.postea.api.TriFunction;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntList;
/**
* A registry for all transformer functions
@@ -36,15 +39,17 @@ public class TransformerRegistry {
/**
* Map of itemID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
private static final Int2ObjectOpenHashMap<Pair<String, List<IItemStackTransformationHandler>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
/**
* Map of blockIO -> originalName+transformationHandler.
* Map of blockID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
private static final Int2ObjectOpenHashMap<Pair<String, List<IBlockTransformationHandler>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
// region FML Life Cycle handlers
/**
@@ -64,17 +69,27 @@ public class TransformerRegistry {
if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// create a lookup for source block ids.
for (String key : BLOCK_REPLACEMENT_MAP.keys()) {
int id = IDRegistry.getBlockId(key);
if (id >= 0) {
RUNTIME_BLOCK_REPLACEMENT_MAP.put(id, Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
for (String key : BLOCK_REPLACEMENT_MAP.keySet()) {
IntList ids = IDRegistry.getBlockIds(key);
if (ids.isEmpty()) {
Postea.LOG.debug("Block {} has no id in this world; its transformers stay inactive", key);
continue;
}
for (int id : ids) {
RUNTIME_BLOCK_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
}
}
// create a lookup for source block ids.
for (String key : ITEM_REPLACEMENT_MAP.keys()) {
int id = IDRegistry.getItemId(key);
if (id >= 0) {
RUNTIME_ITEM_REPLACEMENT_MAP.put(id, Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
// create a lookup for source item ids.
for (String key : ITEM_REPLACEMENT_MAP.keySet()) {
IntList ids = IDRegistry.getItemIds(key);
if (ids.isEmpty()) {
Postea.LOG.debug("Item {} has no id in this world; its transformers stay inactive", key);
continue;
}
for (int id : ids) {
RUNTIME_ITEM_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
}
}
}
@@ -83,12 +98,8 @@ public class TransformerRegistry {
/**
* Registers a block transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing block, a dummy block will be created when
* Postea detects that the id isn't associated to a block during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as the block name in the BlockConversionInfo is automatically
* updated to the original id when attempting to transform a dummy block. When Postea runs a
* transformation on a dummy block and no handler return true, Postea will automatically convert it to
* air.
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
@@ -101,15 +112,11 @@ public class TransformerRegistry {
/**
* Registers an item transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as transformation handlers are given the original id associated
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
* @param originalId The namespaced id of the item to transform.
* @param transformer The transformation handler that will execute a transformation on the stack.
*/
public static void addStackTransformer(@Nonnull String originalId,
@Nonnull IItemStackTransformationHandler transformer) {
@@ -117,17 +124,13 @@ public class TransformerRegistry {
}
/**
* Registers an item transformation handler function for the given id.
* Registers a tile entity transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as transformation handlers are given the original id associated
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
* @implNote Keyed by the tile entity's saved {@code id}; handlers run in registration order until one returns a
* non-null {@link BlockInfo}.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
* @param originalId The saved id of the tile entity to transform.
* @param transformer The transformation handler that will execute a transformation on the tile entity.
*/
public static void addTileEntityTransformer(@Nonnull String originalId,
@Nonnull TriFunction<NBTTagCompound, World, Chunk, BlockInfo> transformer) {
@@ -137,20 +140,12 @@ public class TransformerRegistry {
// region transformation handlers
public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, int metadata, World world, int x,
int y, int z) {
Pair<String, List<IBlockTransformationHandler>> data = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (data == null) return null;
BlockConversionInfo blockConversionInfo = new BlockConversionInfo(
// transparently maps the id to the original id if it's a dummy id
data.getKey(),
blockId,
metadata,
x,
y,
z,
world);
for (IBlockTransformationHandler transformer : data.getValue()) {
if (transformer.apply(blockConversionInfo)) {
return blockConversionInfo;
List<Pair<String, List<IBlockTransformationHandler>>> candidates = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (candidates == null) return null;
for (Pair<String, List<IBlockTransformationHandler>> data : candidates) {
BlockConversionInfo info = new BlockConversionInfo(data.getKey(), blockId, metadata, x, y, z, world);
for (IBlockTransformationHandler transformer : data.getValue()) {
if (transformer.apply(info)) return info;
}
}
return null;
@@ -159,17 +154,12 @@ public class TransformerRegistry {
public static void transformItem(NBTTagCompound tag) {
// abort early if tag is bad.
if (tag.hasNoTags() || !tag.hasKey("id")) return;
// get handler
int id = IDExtenderCompat.getItemStackID(tag);
Pair<String, List<IItemStackTransformationHandler>> data = RUNTIME_ITEM_REPLACEMENT_MAP.get(id);
// abort early if handler not found
if (data != null && !data.getValue()
.isEmpty()) {
// apply handlers
List<Pair<String, List<IItemStackTransformationHandler>>> candidates = RUNTIME_ITEM_REPLACEMENT_MAP
.get(IDExtenderCompat.getItemStackID(tag));
if (candidates == null) return;
for (Pair<String, List<IItemStackTransformationHandler>> data : candidates) {
for (IItemStackTransformationHandler transformer : data.getValue()) {
if (transformer.apply(data.getKey(), tag)) {
return;
}
if (transformer.apply(data.getKey(), tag)) return;
}
}
}
@@ -0,0 +1,136 @@
package com.gtnewhorizons.postea.utility;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.TreeMap;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntLists;
/**
* Every namespaced block and item name a world has mapped to a numeric id, with every id it held, oldest first.
* FML drops a missing name from {@code level.dat} on the first save after its content disappears; this table keeps
* the name so transformers keyed on it keep resolving in later sessions. Persisted as
* {@code <world>/postea/known-ids.json}, format version 1:
*
* <pre>
* { "version": 1, "blocks": { "mod:block": [300, 301] }, "items": { "mod:item": [4200] } }
* </pre>
*/
public final class WorldIdTable {
static final String FILE_NAME = "known-ids.json";
private static final int FORMAT_VERSION = 1;
private final Map<String, IntList> blocks = new TreeMap<>();
private final Map<String, IntList> items = new TreeMap<>();
/**
* Loads {@code file}; an absent file yields an empty table. Throws {@link IllegalStateException} on a file that
* cannot be read or parsed.
*/
public static WorldIdTable load(File file) {
WorldIdTable table = new WorldIdTable();
if (!file.exists()) return table;
try {
JsonObject root = new JsonParser()
.parse(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8))
.getAsJsonObject();
if (root.get("version")
.getAsInt() != FORMAT_VERSION) {
throw new IllegalStateException(file + " has an unsupported format version");
}
read(root.getAsJsonObject("blocks"), table.blocks);
read(root.getAsJsonObject("items"), table.items);
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("Cannot read the retired id table " + file, e);
}
return table;
}
private static void read(JsonObject object, Map<String, IntList> into) {
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
IntList ids = new IntArrayList();
for (JsonElement id : entry.getValue()
.getAsJsonArray()) {
ids.add(id.getAsInt());
}
into.put(entry.getKey(), ids);
}
}
/**
* Writes the table through a temporary file so a crash mid-write never truncates it.
*/
public void save(File file) {
JsonObject root = new JsonObject();
root.addProperty("version", FORMAT_VERSION);
root.add("blocks", write(blocks));
root.add("items", write(items));
File temp = new File(file.getPath() + ".tmp");
try {
Files.createDirectories(
file.toPath()
.getParent());
Files.write(
temp.toPath(),
new GsonBuilder().create()
.toJson(root)
.getBytes(StandardCharsets.UTF_8));
Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot write the retired id table " + file, e);
}
}
private static JsonObject write(Map<String, IntList> from) {
JsonObject object = new JsonObject();
for (Map.Entry<String, IntList> entry : from.entrySet()) {
JsonArray ids = new JsonArray();
for (int id : entry.getValue()) {
ids.add(new JsonPrimitive(id));
}
object.add(entry.getKey(), ids);
}
return object;
}
/**
* Records a world's saved name-to-id map, in which a name prefixed with U+0001 is a block. Returns whether
* any pair was new.
*/
public boolean merge(Map<String, Integer> dataList) {
boolean changed = false;
for (Map.Entry<String, Integer> entry : dataList.entrySet()) {
String prefixed = entry.getKey();
boolean block = prefixed.charAt(0) == '\u0001';
Map<String, IntList> into = block ? blocks : items;
IntList ids = into.computeIfAbsent(block ? prefixed.substring(1) : prefixed, name -> new IntArrayList());
if (!ids.contains((int) entry.getValue())) {
ids.add((int) entry.getValue());
changed = true;
}
}
return changed;
}
public IntList blockIds(String name) {
return blocks.getOrDefault(name, IntLists.EMPTY_LIST);
}
public IntList itemIds(String name) {
return items.getOrDefault(name, IntLists.EMPTY_LIST);
}
}
@@ -0,0 +1,79 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
class WorldIdTableTest {
@TempDir
File dir;
private File file() {
return new File(dir, "known-ids.json");
}
private static IntList ids(int... ids) {
return IntArrayList.wrap(ids);
}
private static Map<String, Integer> savedIds(Object... namesAndIds) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < namesAndIds.length; i += 2) {
map.put((String) namesAndIds[i], (Integer) namesAndIds[i + 1]);
}
return map;
}
@Test
void mergeRecordsEveryIdANameHeldInObservationOrderAndReportsChanges() {
WorldIdTable table = new WorldIdTable();
assertTrue(table.merge(savedIds("\u0001mod:block", 300, "mod:item", 4200)));
assertFalse(table.merge(savedIds("\u0001mod:block", 300, "mod:item", 4200)));
assertTrue(table.merge(savedIds("\u0001mod:block", 301)));
assertEquals(ids(300, 301), table.blockIds("mod:block"));
assertEquals(ids(4200), table.itemIds("mod:item"));
assertEquals(ids(), table.blockIds("mod:item"));
}
@Test
void saveAndLoadRoundTrip() {
WorldIdTable table = new WorldIdTable();
table.merge(savedIds("\u0001mod:block", 300, "mod:item", 4200));
table.merge(savedIds("\u0001mod:block", 301));
table.save(file());
WorldIdTable loaded = WorldIdTable.load(file());
assertEquals(ids(300, 301), loaded.blockIds("mod:block"));
assertEquals(ids(4200), loaded.itemIds("mod:item"));
}
@Test
void anAbsentFileLoadsEmptyAndAMalformedFileFailsLoudly() throws IOException {
assertEquals(
ids(),
WorldIdTable.load(file())
.blockIds("mod:block"));
Files.write(file().toPath(), "{\"version\":1,\"blocks\":5}".getBytes(StandardCharsets.UTF_8));
assertThrows(IllegalStateException.class, () -> WorldIdTable.load(file()));
}
}