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.util.ByteBufferUtils.checkNotReadOnly;
18 import static net.jpountz.util.ByteBufferUtils.checkRange;
19 import static net.jpountz.util.SafeUtils.checkRange;
21 import java.nio.ByteBuffer;
24 * Fast {@link LZ4FastCompressor}s implemented with JNI bindings to the original C
25 * implementation of LZ4.
27 final class LZ4JNICompressor extends LZ4Compressor {
29 public static final LZ4Compressor INSTANCE = new LZ4JNICompressor();
30 private static LZ4Compressor SAFE_INSTANCE;
33 public int compress(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen) {
34 checkRange(src, srcOff, srcLen);
35 checkRange(dest, destOff, maxDestLen);
36 final int result = LZ4JNI.LZ4_compress_limitedOutput(src, null, srcOff, srcLen, dest, null, destOff, maxDestLen);
38 throw new LZ4Exception("maxDestLen is too small");
44 public int compress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) {
45 checkNotReadOnly(dest);
46 checkRange(src, srcOff, srcLen);
47 checkRange(dest, destOff, maxDestLen);
49 if ((src.hasArray() || src.isDirect()) && (dest.hasArray() || dest.isDirect())) {
50 byte[] srcArr = null, destArr = null;
51 ByteBuffer srcBuf = null, destBuf = null;
54 srcOff += src.arrayOffset();
56 assert src.isDirect();
59 if (dest.hasArray()) {
60 destArr = dest.array();
61 destOff += dest.arrayOffset();
63 assert dest.isDirect();
67 final int result = LZ4JNI.LZ4_compress_limitedOutput(srcArr, srcBuf, srcOff, srcLen, destArr, destBuf, destOff, maxDestLen);
69 throw new LZ4Exception("maxDestLen is too small");
73 LZ4Compressor safeInstance = SAFE_INSTANCE;
74 if (safeInstance == null) {
75 safeInstance = SAFE_INSTANCE = LZ4Factory.safeInstance().fastCompressor();
77 return safeInstance.compress(src, srcOff, srcLen, dest, destOff, maxDestLen);