From 1da65317c45f8dcfb4d9ac43ac7d22f7aff0330c Mon Sep 17 00:00:00 2001 From: Dan Mulloy Date: Sun, 26 Apr 2015 15:47:44 -0400 Subject: [PATCH] Add in basic metadata API Fixes #80 --- .../protocol/events/PacketContainer.java | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/ProtocolLib/src/main/java/com/comphenix/protocol/events/PacketContainer.java b/ProtocolLib/src/main/java/com/comphenix/protocol/events/PacketContainer.java index d020e9c5..30971fe3 100644 --- a/ProtocolLib/src/main/java/com/comphenix/protocol/events/PacketContainer.java +++ b/ProtocolLib/src/main/java/com/comphenix/protocol/events/PacketContainer.java @@ -32,6 +32,7 @@ import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -986,7 +987,72 @@ public class PacketContainer implements Serializable { private ByteBuf createPacketBuffer() { return MinecraftReflection.getPacketDataSerializer(UnpooledByteBufAllocator.DEFAULT.buffer()); } - + + // ---- Metadata + // This map will only be initialized if it is actually used + private Map metadata; + + /** + * Gets the metadata value for a given key. + * + * @param key Metadata key + * @return Metadata value, or null if nonexistent. + */ + public Object getMetadata(String key) { + if (metadata != null) { + return metadata.get(key); + } + + return null; + } + + /** + * Adds metadata to this packet. + *

+ * Note: Since metadata is lazily initialized, this may result in the creation of the metadata map. + * + * @param key Metadata key + * @param value Metadata value + */ + public void addMetadata(String key, Object value) { + if (metadata == null) { + metadata = new HashMap(); + } + + metadata.put(key, value); + } + + /** + * Removes metadata from this packet. + *

+ * Note: If this operation leaves the metadata map empty, the map will be set to null. + * + * @param key Metadata key + * @return The previous value, or null if nonexistant. + */ + public Object removeMetadata(String key) { + if (metadata != null) { + Object value = metadata.remove(key); + if (metadata.isEmpty()) { + metadata = null; + } + + return value; + } + + return null; + } + + /** + * Whether or not this packet has metadata for a given key. + * + * @param key Metadata key + * @return True if this packet has metadata for the key, false if not. + */ + public boolean hasMetadata(String key) { + return metadata != null && metadata.containsKey(key); + } + /** * Retrieve the cached method concurrently. * @param lookup - a lazy lookup cache.