-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInventoryCodec.java
More file actions
64 lines (57 loc) · 2.45 KB
/
Copy pathInventoryCodec.java
File metadata and controls
64 lines (57 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package dev.vupe.core.util;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import java.io.*;
import java.util.Base64;
public final class InventoryCodec {
private InventoryCodec() {}
public static String encode(Inventory inventory) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytes)) {
out.writeInt(inventory.getSize());
for (ItemStack item : inventory.getContents()) out.writeObject(item);
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
} catch (IOException ex) {
throw new IllegalStateException("Could not encode inventory", ex);
}
}
public static void decodeInto(String encoded, Inventory inventory) {
if (encoded == null || encoded.isBlank()) return;
try {
byte[] bytes = Base64.getDecoder().decode(encoded);
try (BukkitObjectInputStream in = new BukkitObjectInputStream(new ByteArrayInputStream(bytes))) {
int size = in.readInt();
for (int slot = 0; slot < Math.min(size, inventory.getSize()); slot++) {
inventory.setItem(slot, (ItemStack) in.readObject());
}
}
} catch (Exception ex) {
throw new IllegalStateException("Could not decode inventory", ex);
}
}
public static String encodeItem(ItemStack item) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (BukkitObjectOutputStream out = new BukkitObjectOutputStream(bytes)) {
out.writeObject(item);
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
} catch (IOException ex) {
throw new IllegalStateException("Could not encode item", ex);
}
}
public static ItemStack decodeItem(String encoded) {
try {
byte[] bytes = Base64.getDecoder().decode(encoded);
try (BukkitObjectInputStream in = new BukkitObjectInputStream(new ByteArrayInputStream(bytes))) {
return (ItemStack) in.readObject();
}
} catch (Exception ex) {
throw new IllegalStateException("Could not decode item", ex);
}
}
}