|
| 1 | +package org.asdfformat.asdf.io.compression; |
| 2 | + |
| 3 | +import org.apache.commons.compress.compressors.lz4.BlockLZ4CompressorInputStream; |
| 4 | +import org.asdfformat.asdf.io.util.IOUtils; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.ByteBuffer; |
| 8 | +import java.nio.ByteOrder; |
| 9 | + |
| 10 | +public class Lz4Compressor implements Compressor { |
| 11 | + public static final byte[] IDENTIFIER = {108, 122, 52, 0}; // 'lz4' + padding |
| 12 | + |
| 13 | + @Override |
| 14 | + public byte[] getIdentifier() { |
| 15 | + return IDENTIFIER; |
| 16 | + } |
| 17 | + |
| 18 | + @Override |
| 19 | + public long decompress(final ByteBuffer inputBuffer, final ByteBuffer outputBuffer) throws IOException { |
| 20 | + long bytesDecompressed = 0L; |
| 21 | + |
| 22 | + while (inputBuffer.hasRemaining()) { |
| 23 | + inputBuffer.order(ByteOrder.BIG_ENDIAN); |
| 24 | + final int lz4BlockLength = inputBuffer.getInt() - 4; |
| 25 | + if (lz4BlockLength < 0) { |
| 26 | + throw new RuntimeException("LZ4 block length > " + Integer.MAX_VALUE + " not supported"); |
| 27 | + } |
| 28 | + |
| 29 | + // Discard the uncompressed data size written by the Python LZ4 bindings: |
| 30 | + inputBuffer.getInt(); |
| 31 | + |
| 32 | + final ByteBuffer lz4BlockInputBuffer = inputBuffer.duplicate(); |
| 33 | + lz4BlockInputBuffer.limit(inputBuffer.position() + lz4BlockLength); |
| 34 | + |
| 35 | + try (final ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(lz4BlockInputBuffer); |
| 36 | + final BlockLZ4CompressorInputStream blockLZ4CompressorInputStream = new BlockLZ4CompressorInputStream(byteBufferInputStream) |
| 37 | + ) { |
| 38 | + bytesDecompressed += IOUtils.transferTo(blockLZ4CompressorInputStream, outputBuffer); |
| 39 | + } |
| 40 | + |
| 41 | + inputBuffer.position(inputBuffer.position() + lz4BlockLength); |
| 42 | + } |
| 43 | + |
| 44 | + return bytesDecompressed; |
| 45 | + } |
| 46 | +} |
0 commit comments