From e6d9141602307fe266d8f91a77a34aa1b02c4a20 Mon Sep 17 00:00:00 2001 From: Dominik Opwis Date: Mon, 16 Nov 2026 18:50:57 +0100 Subject: [PATCH 01/16] Speed up the safe Java implementation on Java 9+ with a multi-release JAR The safe LZ4 and xxHash implementations read and compare one byte at a time, because Java 7 has no bounds-checked multi-byte array access. LZ4Factory.unsafeInstance() returns the safe instance, so this is the Java path for everyone without the native library. Move the byte-array primitives of SafeUtils and LZ4SafeUtils into net.jpountz.util.ByteArrays and add a Java 9+ variant of that class in META-INF/versions/9. It uses byte-array-view VarHandles, Arrays.mismatch, and the overlapping-copy algorithm of LZ4UnsafeUtils, so every access stays bounds checked. Java 7 and 8 keep the existing code. The build compiles src/java9 with --release 9 and marks the JAR Multi-Release. Failsafe reruns the tests against the JAR so the Java 9+ class is tested too. bnd no longer writes per-release OSGi manifests, whose empty Require-Capability header Felix and Equinox reject, and the JaCoCo report skips META-INF/versions. Closes #35 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 1 + CONTRIBUTING.md | 2 + README.md | 3 +- lz4-java.bnd | 3 + pom.xml | 49 +++++++ src/java/net/jpountz/lz4/LZ4SafeUtils.java | 25 +--- src/java/net/jpountz/util/ByteArrays.java | 93 +++++++++++++ src/java/net/jpountz/util/SafeUtils.java | 20 +-- src/java9/net/jpountz/util/ByteArrays.java | 127 ++++++++++++++++++ .../net/jpountz/lz4/OverlappingMatchTest.java | 83 ++++++++++++ .../net/jpountz/util/MultiReleaseJarTest.java | 117 ++++++++++++++++ 11 files changed, 489 insertions(+), 34 deletions(-) create mode 100644 src/java/net/jpountz/util/ByteArrays.java create mode 100644 src/java9/net/jpountz/util/ByteArrays.java create mode 100644 src/test/net/jpountz/lz4/OverlappingMatchTest.java create mode 100644 src/test/net/jpountz/util/MultiReleaseJarTest.java diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 74dd57d7..a70bf6ee 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,6 +29,7 @@ jobs: # Disable fuzzing until https://github.com/CodeIntelligenceTesting/jazzer supports linux-riscv64 maven-flags: >- -Dtest='!net/jpountz/fuzz/*' + -Dit.test='!net/jpountz/fuzz/*' -Dmaven.compiler.source=8 -Dmaven.compiler.target=8 steps: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 99bfea0a..c9d4b1d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,8 @@ To be accepted, a contribution must meet these requirements: - **The build passes.** `./mvnw verify` must succeed, and CI must be green on all platforms. See the [README](README.md#building) for build prerequisites. - **Java 7 compatibility.** The library is compiled with Java 7 and must not use newer language features or APIs. + The one exception is `src/java9`, compiled for Java 9 into `META-INF/versions/9` of the multi-release JAR. It only + holds the Java 9+ variant of `net.jpountz.util.ByteArrays`, which must keep the same methods as the Java 7 one. Tests may use the newer Java version configured in `pom.xml`. - **No breaking API changes.** Public API must stay source and binary compatible. Deprecate instead of removing, and keep new non-user-facing members as private as possible. diff --git a/README.md b/README.md index 1aa5187f..b4516f33 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,8 @@ now always uses the (slower) safe Java implementation, regardless of which facto `LZ4Factory` and `XXHashFactory` provide the following implementations, which all produce compatible output: - `nativeInstance()`: JNI bindings to the reference C implementation. -- `safeInstance()`: A pure Java port. +- `safeInstance()`: A pure Java port. On Java 9 and newer it reads, writes and compares several bytes at a time with + `VarHandle` and `Arrays.mismatch`, still without `sun.misc.Unsafe`. - `unsafeInstance()`: A Java port using `sun.misc.Unsafe`. For LZ4, this is currently an alias for the safe instance out of caution. diff --git a/lz4-java.bnd b/lz4-java.bnd index a06ba026..28a5d11d 100644 --- a/lz4-java.bnd +++ b/lz4-java.bnd @@ -4,3 +4,6 @@ Bundle-Version: ${version_cleanup;${ivy.version}} Export-Package: net.jpountz.*;version:=${version_cleanup;${packages.version}} -noee: true -removeheaders: Require-Capability +# No per-release OSGI-INF/MANIFEST.MF: bnd writes an empty Require-Capability there, which Felix and Equinox reject. +# The Java 9 classes in META-INF/versions/9 only add java.lang.invoke, and java.* always comes from the boot loader. +-jpms-multi-release: false diff --git a/pom.xml b/pom.xml index 277aca5f..e81bd1ad 100644 --- a/pom.xml +++ b/pom.xml @@ -188,6 +188,24 @@ + + + compile-java9 + compile + + compile + + + 9 + + ${project.basedir}/src/java9 + + true + ${project.build.sourceEncoding} + true + true + + default-testCompile test-compile @@ -213,6 +231,7 @@ ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.lz4.java + true @@ -277,6 +296,29 @@ maven-surefire-plugin 3.6.1 + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.6.1 + + + + integration-test + verify + + + + + + **/*Test.java + + + true + + + org.apache.maven.plugins maven-source-plugin @@ -363,6 +405,12 @@ report + + + + META-INF/versions/** + + @@ -657,6 +705,7 @@ -O1 -g -fPIC -fno-omit-frame-pointer 5s + true diff --git a/src/java/net/jpountz/lz4/LZ4SafeUtils.java b/src/java/net/jpountz/lz4/LZ4SafeUtils.java index 1d62b991..5a36c5df 100644 --- a/src/java/net/jpountz/lz4/LZ4SafeUtils.java +++ b/src/java/net/jpountz/lz4/LZ4SafeUtils.java @@ -16,6 +16,7 @@ * limitations under the License. */ +import net.jpountz.util.ByteArrays; import net.jpountz.util.SafeUtils; import static net.jpountz.lz4.LZ4Constants.LAST_LITERALS; @@ -38,7 +39,7 @@ static int hash64k(byte[] buf, int i) { } static boolean readIntEquals(byte[] buf, int i, int j) { - return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + return ByteArrays.readIntEquals(buf, i, j); } static void safeIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchLen) { @@ -48,25 +49,11 @@ static void safeIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchLe } static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { - do { - copy8Bytes(dest, matchOff, dest, dOff); - matchOff += 8; - dOff += 8; - } while (dOff < matchCopyEnd); - } - - static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { - for (int i = 0; i < 8; ++i) { - dest[dOff + i] = src[sOff + i]; - } + ByteArrays.wildIncrementalCopy(dest, matchOff, dOff, matchCopyEnd); } static int commonBytes(byte[] b, int o1, int o2, int limit) { - int count = 0; - while (o2 < limit && b[o1++] == b[o2++]) { - ++count; - } - return count; + return ByteArrays.commonBytes(b, o1, o2, limit); } static int commonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { @@ -84,9 +71,9 @@ static void safeArraycopy(byte[] src, int sOff, byte[] dest, int dOff, int len) static void wildArraycopy(byte[] src, int sOff, byte[] dest, int dOff, int len) { try { for (int i = 0; i < len; i += 8) { - copy8Bytes(src, sOff + i, dest, dOff + i); + ByteArrays.copy8Bytes(src, sOff + i, dest, dOff + i); } - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // the Java 9+ ByteArrays may throw the superclass throw new LZ4Exception("Malformed input at offset " + sOff); } } diff --git a/src/java/net/jpountz/util/ByteArrays.java b/src/java/net/jpountz/util/ByteArrays.java new file mode 100644 index 00000000..1bfa1470 --- /dev/null +++ b/src/java/net/jpountz/util/ByteArrays.java @@ -0,0 +1,93 @@ +package net.jpountz.util; + +/* + * Copyright 2020 Adrien Grand and the lz4-java contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.nio.ByteOrder; + +/** + * FOR INTERNAL USE ONLY + *

+ * Multi-byte reads, writes, copies and comparisons on byte arrays for the safe implementations. This is the only class + * with a Java 9+ variant: src/java9/net/jpountz/util/ByteArrays.java, loaded from META-INF/versions/9 of the + * multi-release jar. Keep the two in sync, and keep everything else out of them. + */ +public enum ByteArrays { + ; + + public static int readShortLE(byte[] buf, int i) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); + } + + public static void writeShortLE(byte[] buf, int off, int v) { + buf[off++] = (byte) v; + buf[off++] = (byte) (v >>> 8); + } + + public static int readIntBE(byte[] buf, int i) { + return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); + } + + public static int readIntLE(byte[] buf, int i) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); + } + + /** Reads an int in native byte order. */ + public static int readInt(byte[] buf, int i) { + if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { + return readIntBE(buf, i); + } else { + return readIntLE(buf, i); + } + } + + public static long readLongLE(byte[] buf, int i) { + return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) + | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); + } + + /** Whether the 4 bytes at i equal the 4 bytes at j. */ + public static boolean readIntEquals(byte[] buf, int i, int j) { + return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + } + + public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + for (int i = 0; i < 8; ++i) { + dest[dOff + i] = src[sOff + i]; + } + } + + /** The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. */ + public static int commonBytes(byte[] b, int o1, int o2, int limit) { + int count = 0; + while (o2 < limit && b[o1++] == b[o2++]) { + ++count; + } + return count; + } + + /** + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap and + * matchOff < dOff. Writes up to 7 bytes past matchCopyEnd. + */ + public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { + do { + copy8Bytes(dest, matchOff, dest, dOff); + matchOff += 8; + dOff += 8; + } while (dOff < matchCopyEnd); + } +} diff --git a/src/java/net/jpountz/util/SafeUtils.java b/src/java/net/jpountz/util/SafeUtils.java index 1cbead11..26380a52 100644 --- a/src/java/net/jpountz/util/SafeUtils.java +++ b/src/java/net/jpountz/util/SafeUtils.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import java.nio.ByteOrder; - /** FOR INTERNAL USE ONLY */ public enum SafeUtils { ; @@ -47,29 +45,23 @@ public static byte readByte(byte[] buf, int i) { } public static int readIntBE(byte[] buf, int i) { - return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); + return ByteArrays.readIntBE(buf, i); } public static int readIntLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); + return ByteArrays.readIntLE(buf, i); } public static int readInt(byte[] buf, int i) { - if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { - return readIntBE(buf, i); - } else { - return readIntLE(buf, i); - } + return ByteArrays.readInt(buf, i); } public static long readLongLE(byte[] buf, int i) { - return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) - | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); + return ByteArrays.readLongLE(buf, i); } public static void writeShortLE(byte[] buf, int off, int v) { - buf[off++] = (byte) v; - buf[off++] = (byte) (v >>> 8); + ByteArrays.writeShortLE(buf, off, v); } public static void writeInt(int[] buf, int off, int v) { @@ -89,7 +81,7 @@ public static void writeShort(short[] buf, int off, int v) { } public static int readShortLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); + return ByteArrays.readShortLE(buf, i); } public static int readShort(short[] buf, int off) { diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java new file mode 100644 index 00000000..f94d9ad4 --- /dev/null +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -0,0 +1,127 @@ +package net.jpountz.util; + +/* + * Copyright 2020 Adrien Grand and the lz4-java contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; +import java.util.Arrays; + +/** + * FOR INTERNAL USE ONLY + *

+ * Java 9+ variant of src/java/net/jpountz/util/ByteArrays.java, loaded from META-INF/versions/9 of the multi-release + * jar. VarHandle views and Arrays.mismatch read, write and compare several bytes per bounds check. The copies follow + * LZ4UnsafeUtils, without Unsafe. + */ +public enum ByteArrays { + ; + + private static final VarHandle SHORT_LE = MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle INT_LE = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle INT_BE = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN); + private static final VarHandle INT = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.nativeOrder()); + private static final VarHandle LONG_LE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle LONG = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder()); + + public static int readShortLE(byte[] buf, int i) { + return (short) SHORT_LE.get(buf, i) & 0xFFFF; + } + + public static void writeShortLE(byte[] buf, int off, int v) { + SHORT_LE.set(buf, off, (short) v); + } + + public static int readIntBE(byte[] buf, int i) { + return (int) INT_BE.get(buf, i); + } + + public static int readIntLE(byte[] buf, int i) { + return (int) INT_LE.get(buf, i); + } + + /** Reads an int in native byte order. */ + public static int readInt(byte[] buf, int i) { + return (int) INT.get(buf, i); + } + + public static long readLongLE(byte[] buf, int i) { + return (long) LONG_LE.get(buf, i); + } + + /** Whether the 4 bytes at i equal the 4 bytes at j. */ + public static boolean readIntEquals(byte[] buf, int i, int j) { + return (int) INT.get(buf, i) == (int) INT.get(buf, j); + } + + public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + LONG.set(dest, dOff, (long) LONG.get(src, sOff)); + } + + /** The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. */ + public static int commonBytes(byte[] b, int o1, int o2, int limit) { + final int len = limit - o2; + if (len <= 0) { + return 0; + } + final int mismatch = Arrays.mismatch(b, o1, o1 + len, b, o2, limit); + return mismatch < 0 ? len : mismatch; + } + + /** + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap and + * matchOff < dOff. Writes up to 7 bytes past matchCopyEnd. + */ + public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { + // An 8-byte copy reads bytes it has not written yet while the distance is below 8. Write the start of the repeating + // pattern first, so that matchOff can trail dOff by a multiple of the pattern length of at least 8: 8 for distances + // 1 and 2, 9 for 3, and twice the distance for 4 to 7. + final int distance = dOff - matchOff; + assert distance > 0 : distance; + if (distance < 4) { + for (int i = 0; i < 4; ++i) { + dest[dOff + i] = dest[matchOff + i]; + } + int dec = 0; + switch (distance) { + case 1: + matchOff -= 3; + break; + case 2: + matchOff -= 2; + break; + case 3: + matchOff -= 3; + dec = -1; + break; + } + dOff += 4; + matchOff += 4; + INT.set(dest, dOff, (int) INT.get(dest, matchOff)); + dOff += 4; + matchOff -= dec; + } else if (distance < 8) { + copy8Bytes(dest, matchOff, dest, dOff); + dOff += distance; + } + while (dOff < matchCopyEnd) { + copy8Bytes(dest, matchOff, dest, dOff); + dOff += 8; + matchOff += 8; + } + } +} diff --git a/src/test/net/jpountz/lz4/OverlappingMatchTest.java b/src/test/net/jpountz/lz4/OverlappingMatchTest.java new file mode 100644 index 00000000..4c4b2572 --- /dev/null +++ b/src/test/net/jpountz/lz4/OverlappingMatchTest.java @@ -0,0 +1,83 @@ +package net.jpountz.lz4; + +/* + * Copyright 2026 Jonas Konrad and the lz4-java contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; + +import static net.jpountz.lz4.Instances.FAST_DECOMPRESSORS; +import static net.jpountz.lz4.Instances.SAFE_DECOMPRESSORS; +import static net.jpountz.lz4.LZ4Constants.MIN_MATCH; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A match whose distance is shorter than its length repeats a pattern. The decompressors copy matches in 4 and 8 byte + * steps, which must not read bytes before they are written. + */ +public class OverlappingMatchTest { + private static final int LITERALS = 12; + private static final int TRAILING_LITERALS = 12; + + @Test + public void overlappingMatches() { + for (int distance = 1; distance <= LITERALS; distance++) { + for (int matchLen = MIN_MATCH; matchLen <= 40; matchLen++) { + byte[] expected = expected(distance, matchLen); + byte[] block = block(expected, distance, matchLen); + String what = "distance " + distance + ", match length " + matchLen + ", "; + for (LZ4SafeDecompressor decompressor : SAFE_DECOMPRESSORS) { + byte[] out = new byte[expected.length]; + assertEquals(expected.length, decompressor.decompress(block, 0, block.length, out, 0, out.length)); + assertArrayEquals(expected, out, what + decompressor); + } + for (LZ4FastDecompressor decompressor : FAST_DECOMPRESSORS) { + byte[] out = new byte[expected.length]; + assertEquals(block.length, decompressor.decompress(block, 0, out, 0, out.length)); + assertArrayEquals(expected, out, what + decompressor); + } + } + } + } + + /** LITERALS distinct bytes, the match expanded one byte at a time, then TRAILING_LITERALS more bytes. */ + private static byte[] expected(int distance, int matchLen) { + byte[] out = new byte[LITERALS + matchLen + TRAILING_LITERALS]; + for (int i = 0; i < out.length; i++) { + boolean inMatch = i >= LITERALS && i < LITERALS + matchLen; + out[i] = inMatch ? out[i - distance] : (byte) (i + 1); + } + return out; + } + + /** One sequence with the literals and the match, then a last sequence with only the trailing literals. */ + private static byte[] block(byte[] expected, int distance, int matchLen) { + ByteArrayOutputStream block = new ByteArrayOutputStream(); + int extraMatchLen = matchLen - MIN_MATCH; + block.write(LITERALS << 4 | Math.min(extraMatchLen, 15)); + block.write(expected, 0, LITERALS); + block.write(distance); + block.write(distance >>> 8); + if (extraMatchLen >= 15) { + block.write(extraMatchLen - 15); + } + block.write(TRAILING_LITERALS << 4); + block.write(expected, LITERALS + matchLen, TRAILING_LITERALS); + return block.toByteArray(); + } +} diff --git a/src/test/net/jpountz/util/MultiReleaseJarTest.java b/src/test/net/jpountz/util/MultiReleaseJarTest.java new file mode 100644 index 00000000..d1f9f2a1 --- /dev/null +++ b/src/test/net/jpountz/util/MultiReleaseJarTest.java @@ -0,0 +1,117 @@ +package net.jpountz.util; + +/* + * Copyright 2026 Jonas Konrad and the lz4-java contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.junit.jupiter.api.Test; + +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * The failsafe execution sets lz4.testJar and runs the tests against the multi-release jar. There ByteArrays must be + * the Java 9 variant, or that run tests the Java 7 class a second time. + */ +public class MultiReleaseJarTest { + private static final int JAVA_9_CLASS_FILE = 53; + + @Test + public void jarServesJava9ByteArrays() throws Exception { + assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); + assertEquals(JAVA_9_CLASS_FILE, classFileMajorVersion(ByteArrays.class)); + } + + /** Code compiles against the Java 7 ByteArrays, so a method missing from the Java 9 one fails only at run time. */ + @Test + public void java9ByteArraysHasTheSameMethods() throws Exception { + assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); + byte[] java7Class; + // Without a runtime version, JarFile returns the base entry rather than the META-INF/versions/9 one. + try (JarFile jarFile = new JarFile(jar()); + InputStream in = jarFile.getInputStream(jarFile.getEntry("net/jpountz/util/ByteArrays.class"))) { + java7Class = in.readAllBytes(); + } + class Java7Loader extends ClassLoader { + Java7Loader() { + super(null); + } + + Class define() { + return defineClass(ByteArrays.class.getName(), java7Class, 0, java7Class.length); + } + } + assertEquals(publicMethods(new Java7Loader().define()), publicMethods(ByteArrays.class)); + } + + private static Set publicMethods(Class c) { + return Arrays.stream(c.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers())) + .map(Method::toString) + .collect(Collectors.toCollection(TreeSet::new)); + } + + /** + * Felix and Equinox refuse to resolve a bundle with an empty manifest header. bnd writes an empty Require-Capability + * into META-INF/versions/9/OSGI-INF/MANIFEST.MF unless lz4-java.bnd disables those per-release manifests. + */ + @Test + public void manifestsHaveNoEmptyHeaders() throws Exception { + assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); + try (JarFile jarFile = new JarFile(jar())) { + for (Enumeration entries = jarFile.entries(); entries.hasMoreElements(); ) { + JarEntry entry = entries.nextElement(); + if (!entry.getName().endsWith("MANIFEST.MF")) { + continue; + } + try (InputStream in = jarFile.getInputStream(entry)) { + for (Map.Entry header : new Manifest(in).getMainAttributes().entrySet()) { + assertFalse(header.getValue().toString().trim().isEmpty(), entry.getName() + ": empty " + header.getKey()); + } + } + } + } + } + + private static File jar() throws Exception { + return new File(ByteArrays.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + } + + private static int classFileMajorVersion(Class c) throws IOException { + try (InputStream resource = c.getResourceAsStream(c.getSimpleName() + ".class"); + DataInputStream in = new DataInputStream(resource)) { + in.readInt(); // magic + in.readUnsignedShort(); // minor version + return in.readUnsignedShort(); + } + } +} From 7d9d99a4b09fe4e022fe66fde8b824a595f1f473 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:53:13 +0100 Subject: [PATCH 02/16] Check non-public ByteArrays members in MultiReleaseJarTest The test compared only public methods, so a package-private method or a field added to the Java 7 ByteArrays but missing from the Java 9 one passed the test and then failed with NoSuchMethodError or NoSuchFieldError on Java 9+. Compare all methods and fields that other classes can reach, that is everything except private and synthetic members. Co-Authored-By: Claude Opus 5.5 --- .../net/jpountz/util/MultiReleaseJarTest.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/test/net/jpountz/util/MultiReleaseJarTest.java b/src/test/net/jpountz/util/MultiReleaseJarTest.java index d1f9f2a1..12be074e 100644 --- a/src/test/net/jpountz/util/MultiReleaseJarTest.java +++ b/src/test/net/jpountz/util/MultiReleaseJarTest.java @@ -22,7 +22,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Method; +import java.lang.reflect.Member; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Enumeration; @@ -33,6 +33,7 @@ import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -51,9 +52,12 @@ public void jarServesJava9ByteArrays() throws Exception { assertEquals(JAVA_9_CLASS_FILE, classFileMajorVersion(ByteArrays.class)); } - /** Code compiles against the Java 7 ByteArrays, so a method missing from the Java 9 one fails only at run time. */ + /** + * Code compiles against the Java 7 ByteArrays, so a method or field missing from the Java 9 one fails only at run + * time. Private and synthetic members are not reachable from other classes and may differ. + */ @Test - public void java9ByteArraysHasTheSameMethods() throws Exception { + public void java9ByteArraysHasTheSameMembers() throws Exception { assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); byte[] java7Class; // Without a runtime version, JarFile returns the base entry rather than the META-INF/versions/9 one. @@ -70,13 +74,13 @@ Class define() { return defineClass(ByteArrays.class.getName(), java7Class, 0, java7Class.length); } } - assertEquals(publicMethods(new Java7Loader().define()), publicMethods(ByteArrays.class)); + assertEquals(accessibleMembers(new Java7Loader().define()), accessibleMembers(ByteArrays.class)); } - private static Set publicMethods(Class c) { - return Arrays.stream(c.getDeclaredMethods()) - .filter(m -> Modifier.isPublic(m.getModifiers())) - .map(Method::toString) + private static Set accessibleMembers(Class c) { + return Stream.concat(Arrays.stream(c.getDeclaredMethods()), Arrays.stream(c.getDeclaredFields())) + .filter(m -> !Modifier.isPrivate(m.getModifiers()) && !m.isSynthetic()) + .map(Member::toString) .collect(Collectors.toCollection(TreeSet::new)); } From ef3340337333e02bc8cbcfe6d30c4cd21a465bda Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:53:28 +0100 Subject: [PATCH 03/16] Make the ByteArrays helpers used only by SafeUtils package-private readShortLE, writeShortLE, readIntBE, readIntLE, readInt and readLongLE are called only from SafeUtils in the same package, and SafeUtils already exposes them. Public, they would become a second copy of that API on an exported type that could only be deprecated, never removed. MultiReleaseJarTest now also compares package-private members, so the two variants are still checked against each other. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/util/ByteArrays.java | 12 ++++++------ src/java9/net/jpountz/util/ByteArrays.java | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/java/net/jpountz/util/ByteArrays.java b/src/java/net/jpountz/util/ByteArrays.java index 1bfa1470..cfcd1ce4 100644 --- a/src/java/net/jpountz/util/ByteArrays.java +++ b/src/java/net/jpountz/util/ByteArrays.java @@ -28,25 +28,25 @@ public enum ByteArrays { ; - public static int readShortLE(byte[] buf, int i) { + static int readShortLE(byte[] buf, int i) { return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); } - public static void writeShortLE(byte[] buf, int off, int v) { + static void writeShortLE(byte[] buf, int off, int v) { buf[off++] = (byte) v; buf[off++] = (byte) (v >>> 8); } - public static int readIntBE(byte[] buf, int i) { + static int readIntBE(byte[] buf, int i) { return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); } - public static int readIntLE(byte[] buf, int i) { + static int readIntLE(byte[] buf, int i) { return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); } /** Reads an int in native byte order. */ - public static int readInt(byte[] buf, int i) { + static int readInt(byte[] buf, int i) { if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { return readIntBE(buf, i); } else { @@ -54,7 +54,7 @@ public static int readInt(byte[] buf, int i) { } } - public static long readLongLE(byte[] buf, int i) { + static long readLongLE(byte[] buf, int i) { return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); } diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java index f94d9ad4..eb1ca313 100644 --- a/src/java9/net/jpountz/util/ByteArrays.java +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -38,28 +38,28 @@ public enum ByteArrays { private static final VarHandle LONG_LE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN); private static final VarHandle LONG = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder()); - public static int readShortLE(byte[] buf, int i) { + static int readShortLE(byte[] buf, int i) { return (short) SHORT_LE.get(buf, i) & 0xFFFF; } - public static void writeShortLE(byte[] buf, int off, int v) { + static void writeShortLE(byte[] buf, int off, int v) { SHORT_LE.set(buf, off, (short) v); } - public static int readIntBE(byte[] buf, int i) { + static int readIntBE(byte[] buf, int i) { return (int) INT_BE.get(buf, i); } - public static int readIntLE(byte[] buf, int i) { + static int readIntLE(byte[] buf, int i) { return (int) INT_LE.get(buf, i); } /** Reads an int in native byte order. */ - public static int readInt(byte[] buf, int i) { + static int readInt(byte[] buf, int i) { return (int) INT.get(buf, i); } - public static long readLongLE(byte[] buf, int i) { + static long readLongLE(byte[] buf, int i) { return (long) LONG_LE.get(buf, i); } From a78544981c57f4aac1da005277a1e1e230d48ef1 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:53:41 +0100 Subject: [PATCH 04/16] Guard MultiReleaseJarTest with one @EnabledIfSystemProperty Each of the three tests repeated the same assumeTrue on lz4.testJar. A class-level @EnabledIfSystemProperty says it once and reports the tests as disabled with the reason, not as aborted. Co-Authored-By: Claude Opus 5.5 --- src/test/net/jpountz/util/MultiReleaseJarTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/test/net/jpountz/util/MultiReleaseJarTest.java b/src/test/net/jpountz/util/MultiReleaseJarTest.java index 12be074e..43bab43f 100644 --- a/src/test/net/jpountz/util/MultiReleaseJarTest.java +++ b/src/test/net/jpountz/util/MultiReleaseJarTest.java @@ -17,6 +17,7 @@ */ import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import java.io.DataInputStream; import java.io.File; @@ -37,18 +38,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * The failsafe execution sets lz4.testJar and runs the tests against the multi-release jar. There ByteArrays must be * the Java 9 variant, or that run tests the Java 7 class a second time. */ +@EnabledIfSystemProperty(named = "lz4.testJar", matches = "true", disabledReason = "only runs against the packaged jar") public class MultiReleaseJarTest { private static final int JAVA_9_CLASS_FILE = 53; @Test public void jarServesJava9ByteArrays() throws Exception { - assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); assertEquals(JAVA_9_CLASS_FILE, classFileMajorVersion(ByteArrays.class)); } @@ -58,7 +58,6 @@ public void jarServesJava9ByteArrays() throws Exception { */ @Test public void java9ByteArraysHasTheSameMembers() throws Exception { - assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); byte[] java7Class; // Without a runtime version, JarFile returns the base entry rather than the META-INF/versions/9 one. try (JarFile jarFile = new JarFile(jar()); @@ -90,7 +89,6 @@ private static Set accessibleMembers(Class c) { */ @Test public void manifestsHaveNoEmptyHeaders() throws Exception { - assumeTrue(Boolean.getBoolean("lz4.testJar"), "only runs against the packaged jar"); try (JarFile jarFile = new JarFile(jar())) { for (Enumeration entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); From 623a27097d634c9f1cd252d68d54ddb3c1786fcc Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:54:09 +0100 Subject: [PATCH 05/16] Reuse LZ4Test.assertAllDecode in OverlappingMatchTest OverlappingMatchTest repeated the decode-and-compare loop of LZ4Test.assertAllDecode. Use that helper instead. It also decodes into a destination 64 bytes larger than needed and through the ByteBuffer methods, which covers the match copies that write past the end of the match while there is room for it. Co-Authored-By: Claude Opus 5.5 --- src/test/net/jpountz/lz4/LZ4Test.java | 2 +- .../net/jpountz/lz4/OverlappingMatchTest.java | 23 ++++++++----------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/test/net/jpountz/lz4/LZ4Test.java b/src/test/net/jpountz/lz4/LZ4Test.java index 8ad6fc2d..317d0469 100644 --- a/src/test/net/jpountz/lz4/LZ4Test.java +++ b/src/test/net/jpountz/lz4/LZ4Test.java @@ -375,7 +375,7 @@ private static void assertAllReject(byte[] block, int maxDestLen, int destLen) { * Asserts that every decompressor decodes {@code block} to the same {@code decompressedLen} bytes, with an * exact-size destination and with a larger one. */ - private static void assertAllDecode(byte[] block, int decompressedLen) { + static void assertAllDecode(byte[] block, int decompressedLen) { final byte[] expected = LZ4Factory.safeInstance().safeDecompressor().decompress(block, decompressedLen); assertEquals(decompressedLen, expected.length); for (LZ4SafeDecompressor decompressor : SAFE_DECOMPRESSORS) { diff --git a/src/test/net/jpountz/lz4/OverlappingMatchTest.java b/src/test/net/jpountz/lz4/OverlappingMatchTest.java index 4c4b2572..bc0f66df 100644 --- a/src/test/net/jpountz/lz4/OverlappingMatchTest.java +++ b/src/test/net/jpountz/lz4/OverlappingMatchTest.java @@ -20,15 +20,13 @@ import java.io.ByteArrayOutputStream; -import static net.jpountz.lz4.Instances.FAST_DECOMPRESSORS; -import static net.jpountz.lz4.Instances.SAFE_DECOMPRESSORS; import static net.jpountz.lz4.LZ4Constants.MIN_MATCH; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; /** * A match whose distance is shorter than its length repeats a pattern. The decompressors copy matches in 4 and 8 byte - * steps, which must not read bytes before they are written. + * steps, which must not read bytes before they are written. Every decompressor must decode each block to the expected + * bytes, into an exact-size destination and into a larger one. */ public class OverlappingMatchTest { private static final int LITERALS = 12; @@ -40,16 +38,13 @@ public void overlappingMatches() { for (int matchLen = MIN_MATCH; matchLen <= 40; matchLen++) { byte[] expected = expected(distance, matchLen); byte[] block = block(expected, distance, matchLen); - String what = "distance " + distance + ", match length " + matchLen + ", "; - for (LZ4SafeDecompressor decompressor : SAFE_DECOMPRESSORS) { - byte[] out = new byte[expected.length]; - assertEquals(expected.length, decompressor.decompress(block, 0, block.length, out, 0, out.length)); - assertArrayEquals(expected, out, what + decompressor); - } - for (LZ4FastDecompressor decompressor : FAST_DECOMPRESSORS) { - byte[] out = new byte[expected.length]; - assertEquals(block.length, decompressor.decompress(block, 0, out, 0, out.length)); - assertArrayEquals(expected, out, what + decompressor); + String what = "distance " + distance + ", match length " + matchLen; + assertArrayEquals(expected, LZ4Factory.safeInstance().safeDecompressor().decompress(block, expected.length), + what); + try { + LZ4Test.assertAllDecode(block, expected.length); + } catch (AssertionError e) { + throw new AssertionError(what, e); } } } From d0cc8b41371f83be0a0d32ab87ce96994b172edf Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:54:27 +0100 Subject: [PATCH 06/16] Simplify the short-distance case of the Java 9 wildIncrementalCopy The switch on distances 1 to 3 moved matchOff back and forth and kept a separate dec variable. The net effect is two small adjustments: the second 4-byte copy reads from matchOff + 2 for distance 2 and from matchOff + 1 otherwise, and distance 3 then moves on by one more byte so that matchOff trails dOff by 9. Write that directly. Co-Authored-By: Claude Opus 5.5 --- src/java9/net/jpountz/util/ByteArrays.java | 23 ++++++---------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java index eb1ca313..292b2f67 100644 --- a/src/java9/net/jpountz/util/ByteArrays.java +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -96,24 +96,13 @@ public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int for (int i = 0; i < 4; ++i) { dest[dOff + i] = dest[matchOff + i]; } - int dec = 0; - switch (distance) { - case 1: - matchOff -= 3; - break; - case 2: - matchOff -= 2; - break; - case 3: - matchOff -= 3; - dec = -1; - break; + // The next 4 bytes continue the pattern from matchOff + 1 (distances 1 and 3) or matchOff + 2 (distance 2). + matchOff += distance == 2 ? 2 : 1; + INT.set(dest, dOff + 4, (int) INT.get(dest, matchOff)); + dOff += 8; + if (distance == 3) { + ++matchOff; } - dOff += 4; - matchOff += 4; - INT.set(dest, dOff, (int) INT.get(dest, matchOff)); - dOff += 4; - matchOff -= dec; } else if (distance < 8) { copy8Bytes(dest, matchOff, dest, dOff); dOff += distance; From af83040fc0c36013b8fa1cd85322618e7fd5f5f7 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:54:53 +0100 Subject: [PATCH 07/16] Document where the two ByteArrays variants may differ Both variants agree for every argument the library passes, but not outside of that: the Java 9 copy8Bytes reads all 8 bytes before writing, readIntEquals and commonBytes check their whole range up front, and wildIncrementalCopy writes different bytes past the end of the match. Write down the preconditions on both copies, so that a new caller does not rely on behaviour that only one variant has. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/util/ByteArrays.java | 16 ++++++++++++---- src/java9/net/jpountz/util/ByteArrays.java | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/java/net/jpountz/util/ByteArrays.java b/src/java/net/jpountz/util/ByteArrays.java index cfcd1ce4..b1cfecaa 100644 --- a/src/java/net/jpountz/util/ByteArrays.java +++ b/src/java/net/jpountz/util/ByteArrays.java @@ -59,18 +59,25 @@ static long readLongLE(byte[] buf, int i) { | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); } - /** Whether the 4 bytes at i equal the 4 bytes at j. */ + /** Whether the 4 bytes at i equal the 4 bytes at j. All 8 bytes must be in bounds. */ public static boolean readIntEquals(byte[] buf, int i, int j) { return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; } + /** + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest are + * the same array: the Java 7 variant copies one byte at a time, the Java 9 variant reads all 8 bytes first. + */ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { for (int i = 0; i < 8; ++i) { dest[dOff + i] = src[sOff + i]; } } - /** The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. */ + /** + * The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. Requires o1 < o2 and + * limit <= b.length: the Java 9 variant checks the whole range up front, not only the bytes it compares. + */ public static int commonBytes(byte[] b, int o1, int o2, int limit) { int count = 0; while (o2 < limit && b[o1++] == b[o2++]) { @@ -80,8 +87,9 @@ public static int commonBytes(byte[] b, int o1, int o2, int limit) { } /** - * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap and - * matchOff < dOff. Writes up to 7 bytes past matchCopyEnd. + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap. Requires + * matchOff < dOff and matchCopyEnd - dOff >= 4 (the minimum match length), and writes up to 7 bytes past + * matchCopyEnd, which must be in bounds. The bytes written past matchCopyEnd differ between the variants. */ public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { do { diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java index 292b2f67..44cb3fec 100644 --- a/src/java9/net/jpountz/util/ByteArrays.java +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -63,16 +63,23 @@ static long readLongLE(byte[] buf, int i) { return (long) LONG_LE.get(buf, i); } - /** Whether the 4 bytes at i equal the 4 bytes at j. */ + /** Whether the 4 bytes at i equal the 4 bytes at j. All 8 bytes must be in bounds. */ public static boolean readIntEquals(byte[] buf, int i, int j) { return (int) INT.get(buf, i) == (int) INT.get(buf, j); } + /** + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest are + * the same array: the Java 7 variant copies one byte at a time, the Java 9 variant reads all 8 bytes first. + */ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { LONG.set(dest, dOff, (long) LONG.get(src, sOff)); } - /** The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. */ + /** + * The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. Requires o1 < o2 and + * limit <= b.length: the Java 9 variant checks the whole range up front, not only the bytes it compares. + */ public static int commonBytes(byte[] b, int o1, int o2, int limit) { final int len = limit - o2; if (len <= 0) { @@ -83,8 +90,9 @@ public static int commonBytes(byte[] b, int o1, int o2, int limit) { } /** - * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap and - * matchOff < dOff. Writes up to 7 bytes past matchCopyEnd. + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap. Requires + * matchOff < dOff and matchCopyEnd - dOff >= 4 (the minimum match length), and writes up to 7 bytes past + * matchCopyEnd, which must be in bounds. The bytes written past matchCopyEnd differ between the variants. */ public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { // An 8-byte copy reads bytes it has not written yet while the distance is below 8. Write the start of the repeating From 4d84d444877d6bb14a32f93b607656b80b2731d8 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:59:12 +0100 Subject: [PATCH 08/16] Compare one word before Arrays.mismatch in the Java 9 commonBytes Most calls of commonBytes end within a few bytes: on Calgary book1, 61% return 0 and 99.8% return 7 or less. Arrays.mismatch has a fixed setup cost per call, so the HC compressor gained nothing on text. Compare the first 8 bytes as one long and call Arrays.mismatch only past them, and use a byte loop when fewer than 8 bytes are left. JDK 25 on x86-64, Calgary book1 in 64 KiB blocks, MB/s: base PR this fast 169 187 241 HC 9 19.9 19.9 25.1 HC 17 19.8 19.5 24.5 geo improves by 2-5%. Under C1 (-XX:TieredStopAtLevel=1) HC on book1 goes from 11.3 to 12.3 MB/s, still below the 13.8 of the byte loop. Co-Authored-By: Claude Opus 5.5 --- src/java9/net/jpountz/util/ByteArrays.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java index 44cb3fec..b7d368c3 100644 --- a/src/java9/net/jpountz/util/ByteArrays.java +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -82,11 +82,20 @@ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { */ public static int commonBytes(byte[] b, int o1, int o2, int limit) { final int len = limit - o2; - if (len <= 0) { - return 0; + if (len < 8) { + int count = 0; + while (count < len && b[o1 + count] == b[o2 + count]) { + ++count; + } + return count; + } + // Most matches end within a few bytes, so compare one word before paying for the setup of Arrays.mismatch. + final long diff = (long) LONG_LE.get(b, o1) ^ (long) LONG_LE.get(b, o2); + if (diff != 0) { + return Long.numberOfTrailingZeros(diff) >>> 3; } - final int mismatch = Arrays.mismatch(b, o1, o1 + len, b, o2, limit); - return mismatch < 0 ? len : mismatch; + final int mismatch = Arrays.mismatch(b, o1 + 8, o1 + len, b, o2 + 8, limit); + return mismatch < 0 ? len : 8 + mismatch; } /** From d33cc84acb6c9d827da718ee5b0cbe07425966a9 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 10:13:20 +0100 Subject: [PATCH 09/16] Use the byte loops in the Java 9 ByteArrays without unaligned access HotSpot ports that run with UseUnalignedAccesses off, such as 32-bit ARM and riscv64 on JDK 21, do not compile byte array VarHandle views and Arrays.mismatch to wide accesses. There the Java 9 variant was much slower than the byte loops it replaces. Utils.isUnalignedAccessAllowed() already lists the architectures with fast unaligned access, so fall back to the Java 7 byte loops everywhere else. The check is a static final boolean, so the JIT drops the unused branch. Emulated on JDK 25 x86-64 with -XX:-UseUnalignedAccesses -XX:-UseVectorizedMismatchIntrinsic -Dos.arch=riscv64, Calgary book1 in 64 KiB blocks, MB/s: base PR this fast 167 103 167 HC 9 20.4 11.3 19.5 safe decomp 538 227 506 xxhash64 3495 5926 3491 xxhash64 loses the gain the VarHandle reads still had in this emulation. On x86-64 the results are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/util/ByteArrays.java | 4 +- src/java9/net/jpountz/util/ByteArrays.java | 50 ++++++++++++++++++++-- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/java/net/jpountz/util/ByteArrays.java b/src/java/net/jpountz/util/ByteArrays.java index b1cfecaa..87081c9d 100644 --- a/src/java/net/jpountz/util/ByteArrays.java +++ b/src/java/net/jpountz/util/ByteArrays.java @@ -65,8 +65,8 @@ public static boolean readIntEquals(byte[] buf, int i, int j) { } /** - * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest are - * the same array: the Java 7 variant copies one byte at a time, the Java 9 variant reads all 8 bytes first. + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest + * are the same array: the Java 7 variant copies one byte at a time, the Java 9 variant may read all 8 bytes first. */ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { for (int i = 0; i < 8; ++i) { diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java index b7d368c3..dfe0656c 100644 --- a/src/java9/net/jpountz/util/ByteArrays.java +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -27,6 +27,10 @@ * Java 9+ variant of src/java/net/jpountz/util/ByteArrays.java, loaded from META-INF/versions/9 of the multi-release * jar. VarHandle views and Arrays.mismatch read, write and compare several bytes per bounds check. The copies follow * LZ4UnsafeUtils, without Unsafe. + *

+ * Where {@link Utils#isUnalignedAccessAllowed()} is false, HotSpot does not compile the VarHandle views and + * Arrays.mismatch to wide accesses, and they are slower than the byte loops of the Java 7 variant. There every method + * uses those byte loops instead. */ public enum ByteArrays { ; @@ -37,42 +41,74 @@ public enum ByteArrays { private static final VarHandle INT = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.nativeOrder()); private static final VarHandle LONG_LE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN); private static final VarHandle LONG = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder()); + private static final boolean UNALIGNED = Utils.isUnalignedAccessAllowed(); static int readShortLE(byte[] buf, int i) { + if (!UNALIGNED) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); + } return (short) SHORT_LE.get(buf, i) & 0xFFFF; } static void writeShortLE(byte[] buf, int off, int v) { + if (!UNALIGNED) { + buf[off] = (byte) v; + buf[off + 1] = (byte) (v >>> 8); + return; + } SHORT_LE.set(buf, off, (short) v); } static int readIntBE(byte[] buf, int i) { + if (!UNALIGNED) { + return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); + } return (int) INT_BE.get(buf, i); } static int readIntLE(byte[] buf, int i) { + if (!UNALIGNED) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); + } return (int) INT_LE.get(buf, i); } /** Reads an int in native byte order. */ static int readInt(byte[] buf, int i) { + if (!UNALIGNED) { + return Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN ? readIntBE(buf, i) : readIntLE(buf, i); + } return (int) INT.get(buf, i); } static long readLongLE(byte[] buf, int i) { + if (!UNALIGNED) { + return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) + | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) + | ((buf[i + 7] & 0xFFL) << 56); + } return (long) LONG_LE.get(buf, i); } /** Whether the 4 bytes at i equal the 4 bytes at j. All 8 bytes must be in bounds. */ public static boolean readIntEquals(byte[] buf, int i, int j) { + if (!UNALIGNED) { + return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + } return (int) INT.get(buf, i) == (int) INT.get(buf, j); } /** - * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest are - * the same array: the Java 7 variant copies one byte at a time, the Java 9 variant reads all 8 bytes first. + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest + * are the same array: the Java 7 variant copies one byte at a time, the Java 9 variant may read all 8 bytes first. */ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + if (!UNALIGNED) { + for (int i = 0; i < 8; ++i) { + dest[dOff + i] = src[sOff + i]; + } + return; + } LONG.set(dest, dOff, (long) LONG.get(src, sOff)); } @@ -82,7 +118,7 @@ public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { */ public static int commonBytes(byte[] b, int o1, int o2, int limit) { final int len = limit - o2; - if (len < 8) { + if (len < 8 || !UNALIGNED) { int count = 0; while (count < len && b[o1 + count] == b[o2 + count]) { ++count; @@ -107,6 +143,14 @@ public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int // An 8-byte copy reads bytes it has not written yet while the distance is below 8. Write the start of the repeating // pattern first, so that matchOff can trail dOff by a multiple of the pattern length of at least 8: 8 for distances // 1 and 2, 9 for 3, and twice the distance for 4 to 7. + if (!UNALIGNED) { + do { + copy8Bytes(dest, matchOff, dest, dOff); + matchOff += 8; + dOff += 8; + } while (dOff < matchCopyEnd); + return; + } final int distance = dOff - matchOff; assert distance > 0 : distance; if (distance < 4) { From 993aee40ac112f3c40f2720ca4454379a56833f1 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 10:14:01 +0100 Subject: [PATCH 10/16] Report coverage of the Java 9 ByteArrays The JaCoCo report excluded META-INF/versions, because one report cannot hold two classes of the same name. So the coverage summary and badge never showed untested branches of the class that Java 9+ users run, although the failsafe run already records probes for it. Add a second report with only META-INF/versions/9 in target/site/jacoco-java9, and sum both reports in the CI summary and the published badge. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 4 +++- docs/justfile | 3 ++- pom.xml | 15 ++++++++++++++- scripts/jacoco_summary.py | 13 +++++++------ 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a70bf6ee..2b51faaf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -62,4 +62,6 @@ jobs: verify - name: Summarize coverage if: matrix.coverage - run: python3 scripts/jacoco_summary.py target/site/jacoco/jacoco.csv >> "$GITHUB_STEP_SUMMARY" + run: >- + python3 scripts/jacoco_summary.py target/site/jacoco/jacoco.csv target/site/jacoco-java9/jacoco.csv + >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/justfile b/docs/justfile index 48a97b08..c043537d 100644 --- a/docs/justfile +++ b/docs/justfile @@ -115,7 +115,8 @@ rewrite-version-links: coverage: if [ -f ../target/site/jacoco/jacoco.csv ]; then \ cp -r ../target/site/jacoco '{{build}}/site/{{latest_version_name}}/coverage' && \ - python3 ../scripts/jacoco_summary.py ../target/site/jacoco/jacoco.csv --badge '{{build}}/site/{{latest_version_name}}/coverage/badge.json'; \ + cp -r ../target/site/jacoco-java9 '{{build}}/site/{{latest_version_name}}/coverage/java9' && \ + python3 ../scripts/jacoco_summary.py ../target/site/jacoco/jacoco.csv ../target/site/jacoco-java9/jacoco.csv --badge '{{build}}/site/{{latest_version_name}}/coverage/badge.json'; \ fi prepare: diff --git a/pom.xml b/pom.xml index e81bd1ad..5bcb6238 100644 --- a/pom.xml +++ b/pom.xml @@ -406,12 +406,25 @@ report - + META-INF/versions/** + + report-java9 + verify + + report + + + + META-INF/versions/9/** + + ${project.reporting.outputDirectory}/jacoco-java9 + + diff --git a/scripts/jacoco_summary.py b/scripts/jacoco_summary.py index 672e7232..52d29250 100644 --- a/scripts/jacoco_summary.py +++ b/scripts/jacoco_summary.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Summarize line coverage from a JaCoCo CSV report. +"""Summarize line coverage from one or more JaCoCo CSV reports. Prints a Markdown summary line, and with --badge also writes a shields.io endpoint badge JSON file. """ @@ -8,15 +8,16 @@ import json parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument("csv", help="JaCoCo CSV report, e.g. target/site/jacoco/jacoco.csv") +parser.add_argument("csv", nargs="+", help="JaCoCo CSV reports, e.g. target/site/jacoco/jacoco.csv") parser.add_argument("--badge", help="write shields.io endpoint badge JSON to this file") args = parser.parse_args() missed = covered = 0 -with open(args.csv, newline="") as f: - for row in csv.DictReader(f): - missed += int(row["LINE_MISSED"]) - covered += int(row["LINE_COVERED"]) +for path in args.csv: + with open(path, newline="") as f: + for row in csv.DictReader(f): + missed += int(row["LINE_MISSED"]) + covered += int(row["LINE_COVERED"]) total = missed + covered pct = 100 * covered / total From f372c3add341052b84eca9e448210b5cf8929b8a Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 10:14:23 +0100 Subject: [PATCH 11/16] Run only the tests that reach ByteArrays against the jar The failsafe execution reran every test against the multi-release jar, which roughly doubled the test time on every CI leg: 88 s on x86-64, 136 s on aarch64 and 968 s on riscv64 in the PR's CI run. A large part of that is the stream tests, which mostly go through the JNI code via fastestInstance() and are not affected by the jar layout. Limit the rerun to the tests of the safe Java implementations, the xxhash tests, the fuzz regression tests and MultiReleaseJarTest. Co-Authored-By: Claude Opus 5.5 --- pom.xml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 5bcb6238..f38f0ed3 100644 --- a/pom.xml +++ b/pom.xml @@ -296,8 +296,9 @@ maven-surefire-plugin 3.6.1 - + org.apache.maven.plugins maven-failsafe-plugin @@ -312,7 +313,14 @@ - **/*Test.java + net/jpountz/util/MultiReleaseJarTest.java + net/jpountz/lz4/LZ4Test.java + net/jpountz/lz4/OutOfBoundsTest.java + net/jpountz/lz4/OverlappingMatchTest.java + net/jpountz/lz4/UtilsTest.java + net/jpountz/xxhash/XXHash32Test.java + net/jpountz/xxhash/XXHash64Test.java + net/jpountz/fuzz/*Test.java true From 058a596c388b89e2a6150373145f52ca9f865c0c Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 10:14:58 +0100 Subject: [PATCH 12/16] Keep surefire and failsafe at one shared version surefire and failsafe are released together, and the PR added failsafe with its own copy of the surefire version. Use one surefire.version property for both and for the fuzz profile, so an update cannot move them apart. fuzz_runner.py read the literal of surefire, so it now resolves a property reference there. Co-Authored-By: Claude Opus 5.5 --- pom.xml | 8 +++++--- scripts/fuzz_runner.py | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index f38f0ed3..e2093ad6 100644 --- a/pom.xml +++ b/pom.xml @@ -70,6 +70,8 @@ 7.5.0 + + 3.6.1 ${project.version} ${project.version} @@ -294,7 +296,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.6.1 + ${surefire.version}