Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/java/net/jpountz/lz4/LZ4BlockOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,22 @@ public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}

/**
* Same as {@link #finish()}, but also closes the underlying stream. The underlying stream is closed even if finishing
* fails.
*/
@Override
public void close() throws IOException {
if (!finished) {
finish();
try {
if (!finished) {
finish();
}
} catch (Throwable t) {
final OutputStream failedOut = out;
finished = true;
out = null;
LZ4Utils.closeAfterFailure(failedOut, t);
throw t;
}
if (out != null) {
out.close();
Expand Down
31 changes: 25 additions & 6 deletions src/java/net/jpountz/lz4/LZ4FrameOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public static BLOCKSIZE valueOf(int indicator) {
private final byte[] compressedBuffer; // Only allocated once so it can be reused
private final int maxBlockSize;
private final long knownSize;
private long totalContentSize = 0L;
private final ByteBuffer intLEBuffer = ByteBuffer.allocate(INTEGER_BYTES).order(ByteOrder.LITTLE_ENDIAN);

private FrameInfo frameInfo = null;
Expand All @@ -114,7 +115,9 @@ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, FLG.Bits... b
*
* @param out the output stream to compress
* @param blockSize the BLOCKSIZE to use
* @param knownSize the size of the uncompressed data. A value less than zero means unknown.
* @param knownSize the size of the uncompressed data. A value less than zero means unknown. If
* {@link FLG.Bits#CONTENT_SIZE} is set and the value is greater than zero, {@link #close()} fails if
* a different number of bytes was written.
* @param bits a set of features to use
* @throws IOException if an I/O error occurs
*/
Expand All @@ -128,7 +131,9 @@ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, long knownSiz
*
* @param out the output stream to compress
* @param blockSize the BLOCKSIZE to use
* @param knownSize the size of the uncompressed data. A value less than zero means unknown.
* @param knownSize the size of the uncompressed data. A value less than zero means unknown. If
* {@link FLG.Bits#CONTENT_SIZE} is set and the value is greater than zero, {@link #close()} fails if
* a different number of bytes was written.
* @param compressor the {@link LZ4Compressor} instance to use to compress data
* @param checksum the {@link XXHash32} instance to use to check data for integrity
* @param bits a set of features to use
Expand Down Expand Up @@ -205,8 +210,6 @@ private void writeBlock() throws IOException {
if (buffer.position() == 0) {
return;
}
// Make sure there's no stale data
Arrays.fill(compressedBuffer, (byte) 0);

if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) {
frameInfo.updateStreamHash(buffer.array(), 0, buffer.position());
Expand Down Expand Up @@ -236,6 +239,7 @@ private void writeBlock() throws IOException {
intLEBuffer.putInt(0, checksum.hash(bufferToWrite, 0, compressedLength, 0));
out.write(intLEBuffer.array());
}
totalContentSize += buffer.position();
buffer.rewind();
}

Expand Down Expand Up @@ -301,13 +305,28 @@ private void ensureNotFinished() {
}
}

/**
* Ends the frame and closes the underlying stream. The underlying stream is closed even if ending the frame fails.
*/
@Override
public void close() throws IOException {
if (!frameInfo.isFinished()) {
if (frameInfo.isFinished()) {
return;
}
try {
flush();
// as in liblz4, 0 is not checked: the lz4 CLI decodes such frames whatever their size
if (frameInfo.isEnabled(FLG.Bits.CONTENT_SIZE) && knownSize > 0 && totalContentSize != knownSize) {
throw new IOException("Expected " + knownSize + " bytes of content, but " + totalContentSize + " were written");
}
writeEndMark();
out.flush();
} catch (Throwable t) {
frameInfo.finish();
LZ4Utils.closeAfterFailure(out, t);
throw t;
}
super.close();
out.close();
}

public static class FLG {
Expand Down
13 changes: 13 additions & 0 deletions src/java/net/jpountz/lz4/LZ4Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* limitations under the License.
*/

import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -89,6 +90,18 @@ static int grownLength(int length, int minLength, int maxLength) {
return (int) Math.min(maxLength, Math.max(minLength, 2L * length));
}

/** Closes {@code closeable} after {@code failure}, which the caller rethrows. Never throws. */
static void closeAfterFailure(Closeable closeable, Throwable failure) {
try {
closeable.close();
} catch (Throwable t) {
// streams may rethrow an earlier exception, and an exception cannot suppress itself
if (t != failure) {
failure.addSuppressed(t);
}
}
}

/**
* Returns {@code true} if {@code available < required}.
* <p>
Expand Down
210 changes: 210 additions & 0 deletions src/test/net/jpountz/lz4/LZ4OutputStreamTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
package net.jpountz.lz4;

/*
* Copyright 2026 Dominik Opwis and the lz4-java contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import net.jpountz.lz4.LZ4FrameOutputStream.BLOCKSIZE;
import net.jpountz.lz4.LZ4FrameOutputStream.FLG;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class LZ4OutputStreamTest {

enum Format {
FRAME {
@Override
OutputStream open(OutputStream out) throws IOException {
return new LZ4FrameOutputStream(out, BLOCKSIZE.SIZE_64KB);
}
},
BLOCK {
@Override
OutputStream open(OutputStream out) {
return new LZ4BlockOutputStream(out);
}
};

abstract OutputStream open(OutputStream out) throws IOException;
}

/** Records what was written, throws the given exceptions, if any, and counts calls. */
private static final class FailingOutputStream extends OutputStream {
final ByteArrayOutputStream written = new ByteArrayOutputStream();
Throwable writeFailure;
Throwable flushFailure;
IOException closeFailure;
int failedWrites;
int closes;
int flushedSize;

@Override
public void write(int b) throws IOException {
if (writeFailure != null) {
failedWrites++;
}
throwIfNotNull(writeFailure);
written.write(b);
}

@Override
public void flush() throws IOException {
throwIfNotNull(flushFailure);
flushedSize = written.size();
}

@Override
public void close() throws IOException {
closes++;
throwIfNotNull(closeFailure);
}

private static void throwIfNotNull(Throwable t) throws IOException {
if (t instanceof IOException) {
throw (IOException) t;
} else if (t != null) {
throw (Error) t;
}
}
}

@ParameterizedTest
@EnumSource(Format.class)
public void testFailedCloseClosesUnderlyingStream(Format format) throws IOException {
for (Throwable failure : new Throwable[] {new IOException("write"), new Error("write")}) {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = format.open(out);
os.write(1);
out.writeFailure = failure;
out.closeFailure = new IOException("close");

assertSame(failure, assertThrows(Throwable.class, os::close));
assertArrayEquals(new Throwable[] {out.closeFailure}, failure.getSuppressed());
assertEquals(1, out.closes);
}
}

@ParameterizedTest
@EnumSource(Format.class)
public void testFailedFlushClosesUnderlyingStream(Format format) throws IOException {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = format.open(out);
out.flushFailure = new Error("flush");

assertSame(out.flushFailure, assertThrows(Error.class, os::close));
assertEquals(1, out.closes);
}

@ParameterizedTest
@EnumSource(Format.class)
public void testFailedCloseIsNotRetried(Format format) throws IOException {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = format.open(out);
os.write(1);
out.writeFailure = new IOException("write");
assertThrows(IOException.class, os::close);
final int failedWrites = out.failedWrites;

os.close();
assertEquals(failedWrites, out.failedWrites);
assertEquals(1, out.closes);
assertThrows(IllegalStateException.class, () -> os.write(1));
}

/** Streams may rethrow the exception of an earlier failure, and an exception must not suppress itself. */
@ParameterizedTest
@EnumSource(Format.class)
public void testSameExceptionOnWriteAndClose(Format format) throws IOException {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = format.open(out);
os.write(1);
out.closeFailure = new IOException("failed");
out.writeFailure = out.closeFailure;

assertSame(out.closeFailure, assertThrows(IOException.class, os::close));
assertEquals(1, out.closes);
}

@ParameterizedTest
@EnumSource(Format.class)
public void testDoubleCloseClosesUnderlyingStreamOnce(Format format) throws IOException {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = format.open(out);
os.close();
assertEquals(out.written.size(), out.flushedSize);
out.flushFailure = new IOException("flush");
os.close();
assertEquals(1, out.closes);
}

private static OutputStream frameWithKnownSize(OutputStream out, long knownSize) throws IOException {
return new LZ4FrameOutputStream(out, BLOCKSIZE.SIZE_64KB, knownSize, FLG.Bits.BLOCK_INDEPENDENCE,
FLG.Bits.CONTENT_SIZE);
}

@ParameterizedTest
@ValueSource(ints = {0, 9, 11, (1 << 16) + 10})
public void testCloseRejectsKnownSizeMismatch(int size) throws IOException {
final FailingOutputStream out = new FailingOutputStream();
final OutputStream os = frameWithKnownSize(out, 10);
os.write(new byte[size]);
os.flush();
final int writtenBeforeClose = out.written.size();

assertThrows(IOException.class, os::close);
assertEquals(writtenBeforeClose, out.written.size(), "the frame must not be ended");
assertEquals(1, out.closes);
}

/** The lz4 CLI decodes such frames, so writing them must keep working. */
@Test
public void testKnownSizeZeroIsNotChecked() throws IOException {
final OutputStream os = frameWithKnownSize(new ByteArrayOutputStream(), 0);
os.write(new byte[5]);
os.close();
}

@Test
public void testKnownSizeIsNotCheckedWithoutContentSize() throws IOException {
final OutputStream os = new LZ4FrameOutputStream(new ByteArrayOutputStream(), BLOCKSIZE.SIZE_64KB, 10,
FLG.Bits.BLOCK_INDEPENDENCE);
os.write(new byte[5]);
os.close();
}

@Test
public void testKnownSizeAcrossBlocksAndFlushes() throws IOException {
final byte[] data = new byte[(1 << 16) + 10];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (OutputStream os = frameWithKnownSize(out, data.length)) {
os.write(data, 0, 5);
os.flush();
os.write(data, 5, data.length - 5);
}
assertArrayEquals(data, new LZ4FrameInputStream(new ByteArrayInputStream(out.toByteArray())).readAllBytes());
}
}
Loading