Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@
@NullMarked
record TypedKeyImpl<T>(Key key, RegistryKey<T> registryKey) implements TypedKey<T> {
// Wrap key methods to make this easier to use
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other instanceof final TypedKey<?> otherTyped) {
return this.key.equals(otherTyped.key()) && this.registryKey.equals(otherTyped.registryKey());
}
// A TypedKey is a Key, so it must compare equal to a plain Key with the same
// namespace and value (adventure's Key equality) to keep equals symmetric.
return other instanceof final Key otherKey
&& this.key.namespace().equals(otherKey.namespace())
&& this.key.value().equals(otherKey.value());
}

@Override
public int hashCode() {
// Match KeyImpl#hashCode so a TypedKey and an equal plain Key share a hash code.
return this.key.hashCode();
}

@KeyPattern.Namespace
@Override
public String namespace() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.papermc.paper.registry;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import net.kyori.adventure.key.Key;
import org.bukkit.inventory.ItemType;
import org.junit.jupiter.api.Test;

class TypedKeyEqualityTest {

@Test
void typedKeyIsSymmetricWithPlainKey() {
final Key key = Key.key("minecraft:stone");
final TypedKey<ItemType> typedKey = TypedKey.create(RegistryKey.ITEM, key);

// equals must be symmetric across the Key hierarchy
assertTrue(key.equals(typedKey), "plain Key should equal an equal TypedKey");
assertTrue(typedKey.equals(key), "TypedKey should equal an equal plain Key");
assertEquals(key.equals(typedKey), typedKey.equals(key), "equals must be symmetric");

// equal keys must share a hash code
assertEquals(key.hashCode(), typedKey.hashCode());
}

@Test
void typedKeysDifferByRegistry() {
final Key key = Key.key("minecraft:stone");
final TypedKey<ItemType> itemKey = TypedKey.create(RegistryKey.ITEM, key);
final TypedKey<?> blockKey = TypedKey.create(RegistryKey.BLOCK, key);

// same underlying key but different registries are not equal
assertNotEquals(itemKey, blockKey);
}
}
Loading