From 12eff983d7241abf4164bfdda4a0178e5f67c5e1 Mon Sep 17 00:00:00 2001 From: Carter Kozak Date: Fri, 30 Jun 2017 11:39:08 -0400 Subject: [PATCH] Avoid re-reading data from a cached buffer Attempting to read an empty stream previously resulted in readObject returning the last object the FSTObjectInput read. --- .../coders/FSTStreamDecoder.java | 3 ++ src/test/ser/BasicReuseTest.java | 42 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/test/ser/BasicReuseTest.java diff --git a/src/main/java/org/nustaq/serialization/coders/FSTStreamDecoder.java b/src/main/java/org/nustaq/serialization/coders/FSTStreamDecoder.java index 0c817e3a..8e4499ee 100644 --- a/src/main/java/org/nustaq/serialization/coders/FSTStreamDecoder.java +++ b/src/main/java/org/nustaq/serialization/coders/FSTStreamDecoder.java @@ -290,6 +290,9 @@ public float readFFloat() throws IOException { @Override public final byte readFByte() throws IOException { input.ensureReadAhead(1); + if (input.pos > input.count) { + throw new IOException("Failed to read the next byte"); + } return input.buf[input.pos++]; } diff --git a/src/test/ser/BasicReuseTest.java b/src/test/ser/BasicReuseTest.java new file mode 100644 index 00000000..3e39a701 --- /dev/null +++ b/src/test/ser/BasicReuseTest.java @@ -0,0 +1,42 @@ +package ser; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.nustaq.serialization.FSTConfiguration; +import org.nustaq.serialization.FSTObjectInput; +import org.nustaq.serialization.FSTObjectOutput; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class BasicReuseTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void testStreamReuse() throws Exception { + FSTConfiguration configuration = FSTConfiguration.createDefaultConfiguration(); + + String expected = "Hello, World!"; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + FSTObjectOutput fstObjectOutput = configuration.getObjectOutput(baos); + try { + fstObjectOutput.writeObject(expected); + } finally { + fstObjectOutput.flush(); + } + byte[] serializedData = baos.toByteArray(); + FSTObjectInput input = configuration.getObjectInput(new ByteArrayInputStream(serializedData)); + Object read = input.readObject(); + Assert.assertEquals(expected, read); + + FSTObjectInput secondInput = configuration.getObjectInput(new ByteArrayInputStream(new byte[0])); + expectedException.expect(IOException.class); + expectedException.expectMessage("Failed to read"); + secondInput.readObject(); + } +}