1 package net.jpountz.lz4;
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 import static net.jpountz.lz4.LZ4Constants.DEFAULT_COMPRESSION_LEVEL;
19 import java.nio.ByteBuffer;
21 import net.jpountz.util.ByteBufferUtils;
22 import net.jpountz.util.SafeUtils;
25 * High compression {@link LZ4Compressor}s implemented with JNI bindings to the
26 * original C implementation of LZ4.
28 final class LZ4HCJNICompressor extends LZ4Compressor {
30 public static final LZ4HCJNICompressor INSTANCE = new LZ4HCJNICompressor();
31 private static LZ4Compressor SAFE_INSTANCE;
33 private final int compressionLevel;
35 LZ4HCJNICompressor() { this(DEFAULT_COMPRESSION_LEVEL); }
36 LZ4HCJNICompressor(int compressionLevel) {
37 this.compressionLevel = compressionLevel;
41 public int compress(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen) {
42 SafeUtils.checkRange(src, srcOff, srcLen);
43 SafeUtils.checkRange(dest, destOff, maxDestLen);
44 final int result = LZ4JNI.LZ4_compressHC(src, null, srcOff, srcLen, dest, null, destOff, maxDestLen, compressionLevel);
46 throw new LZ4Exception();
52 public int compress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) {
53 ByteBufferUtils.checkNotReadOnly(dest);
54 ByteBufferUtils.checkRange(src, srcOff, srcLen);
55 ByteBufferUtils.checkRange(dest, destOff, maxDestLen);
57 if ((src.hasArray() || src.isDirect()) && (dest.hasArray() || dest.isDirect())) {
58 byte[] srcArr = null, destArr = null;
59 ByteBuffer srcBuf = null, destBuf = null;
62 srcOff += src.arrayOffset();
64 assert src.isDirect();
67 if (dest.hasArray()) {
68 destArr = dest.array();
69 destOff += dest.arrayOffset();
71 assert dest.isDirect();
75 final int result = LZ4JNI.LZ4_compressHC(srcArr, srcBuf, srcOff, srcLen, destArr, destBuf, destOff, maxDestLen, compressionLevel);
77 throw new LZ4Exception();
81 LZ4Compressor safeInstance = SAFE_INSTANCE;
82 if (safeInstance == null) {
83 safeInstance = SAFE_INSTANCE = LZ4Factory.safeInstance().highCompressor(compressionLevel);
85 return safeInstance.compress(src, srcOff, srcLen, dest, destOff, maxDestLen);