diff --git a/src/main/java/org/xerial/snappy/Snappy.java b/src/main/java/org/xerial/snappy/Snappy.java index 14d17964..7613e7f7 100755 --- a/src/main/java/org/xerial/snappy/Snappy.java +++ b/src/main/java/org/xerial/snappy/Snappy.java @@ -150,6 +150,13 @@ public static int compress(ByteBuffer uncompressed, ByteBuffer compressed) int uPos = uncompressed.position(); int uLen = uncompressed.remaining(); int cPos = compressed.position(); + + int requiredCapacity = maxCompressedLength(uLen); + if (compressed.remaining() < requiredCapacity) { + throw new IllegalArgumentException("not enough space for output: need " + requiredCapacity + + " bytes, but only " + compressed.remaining() + " remaining"); + } + int compressedSize = impl.rawCompress(uncompressed, uPos, uLen, compressed, cPos); diff --git a/src/test/java/org/xerial/snappy/SnappyTest.java b/src/test/java/org/xerial/snappy/SnappyTest.java index 52c3a005..34bd8e4d 100755 --- a/src/test/java/org/xerial/snappy/SnappyTest.java +++ b/src/test/java/org/xerial/snappy/SnappyTest.java @@ -527,6 +527,21 @@ public void isTooLargeShortArrayInputLengthForBitShuffleShuffle() throws Excepti BitShuffle.shuffle(new short[Integer.MAX_VALUE / 2 + 1]); } + @Test(expected = IllegalArgumentException.class) + public void testCompressWithInsufficientBuffer() throws Exception { + byte[] incompressible = new byte[1024 * 1024]; + new java.util.Random(42).nextBytes(incompressible); + + ByteBuffer src = ByteBuffer.allocateDirect(incompressible.length); + src.put(incompressible); + src.flip(); + + ByteBuffer dest = ByteBuffer.allocateDirect(64); + + Snappy.compress(src, dest); + fail("Expected IllegalArgumentException but method completed normally"); +} + private void assumingCIIsFalse() { if (System.getenv("CI") == null) return;