All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.aliyun.datahub.client.impl.compress.Lz4Compressor Maven / Gradle / Ivy

The newest version!
package com.aliyun.datahub.client.impl.compress;

import com.aliyun.datahub.client.model.CompressType;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4SafeDecompressor;
import org.apache.commons.io.IOUtils;

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

public class Lz4Compressor extends Compressor {
    private static final LZ4Compressor compressor = LZ4Factory.fastestInstance().fastCompressor();
    private static final LZ4SafeDecompressor decompressor = LZ4Factory.fastestInstance().safeDecompressor();

    public Lz4Compressor() {
        super(CompressType.LZ4);
    }

    @Override
    public byte[] compress(byte[] input, int offset, int length) throws IOException {
        return compressor.compress(input, offset, length);
    }

    @Override
    public byte[] decompress(byte[] input, int offset, int length, int oriSize) throws IOException {
        byte[] restored = new byte[oriSize];
        int size = decompressor.decompress(input, offset, length, restored, 0);
        if (size != oriSize) {
            throw new IOException("Decompressed buffer size error, expect:" + oriSize + ", real:" + size);
        }
        return restored;
    }

    @Override
    public void compress(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] input = IOUtils.toByteArray(inputStream);
        byte[] output = compress(input);
        outputStream.write(output);
        outputStream.flush();
    }

    @Override
    public void decompress(InputStream inputStream, OutputStream outputStream, int oriSize) throws IOException {
        byte[] input = IOUtils.toByteArray(inputStream);
        byte[] output = decompress(input, oriSize);
        outputStream.write(output);
        outputStream.flush();
    }

    @Override
    public InputStream decompress(InputStream inputStream, int oriSize) throws IOException {
        byte[] input = IOUtils.toByteArray(inputStream);
        byte[] output = decompress(input, oriSize);
        return new ByteArrayInputStream(output);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy