Skip to content

Commit

Permalink
update version => 1.0.62: optimization for consistent caching of shul…
Browse files Browse the repository at this point in the history
…kerboxes, preventing random permutations of nbt tags from affecting hashcode
  • Loading branch information
crxyne committed May 15, 2024
1 parent f8af722 commit d2cad98
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

<groupId>org.zeroBzeroT</groupId>
<artifactId>AntiIllegals</artifactId>
<version>1.0.61</version>
<version>1.0.62</version>
<packaging>jar</packaging>
<name>${project.artifactId}</name>

Expand Down
29 changes: 25 additions & 4 deletions src/main/java/org/zeroBzeroT/antiillegals/result/CachedState.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.zeroBzeroT.antiillegals.result;

import com.google.gson.Gson;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
Expand All @@ -9,18 +10,38 @@

public record CachedState(@NotNull ItemStack revertedStack, @NotNull ItemState revertedState) {

/**
* hashes the item identity, not the object reference itself
* @param itemStack the itemstack to find the hashcode of
* @return the hashcode
*/
public static int itemStackHashCode(@NotNull final ItemStack itemStack) {
final ItemMeta meta = itemStack.getItemMeta();

// hash the item identity, not the object reference itself
return Objects.hash(
itemStack.getType().ordinal(),
itemStack.getDurability(),
itemStack.getAmount(),
String.valueOf(meta)
nbtHashCode(itemStack)
);
}

@NotNull
private static final Gson NBT_GSON = new Gson();

/**
* order-independent nbt hashcode implementation
* @param itemStack the itemstack of which the nbt json will be used
* @return the hashcode of the nbt, ignoring the order of keys/values to ensure proper identity
*/
public static int nbtHashCode(@NotNull final ItemStack itemStack) {
final ItemMeta nbt = itemStack.clone().getItemMeta();
if (nbt == null) return 0;

final String name = nbt.getDisplayName();
nbt.setDisplayName(null);

return Objects.hash(NBT_GSON.toJsonTree(nbt), name);
}

public void applyRevertedState(@NotNull final ItemStack cached) {
if (revertedState == ItemState.CLEAN) return; // nothing to change

Expand Down

0 comments on commit d2cad98

Please sign in to comment.