Skip to content

Commit

Permalink
Add read/writeOptionalVLong to StreamInput/Output (#53145)
Browse files Browse the repository at this point in the history
The spirit of StreamInput/StreamOutput is that common I/O patterns should
be handled by these classes so that the persistence methods in
application classes can be kept short, which facilitates easy visual
comparison between read and write methods, and reduces risks of having
serialization issues due to mismatched implementations.

To this end, this change adds readOptionalVLong and writeOptionalVLong
methods to these classes as we have started to build up cases where
that conditional/null logic has been implemented directly in the read &
write methods.
  • Loading branch information
tvernum committed Mar 5, 2020
1 parent 17917b1 commit 0b38b6a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,14 @@ public long readVLong() throws IOException {
return i;
}

@Nullable
public Long readOptionalVLong() throws IOException {
if (readBoolean()) {
return readVLong();
}
return null;
}

public long readZLong() throws IOException {
long accumulator = 0L;
int i = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,15 @@ public void writeVLong(long i) throws IOException {
writeVLongNoCheck(i);
}

public void writeOptionalVLong(@Nullable Long l) throws IOException {
if (l == null) {
writeBoolean(false);
} else {
writeBoolean(true);
writeVLong(l);
}
}

/**
* Writes a long in a variable-length format without first checking if it is negative. Package private for testing. Use
* {@link #writeVLong(long)} instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

/**
* Tests for {@link BytesStreamOutput} paging behaviour.
Expand Down Expand Up @@ -275,6 +276,8 @@ public void testSimpleStreams() throws Exception {
out.writeLong(-3);
out.writeVLong(4);
out.writeOptionalLong(11234234L);
out.writeOptionalVLong(5L);
out.writeOptionalVLong(null);
out.writeFloat(1.1f);
out.writeDouble(2.2);
int[] intArray = {1, 2, 3};
Expand Down Expand Up @@ -311,6 +314,8 @@ public void testSimpleStreams() throws Exception {
assertThat(in.readLong(), equalTo(-3L));
assertThat(in.readVLong(), equalTo(4L));
assertThat(in.readOptionalLong(), equalTo(11234234L));
assertThat(in.readOptionalVLong(), equalTo(5L));
assertThat(in.readOptionalVLong(), nullValue());
assertThat((double)in.readFloat(), closeTo(1.1, 0.0001));
assertThat(in.readDouble(), closeTo(2.2, 0.0001));
assertThat(in.readGenericValue(), equalTo((Object) intArray));
Expand Down

0 comments on commit 0b38b6a

Please sign in to comment.