Added helper methods
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user