| 26 | import java.nio.ByteBuffer; |
| 27 | |
| 28 | public class XerialSnappyCodec implements CompressionCodec, DirectDecompressionCodec { |
| 29 | private static final ThreadLocal<byte[]> threadBuffer = ThreadLocal.withInitial(() -> null); |
| 30 | |
| 31 | static { |
| 32 | Snappy.getNativeLibraryVersion(); |
| 33 | } |
| 34 | |
| 35 | public XerialSnappyCodec() {} |
| 36 | |
| 37 | protected static byte[] getBuffer(int size) { |
| 38 | byte[] result = threadBuffer.get(); |
| 39 | if (result == null || result.length < size || result.length > size * 2) { |
| 40 | result = new byte[size]; |
| 41 | threadBuffer.set(result); |
| 42 | } |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | @Override |
| 47 | public Options getDefaultOptions() { |
| 48 | return CompressionCodec.NullOptions.INSTANCE; |
| 49 | } |
| 50 | |
| 51 | @Override |
| 52 | public boolean compress(ByteBuffer in, ByteBuffer out, |
| 53 | ByteBuffer overflow, |
| 54 | Options options) throws IOException { |
| 55 | int inBytes = in.remaining(); |
| 56 | // Skip with minimum size check similar to ZstdCodec |
| 57 | if (inBytes < 10) return false; |
| 58 | |
| 59 | int maxOutputLength = Snappy.maxCompressedLength(inBytes); |
| 60 | byte[] compressed = getBuffer(maxOutputLength); |
| 61 | |
| 62 | int outBytes = Snappy.compress(in.array(), in.arrayOffset() + in.position(), inBytes, |
| 63 | compressed, 0); |
| 64 | |
| 65 | if (outBytes < inBytes) { |
| 66 | int remaining = out.remaining(); |
| 67 | if (remaining >= outBytes) { |
| 68 | System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + |
| 69 | out.position(), outBytes); |
| 70 | out.position(out.position() + outBytes); |
| 71 | } else { |
| 72 | System.arraycopy(compressed, 0, out.array(), out.arrayOffset() + |
| 73 | out.position(), remaining); |
| 74 | out.position(out.limit()); |
| 75 | System.arraycopy(compressed, remaining, overflow.array(), |
| 76 | overflow.arrayOffset(), outBytes - remaining); |
| 77 | overflow.position(outBytes - remaining); |
| 78 | } |
| 79 | return true; |
| 80 | } else { |
| 81 | return false; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | @Override |
nothing calls this directly
no outgoing calls
no test coverage detected