Added helper methods

This commit is contained in:
Finn
2026-02-01 17:06:06 +01:00
parent e3fe6dd088
commit b25e20b150
2 changed files with 53 additions and 1 deletions

View File

@@ -9,6 +9,8 @@
package dev.unlegitdqrk.unlegitlibrary.network.system.packets;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public abstract class Packet {
@@ -19,5 +21,55 @@ public abstract class Packet {
public abstract void read(DataInputStream stream, UUID clientID) throws IOException;
public abstract void write(DataOutputStream stream) throws IOException;
public final void writeList(DataOutputStream stream, List<?> list) throws IOException {
stream.writeInt(list.size());
for (Object item : list) {
writeObject(stream, item);
}
}
public final List<?> readList(DataInputStream stream) throws IOException {
int size = stream.readInt();
java.util.ArrayList<Object> list = new java.util.ArrayList<>(Math.max(size, 0));
for (int i = 0; i < size; i++) {
list.add(readObject(stream));
}
return list;
}
public final void writeMap(DataOutputStream stream, Map<?, ?> map) throws IOException {
stream.writeInt(map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
writeObject(stream, entry.getKey());
writeObject(stream, entry.getValue());
}
}
public final Map<?, ?> readMap(DataInputStream stream) throws IOException {
int size = stream.readInt();
java.util.HashMap<Object, Object> map = new java.util.HashMap<>(Math.max(size * 2, 0));
for (int i = 0; i < size; i++) {
Object key = readObject(stream);
Object value = readObject(stream);
map.put(key, value);
}
return map;
}
public final void writeObject(DataOutputStream stream, Object object) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(stream);
oos.writeObject(object);
oos.flush();
}
public final Object readObject(DataInputStream stream) throws IOException {
ObjectInputStream ois = new ObjectInputStream(stream);
try {
return ois.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("Failed to deserialize object", e);
}
}
}