Update convenience methods

This commit is contained in:
Noel Németh 2022-06-10 20:22:33 +02:00
parent 6b489b5843
commit 960d5c80db
2 changed files with 20 additions and 9 deletions

View File

@ -126,6 +126,10 @@ public class BinaryReader extends InputStream {
return readSizedString(Integer.MAX_VALUE);
}
public @Nullable String readNullableSizedString() {
return readNullable(this::readSizedString);
}
public byte[] readBytes(int length) {
byte[] bytes = new byte[length];
buffer.get(bytes);
@ -206,7 +210,7 @@ public class BinaryReader extends InputStream {
}
public @Nullable Component readNullableComponent() {
return readBoolean() ? readComponent() : null;
return readNullable(this::readComponent);
}
public Component readComponent() {
@ -303,4 +307,8 @@ public class BinaryReader extends InputStream {
//buffer.get(startingPosition, output);
return output;
}
public <T> @Nullable T readNullable(Supplier<T> reader) {
return readBoolean() ? reader.get() : null;
}
}

View File

@ -72,12 +72,7 @@ public class BinaryWriter extends OutputStream {
}
public void writeNullableComponent(@Nullable Component component) {
if (component == null) {
writeBoolean(false);
} else {
writeBoolean(true);
writeComponent(component);
}
writeNullable(component, this::writeComponent);
}
/**
@ -201,6 +196,10 @@ public class BinaryWriter extends OutputStream {
writeBytes(bytes);
}
public void writeNullableSizedString(@Nullable String string) {
writeNullable(string, this::writeSizedString);
}
/**
* Writes a null terminated string to the buffer. This method adds the null character
* to the end of the string before writing.
@ -336,11 +335,15 @@ public class BinaryWriter extends OutputStream {
}
public void writeNullable(@Nullable Writeable writeable) {
if (writeable == null) {
writeNullable(writeable, this::write);
}
public <T> void writeNullable(T object, Consumer<T> writer) {
if (object == null) {
writeBoolean(false);
} else {
writeBoolean(true);
write(writeable);
writer.accept(object);
}
}