Skip to content

Commit

Permalink
Merge pull request #202 from cakofony/stream_decoder_reuse_safety
Browse files Browse the repository at this point in the history
Avoid re-reading data from a cached buffer
  • Loading branch information
RuedigerMoeller authored Jul 3, 2017
2 parents 9f0d169 + 12eff98 commit 795d02e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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++];
}

Expand Down
42 changes: 42 additions & 0 deletions src/test/ser/BasicReuseTest.java
Original file line number Diff line number Diff line change
@@ -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();
}
}

0 comments on commit 795d02e

Please sign in to comment.