mirror of
https://github.com/dmulloy2/ProtocolLib.git
synced 2024-11-01 00:11:39 +01:00
Add the ability to serialize ItemStacks to strings.
This commit is contained in:
parent
4756de8066
commit
749f006621
@ -1,9 +1,12 @@
|
|||||||
package com.comphenix.protocol.utility;
|
package com.comphenix.protocol.utility;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.DataInputStream;
|
import java.io.DataInputStream;
|
||||||
import java.io.DataOutputStream;
|
import java.io.DataOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
|
||||||
@ -46,6 +49,24 @@ public class StreamSerializer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deserialize an item stack from a base-32 encoded string.
|
||||||
|
* @param input - base-32 encoded string.
|
||||||
|
* @return A deserialized item stack.
|
||||||
|
* @throws IOException If the operation failed due to reflection or corrupt data.
|
||||||
|
*/
|
||||||
|
public ItemStack deserializeItemStack(String input) throws IOException {
|
||||||
|
try {
|
||||||
|
BigInteger base32 = new BigInteger(input, 32);
|
||||||
|
ByteArrayInputStream inputStream = new ByteArrayInputStream(base32.toByteArray());
|
||||||
|
|
||||||
|
return deserializeItemStack(new DataInputStream(inputStream));
|
||||||
|
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw new IOException("Input is not valid base 32.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write or serialize an item stack to the given output stream.
|
* Write or serialize an item stack to the given output stream.
|
||||||
* <p>
|
* <p>
|
||||||
@ -70,4 +91,20 @@ public class StreamSerializer {
|
|||||||
throw new IOException("Cannot write item stack " + stack, e);
|
throw new IOException("Cannot write item stack " + stack, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialize an item stack as a base-32 encoded string.
|
||||||
|
* @param stack - the item stack to serialize.
|
||||||
|
* @return A base-32 representation of the given item stack.
|
||||||
|
* @throws IOException If the operation fails due to reflection problems.
|
||||||
|
*/
|
||||||
|
public String serializeItemStack(ItemStack stack) throws IOException {
|
||||||
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
DataOutputStream dataOutput = new DataOutputStream(outputStream);
|
||||||
|
|
||||||
|
serializeItemStack(dataOutput, stack);
|
||||||
|
|
||||||
|
// Serialize that array
|
||||||
|
return new BigInteger(1, outputStream.toByteArray()).toString(32);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user