Throw IOException when writing to / flushing closed SnappyOutputStreams.

This commit is contained in:
Josh Rosen 2015-05-14 10:59:16 -07:00
parent 2b6c8dc896
commit dcdada2ed4
2 changed files with 41 additions and 0 deletions

View File

@ -232,6 +232,9 @@ public class SnappyOutputStream extends OutputStream {
* @throws IOException
*/
public void rawWrite(Object array, int byteOffset, int byteLength) throws IOException {
if (closed) {
throw new IOException("Stream is closed");
}
int cursor = 0;
while(cursor < byteLength) {
int readLen = Math.min(byteLength - cursor, blockSize - inputCursor);
@ -259,6 +262,9 @@ public class SnappyOutputStream extends OutputStream {
*/
@Override
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Stream is closed");
}
if(inputCursor >= inputBuffer.length) {
compressInput();
}
@ -270,6 +276,9 @@ public class SnappyOutputStream extends OutputStream {
*/
@Override
public void flush() throws IOException {
if (closed) {
throw new IOException("Stream is closed");
}
compressInput();
dumpOutput();
out.flush();

View File

@ -29,6 +29,7 @@ import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.Test;
import org.xerial.snappy.buffer.BufferAllocatorFactory;
@ -193,6 +194,37 @@ public class SnappyOutputStreamTest
in3.close();
}
@Test
public void writingToClosedStreamShouldThrowIOException() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
SnappyOutputStream os = new SnappyOutputStream(b);
os.close();
try {
os.write(4);
fail("Expected write() to throw IOException");
} catch (IOException e) {
// Expected exception
}
try {
os.write(new int[] { 1, 2, 3, 4});
fail("Expected write() to throw IOException");
} catch (IOException e) {
// Expected exception
}
}
@Test
public void flushingClosedStreamShouldThrowIOException() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
SnappyOutputStream os = new SnappyOutputStream(b);
os.close();
try {
os.flush();
} catch (IOException e) {
// Expected exception
}
}
@Test
public void longArrayCompress() throws Exception {
long[] l = new long[10];