Search in sources :

Example 6 with LZ4Exception

use of net.jpountz.lz4.LZ4Exception in project netty by netty.

the class Lz4FrameEncoder method flushBufferedData.

private void flushBufferedData(ByteBuf out) {
    int flushableBytes = buffer.readableBytes();
    if (flushableBytes == 0) {
        return;
    }
    checksum.reset();
    checksum.update(buffer, buffer.readerIndex(), flushableBytes);
    final int check = (int) checksum.getValue();
    final int bufSize = compressor.maxCompressedLength(flushableBytes) + HEADER_LENGTH;
    out.ensureWritable(bufSize);
    final int idx = out.writerIndex();
    int compressedLength;
    try {
        ByteBuffer outNioBuffer = out.internalNioBuffer(idx + HEADER_LENGTH, out.writableBytes() - HEADER_LENGTH);
        int pos = outNioBuffer.position();
        // We always want to start at position 0 as we take care of reusing the buffer in the encode(...) loop.
        compressor.compress(buffer.internalNioBuffer(buffer.readerIndex(), flushableBytes), outNioBuffer);
        compressedLength = outNioBuffer.position() - pos;
    } catch (LZ4Exception e) {
        throw new CompressionException(e);
    }
    final int blockType;
    if (compressedLength >= flushableBytes) {
        blockType = BLOCK_TYPE_NON_COMPRESSED;
        compressedLength = flushableBytes;
        out.setBytes(idx + HEADER_LENGTH, buffer, 0, flushableBytes);
    } else {
        blockType = BLOCK_TYPE_COMPRESSED;
    }
    out.setLong(idx, MAGIC_NUMBER);
    out.setByte(idx + TOKEN_OFFSET, (byte) (blockType | compressionLevel));
    out.setIntLE(idx + COMPRESSED_LENGTH_OFFSET, compressedLength);
    out.setIntLE(idx + DECOMPRESSED_LENGTH_OFFSET, flushableBytes);
    out.setIntLE(idx + CHECKSUM_OFFSET, check);
    out.writerIndex(idx + HEADER_LENGTH + compressedLength);
    buffer.clear();
}
Also used : LZ4Exception(net.jpountz.lz4.LZ4Exception) ByteBuffer(java.nio.ByteBuffer)

Aggregations

LZ4Exception (net.jpountz.lz4.LZ4Exception)6 IOException (java.io.IOException)4 ByteBuf (io.netty.buffer.ByteBuf)1 ByteBuffer (java.nio.ByteBuffer)1