lz4 / lz4-java

LZ4 compression for Java
Apache License 2.0
1.1k stars 253 forks source link

-1 issue if using read method #117

Closed sorenop closed 6 years ago

sorenop commented 6 years ago

I ran into an issue with the LZ4FrameInputStream.read() method: When the resulting one byte is '-1' (0xFF) this is not properly converted to unsigned int and is thus mistaken for the 'error return value' I guess that in most situations you would not use the read() method, but anyway ... Issue was found in 1.4.0 but is also present in 1.5

This test fails:

public void testLZ4LibFFFlaw() throws Exception {
        byte[] source = new byte[1];
        source[0] = (byte) 0xFF;
        byte[] dest = new byte[1];

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        LZ4FrameOutputStream compressedStream = new LZ4FrameOutputStream(bos);
        compressedStream.write(source);
        compressedStream.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        LZ4FrameInputStream decompressedStream = new LZ4FrameInputStream(bis);
        int i = 0;
        int data;
        while (i == 0) {
            data = decompressedStream.read();
            if (data == -1) {
                break;
            }
            dest[i++] = (byte) data;
        }
        assertEquals(source[0], dest[0]);
    }

whereas this works fine:

public void testLZ4LibFFFlaw() throws Exception {
        byte[] source = new byte[1];
        source[0] = (byte) 0xFF;
        byte[] dest = new byte[1];

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        LZ4FrameOutputStream compressedStream = new LZ4FrameOutputStream(bos);
        compressedStream.write(source);
        compressedStream.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        LZ4FrameInputStream decompressedStream = new LZ4FrameInputStream(bis);
        int i = 0;
        int data;
        while (i == 0) {
            data = decompressedStream.read(dest);
            if (data == -1) {
                break;
            }
        }
        assertEquals(source[0], dest[0]);
    }
odaira commented 6 years ago

Good catch! I'll fix it ASAP.

odaira commented 6 years ago

Fixed by 6081e4ee2dcb1726bb1528a19f34d9e207185059. Thanks!