[Git][java-team/zstd-jni-java][master] 7 commits: New upstream version 1.5.7-24+ds
Emmanuel Bourg (@ebourg)
gitlab at salsa.debian.org
Wed Nov 11 00:59:12 GMT 2026
Emmanuel Bourg pushed to branch master at Debian Java Maintainers / zstd-jni-java
Commits:
7ed721ce by Emmanuel Bourg at 2026-11-10T23:00:21+01:00
New upstream version 1.5.7-24+ds
- - - - -
117fc9b2 by Emmanuel Bourg at 2026-11-10T23:00:22+01:00
New upstream version 1.5.7-25+ds
- - - - -
9654c5e0 by Emmanuel Bourg at 2026-11-10T23:00:22+01:00
New upstream version 1.5.7-26+ds
- - - - -
87ab6aea by Emmanuel Bourg at 2026-11-10T23:07:07+01:00
Update upstream source from tag 'upstream/1.5.7-26+ds'
- - - - -
42219aa0 by Emmanuel Bourg at 2026-11-10T23:07:07+01:00
Refreshed the patches
- - - - -
3aafd9a2 by Emmanuel Bourg at 2026-11-10T23:07:07+01:00
Updated debian/libzstd-jni1.symbols
- - - - -
c47df355 by Emmanuel Bourg at 2026-11-10T23:07:14+01:00
Upload to unstable
- - - - -
28 changed files:
- README.md
- build.sbt
- debian/changelog
- debian/libzstd-jni1.symbols
- debian/patches/use_public_zdict_api.patch
- libzstd-jni.so.exported
- libzstd-jni.so.map
- make_so.sh
- src/main/java/com/github/luben/zstd/BaseZstdBufferDecompressingStreamNoFinalizer.java
- src/main/java/com/github/luben/zstd/Zstd.java
- src/main/java/com/github/luben/zstd/ZstdCompressCtx.java
- src/main/java/com/github/luben/zstd/ZstdDecompressCtx.java
- src/main/java/com/github/luben/zstd/ZstdDictCompress.java
- + src/main/java/com/github/luben/zstd/ZstdDictContentType.java
- src/main/java/com/github/luben/zstd/ZstdDictDecompress.java
- src/main/java/com/github/luben/zstd/ZstdInputStream.java
- src/main/java/com/github/luben/zstd/ZstdInputStreamNoFinalizer.java
- src/main/java22/com/github/luben/zstd/Zstd.java
- src/main/java22/com/github/luben/zstd/ZstdBinding.java
- src/main/java22/com/github/luben/zstd/ZstdCompressCtx.java
- src/main/java22/com/github/luben/zstd/ZstdDecompressCtx.java
- src/main/java22/com/github/luben/zstd/ZstdDictCompress.java
- src/main/java22/com/github/luben/zstd/ZstdDictDecompress.java
- src/main/java22/com/github/luben/zstd/ZstdInputStreamNoFinalizer.java
- src/main/native/ffm_zstd.c
- src/main/native/jni_fast_zstd.c
- src/main/native/jni_zdict.c
- version
Changes:
=====================================
README.md
=====================================
@@ -117,7 +117,7 @@ Binary releases
The binary releases are architecture dependent because we are embedding the
native library in the provided Jar file. Currently they are built for
*linux-amd64*, *linux-i386*, *linux-aarch64*, *linux-armhf*, *linux-ppc64*,
-*linux-ppc64le*, *linux-mips64*, *linux-s390x*, *linux-riscv64*, *linux-loongarch64*,
+*linux-ppc64le*, *linux-s390x*, *linux-riscv64*, *linux-loongarch64*,
*win-amd64*, *win-x86*, *win-aarch64*, *darwin-x86_64* (MacOS X), *darwin-aarch64*,
*aix-ppc64*, *freebsd-amd64*, and *freebsd-i386*.
=====================================
build.sbt
=====================================
@@ -216,7 +216,6 @@ Compile / packageBin / packageOptions ++= Seq(
|linux/amd64/libzstd-jni-${version.value}.so;osname=Linux;processor=amd64,
|linux/arm/libzstd-jni-${version.value}.so;osname=Linux;processor=arm,
|linux/i386/libzstd-jni-${version.value}.so;osname=Linux;processor=i386,
- |linux/mips64/libzstd-jni-${version.value}.so;osname=Linux;processor=mips64,
|linux/loongarch64/libzstd-jni-${version.value}.so;osname=Linux;processor=loongarch64,
|linux/ppc64/libzstd-jni-${version.value}.so;osname=Linux;processor=ppc64,
|linux/ppc64le/libzstd-jni-${version.value}.so;osname=Linux;processor=ppc64le,
@@ -238,7 +237,6 @@ Compile / packageBin / packageOptions ++= Seq(
|linux.arm,
|linux.i386,
|linux.loongarch64,
- |linux.mips64,
|linux.ppc64,
|linux.ppc64le,
|linux.riscv64,
@@ -273,6 +271,71 @@ pomExtra := (
</developers>
)
+// CycloneDX SBOM
+// The jar has no runtime dependencies, but embeds the native zstd library,
+// which is invisible to Maven-based tooling.
+// Publishing an SBOM next to the jar lets consumers track it.
+val cyclonedxBom = taskKey[File]("Generates a CycloneDX SBOM")
+cyclonedxBom := {
+ val header = IO.read(file("src/main/native/zstd.h"))
+ def zstdMacro(name: String): String =
+ s"(?m)^#define\\s+ZSTD_VERSION_$name\\s+(\\d+)".r.findFirstMatchIn(header)
+ .getOrElse(sys.error(s"ZSTD_VERSION_$name not found in zstd.h")).group(1)
+ val zstdVersion = Seq("MAJOR", "MINOR", "RELEASE").map(zstdMacro).mkString(".")
+ val purl = s"pkg:maven/${organization.value}/${name.value}@${version.value}"
+ val zstdPurl = s"pkg:github/meta/zstd at v$zstdVersion"
+ val serialNumber = java.util.UUID.nameUUIDFromBytes(purl.getBytes("UTF-8"))
+ // sjson-new ships with sbt: building an AST guarantees well-formed, correctly escaped JSON
+ import sjsonnew.shaded.scalajson.ast.unsafe._
+ def obj(fields: (String, JValue)*): JValue = JObject(fields.map { case (k, v) => JField(k, v) }.toArray)
+ def arr(values: JValue*): JValue = JArray(values.toArray)
+ def str(value: String): JValue = JString(value)
+ val meta = obj("name" -> str("Meta Platforms, Inc."), "url" -> arr(str("https://github.com/meta")))
+ val bom = obj(
+ "$schema" -> str("http://cyclonedx.org/schema/bom-1.7.schema.json"),
+ "bomFormat" -> str("CycloneDX"),
+ "specVersion" -> str("1.7"),
+ "serialNumber" -> str(s"urn:uuid:$serialNumber"),
+ "version" -> JNumber(1),
+ "metadata" -> obj(
+ "component" -> obj(
+ "type" -> str("library"),
+ "bom-ref" -> str(purl),
+ "group" -> str(organization.value),
+ "name" -> str(name.value),
+ "version" -> str(version.value),
+ "description" -> str(description.value),
+ "licenses" -> arr(obj("license" -> obj("id" -> str("BSD-2-Clause"), "acknowledgement" -> str("declared")))),
+ "purl" -> str(purl),
+ "externalReferences" -> arr(obj("type" -> str("vcs"), "url" -> str("https://github.com/luben/zstd-jni")))
+ )
+ ),
+ "components" -> arr(
+ obj(
+ "type" -> str("library"),
+ "bom-ref" -> str(zstdPurl),
+ "supplier" -> meta,
+ "manufacturer" -> meta,
+ "name" -> str("Zstandard"),
+ "version" -> str(zstdVersion),
+ "description" -> str("Zstandard - Fast real-time compression algorithm (native library)"),
+ "licenses" -> arr(obj("expression" -> str("BSD-3-Clause OR GPL-2.0-only"), "acknowledgement" -> str("concluded"))),
+ "cpe" -> str(s"cpe:2.3:a:facebook:zstandard:$zstdVersion:*:*:*:*:*:*:*"),
+ "purl" -> str(zstdPurl),
+ "externalReferences" -> arr(obj("type" -> str("vcs"), "url" -> str("https://github.com/meta/zstd")))
+ )
+ ),
+ "dependencies" -> arr(
+ obj("ref" -> str(purl), "dependsOn" -> arr(str(zstdPurl))),
+ obj("ref" -> str(zstdPurl), "dependsOn" -> arr())
+ )
+ )
+ val out = target.value / s"${name.value}-${version.value}-cyclonedx.json"
+ IO.write(out, sjsonnew.support.scalajson.unsafe.PrettyPrinter(bom))
+ out
+}
+addArtifact(Artifact(nameValue, "json", "json", "cyclonedx"), cyclonedxBom)
+
// Jacoco coverage setting
jacocoReportSettings := JacocoReportSettings(
"Jacoco Coverage Report",
@@ -346,13 +409,6 @@ Linux_ppc64 / packageBin / mappings := {
}
addArtifact(Artifact(nameValue, "linux_ppc64"), Linux_ppc64 / packageBin)
-lazy val Linux_mips64 = config("linux_mips64").extend(Compile)
-inConfig(Linux_mips64)(Defaults.compileSettings)
-Linux_mips64 / packageBin / mappings := {
- (file(s"target/classes/linux/mips64/libzstd-jni-${version.value}.so"), s"linux/mips64/libzstd-jni-${version.value}.so") :: classes
-}
-addArtifact(Artifact(nameValue, "linux_mips64"), Linux_mips64 / packageBin)
-
lazy val Linux_loongarch64 = config("linux_loongarch64").extend(Compile)
inConfig(Linux_loongarch64)(Defaults.compileSettings)
Linux_loongarch64 / packageBin / mappings := {
@@ -442,7 +498,7 @@ addArtifact(Artifact(nameValue, "cloud"), Cloud / packageBin)
val classifiedConfigs = Seq(
Linux_amd64, Linux_i386, Linux_aarch64, Linux_arm, Linux_ppc64le, Linux_ppc64,
- Linux_mips64, Linux_loongarch64, Linux_s390x, Linux_riscv64, Aix_ppc64,
+ Linux_loongarch64, Linux_s390x, Linux_riscv64, Aix_ppc64,
Darwin_x86_64, Darwin_aarch64, FreeBSD_amd64, FreeBSD_i386,
Win_x86, Win_amd64, Win_aarch64, Cloud
)
=====================================
debian/changelog
=====================================
@@ -1,3 +1,12 @@
+zstd-jni-java (1.5.7-26+ds-1) unstable; urgency=medium
+
+ * Team upload
+ * New upstream release
+ - Refreshed the patches
+ - Updated debian/libzstd-jni1.symbols
+
+ -- Emmanuel Bourg <ebourg at apache.org> Tue, 10 Nov 2026 23:07:14 +0100
+
zstd-jni-java (1.5.7-23+ds-2) unstable; urgency=medium
* Team upload
=====================================
debian/libzstd-jni1.symbols
=====================================
@@ -14,7 +14,7 @@ libzstd-jni.so.1 libzstd-jni1 #MINVER#
Java_com_github_luben_zstd_ZstdCompressCtx_free at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdCompressCtx_getFrameProgression0 at Base 1.5.7-23+ds
Java_com_github_luben_zstd_ZstdCompressCtx_init at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdCompressCtx_loadCDict0 at Base 1.5.2-5+ds
+ Java_com_github_luben_zstd_ZstdCompressCtx_loadCDict0 at Base 1.5.7-26+ds
Java_com_github_luben_zstd_ZstdCompressCtx_loadCDictFast0 at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdCompressCtx_reset0 at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdCompressCtx_setChecksum0 at Base 1.5.2-5+ds
@@ -32,15 +32,15 @@ libzstd-jni.so.1 libzstd-jni1 #MINVER#
Java_com_github_luben_zstd_ZstdDecompressCtx_decompressDirectByteBufferToByteArrayStream0 at Base 1.5.7-23+ds
Java_com_github_luben_zstd_ZstdDecompressCtx_free at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdDecompressCtx_init at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDict0 at Base 1.5.2-5+ds
+ Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDict0 at Base 1.5.7-26+ds
Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDictFast0 at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdDecompressCtx_reset0 at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdDictCompress_free at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdDictCompress_init at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdDictCompress_initDirect at Base 1.5.7-23+ds
+ Java_com_github_luben_zstd_ZstdDictCompress_init at Base 1.5.7-26+ds
+ Java_com_github_luben_zstd_ZstdDictCompress_initDirect at Base 1.5.7-26+ds
Java_com_github_luben_zstd_ZstdDictDecompress_free at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdDictDecompress_init at Base 1.5.2-5+ds
- Java_com_github_luben_zstd_ZstdDictDecompress_initDirect at Base 1.5.7-23+ds
+ Java_com_github_luben_zstd_ZstdDictDecompress_init at Base 1.5.7-26+ds
+ Java_com_github_luben_zstd_ZstdDictDecompress_initDirect at Base 1.5.7-26+ds
Java_com_github_luben_zstd_ZstdDirectBufferCompressingStreamNoFinalizer_compressDirectByteBuffer at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdDirectBufferCompressingStreamNoFinalizer_createCStream at Base 1.5.2-5+ds
Java_com_github_luben_zstd_ZstdDirectBufferCompressingStreamNoFinalizer_endStream at Base 1.5.2-5+ds
@@ -184,10 +184,13 @@ libzstd-jni.so.1 libzstd-jni1 #MINVER#
zstd_java_c_targetLength at Base 1.5.7-23+ds
zstd_java_c_validateSequences at Base 1.5.7-23+ds
zstd_java_c_windowLog at Base 1.5.7-23+ds
+ zstd_java_createCDict at Base 1.5.7-26+ds
+ zstd_java_createDDict at Base 1.5.7-26+ds
zstd_java_d_format at Base 1.5.7-23+ds
zstd_java_d_refMultipleDDicts at Base 1.5.7-23+ds
zstd_java_d_windowLogMax at Base 1.5.7-23+ds
zstd_java_decompressedSize at Base 1.5.7-23+ds
+ zstd_java_dlm_byCopy at Base 1.5.7-26+ds
zstd_java_e_continue at Base 1.5.7-23+ds
zstd_java_e_end at Base 1.5.7-23+ds
zstd_java_e_flush at Base 1.5.7-23+ds
=====================================
debian/patches/use_public_zdict_api.patch
=====================================
@@ -12,7 +12,7 @@ Author: Emmanuel Bourg <ebourg at apache.org>
Forwarded: not-needed
--- a/src/main/native/jni_zdict.c
+++ b/src/main/native/jni_zdict.c
-@@ -55,7 +55,14 @@
+@@ -61,7 +61,14 @@
params.zParams.compressionLevel = compressionLevel;
size = ZDICT_trainFromBuffer_legacy(dict_buff, dict_capacity, samples_buffer, samples_sizes, num_samples, params);
} else {
@@ -28,7 +28,7 @@ Forwarded: not-needed
}
(*env)->ReleasePrimitiveArrayCritical(env, dictBuffer, dict_buff, 0);
-@@ -104,7 +111,14 @@
+@@ -110,7 +117,14 @@
params.zParams.compressionLevel = compressionLevel;
size = ZDICT_trainFromBuffer_legacy(dict_buff, dict_capacity, samples_buffer, samples_sizes, num_samples, params);
} else {
=====================================
libzstd-jni.so.exported
=====================================
@@ -3,6 +3,7 @@ _zstd_java_*
_ZDICT_trainFromBuffer
_ZDICT_trainFromBuffer_legacy
_ZSTD_CCtx_loadDictionary
+_ZSTD_CCtx_loadDictionary_advanced
_ZSTD_CCtx_refCDict
_ZSTD_CCtx_reset
_ZSTD_CCtx_setParameter
@@ -11,15 +12,12 @@ _ZSTD_compress2
_ZSTD_compressBound
_ZSTD_compressStream2_simpleArgs
_ZSTD_createCCtx
-_ZSTD_createCDict
-_ZSTD_createCDict_byReference
_ZSTD_createCStream
_ZSTD_createDCtx
-_ZSTD_createDDict
-_ZSTD_createDDict_byReference
_ZSTD_createDStream
_ZSTD_CStreamOutSize
_ZSTD_DCtx_loadDictionary
+_ZSTD_DCtx_loadDictionary_advanced
_ZSTD_DCtx_refDDict
_ZSTD_DCtx_reset
_ZSTD_DCtx_setParameter
=====================================
libzstd-jni.so.map
=====================================
@@ -1,4 +1,4 @@
LOCAL_ZSTD {
- global: Java_com_github_luben_zstd*; zstd_java_*; ZDICT_trainFromBuffer; ZDICT_trainFromBuffer_legacy; ZSTD_CCtx_loadDictionary; ZSTD_CCtx_refCDict; ZSTD_CCtx_reset; ZSTD_CCtx_setParameter; ZSTD_CCtx_setPledgedSrcSize; ZSTD_compress2; ZSTD_compressBound; ZSTD_compressStream2_simpleArgs; ZSTD_createCCtx; ZSTD_createCDict; ZSTD_createCDict_byReference; ZSTD_createCStream; ZSTD_createDCtx; ZSTD_createDDict; ZSTD_createDDict_byReference; ZSTD_createDStream; ZSTD_CStreamOutSize; ZSTD_DCtx_loadDictionary; ZSTD_DCtx_refDDict; ZSTD_DCtx_reset; ZSTD_DCtx_setParameter; ZSTD_decompress; ZSTD_decompressDCtx; ZSTD_decompressStream_simpleArgs; ZSTD_DStreamInSize; ZSTD_DStreamOutSize; ZSTD_findFrameCompressedSize; ZSTD_freeCCtx; ZSTD_freeCDict; ZSTD_freeCStream; ZSTD_freeDCtx; ZSTD_freeDDict; ZSTD_getDictID_fromDict; ZSTD_getDictID_fromFrame; ZSTD_getErrorCode; ZSTD_getErrorName; ZSTD_getFrameProgression; ZSTD_initCStream; ZSTD_initDStream; ZSTD_isError; ZSTD_maxCLevel; ZSTD_minCLevel; ZSTD_registerSequenceProducer;
+ global: Java_com_github_luben_zstd*; zstd_java_*; ZDICT_trainFromBuffer; ZDICT_trainFromBuffer_legacy; ZSTD_CCtx_loadDictionary; ZSTD_CCtx_loadDictionary_advanced; ZSTD_CCtx_refCDict; ZSTD_CCtx_reset; ZSTD_CCtx_setParameter; ZSTD_CCtx_setPledgedSrcSize; ZSTD_compress2; ZSTD_compressBound; ZSTD_compressStream2_simpleArgs; ZSTD_createCCtx; ZSTD_createCStream; ZSTD_createDCtx; ZSTD_createDStream; ZSTD_CStreamOutSize; ZSTD_DCtx_loadDictionary; ZSTD_DCtx_loadDictionary_advanced; ZSTD_DCtx_refDDict; ZSTD_DCtx_reset; ZSTD_DCtx_setParameter; ZSTD_decompress; ZSTD_decompressDCtx; ZSTD_decompressStream_simpleArgs; ZSTD_DStreamInSize; ZSTD_DStreamOutSize; ZSTD_findFrameCompressedSize; ZSTD_freeCCtx; ZSTD_freeCDict; ZSTD_freeCStream; ZSTD_freeDCtx; ZSTD_freeDDict; ZSTD_getDictID_fromDict; ZSTD_getDictID_fromFrame; ZSTD_getErrorCode; ZSTD_getErrorName; ZSTD_getFrameProgression; ZSTD_initCStream; ZSTD_initDStream; ZSTD_isError; ZSTD_maxCLevel; ZSTD_minCLevel; ZSTD_registerSequenceProducer;
local: *;
};
=====================================
make_so.sh
=====================================
@@ -16,6 +16,7 @@ compile () {
rsync ./libzstd-jni.so.map $HOST:
# fall-back to scp if rsync fails
if [[ $? != "0" ]]; then
+ ssh $HOST rm -rf jni native libzstd-jni.so.map
scp -r jni $HOST:
scp -r src/main/native $HOST:
scp ./libzstd-jni.so.map $HOST:
@@ -32,10 +33,15 @@ compile_aix() {
HOST="gcc-$ARCH-$OS"
echo "Compiling for $ARCH/$OS on $HOST"
INSTALL=target/classes/$OS/$ARCH
- ssh $HOST rm -rf jni native
- scp -r jni $HOST:
- scp -r src/main/native $HOST:
- ssh $HOST 'export PATH=$HOME/bin:/opt/freeware/bin:$PATH; '$CC' -shared -fPIC -O3 -DZSTD_MULTITHREAD=1 -I/usr/include -I./jni -I./native -I./native/common -std=c99 -lpthread -o libzstd-jni-'$VERSION'.so native/*.c native/common/*.c native/compress/*.c native/decompress/*.c native/dictBuilder/*.c'
+ rsync -r --delete --rsync-path=/opt/freeware/bin/rsync jni $HOST:
+ rsync -r --delete --rsync-path=/opt/freeware/bin/rsync src/main/native $HOST:
+ # fall-back to scp if rsync fails
+ if [[ $? != "0" ]]; then
+ ssh $HOST rm -rf jni native
+ scp -r jni $HOST:
+ scp -r src/main/native $HOST:
+ fi
+ ssh $HOST 'export PATH=$HOME/bin:/opt/freeware/bin:$PATH; '$CC' -maix64 -shared -fPIC -O3 -DZSTD_MULTITHREAD=1 -I/usr/include -I./jni -I./native -I./native/common -std=c99 -lpthread -o libzstd-jni-'$VERSION'.so native/*.c native/common/*.c native/compress/*.c native/decompress/*.c native/dictBuilder/*.c'
mkdir -p $INSTALL
scp $HOST:libzstd-jni-$VERSION.so $INSTALL
}
@@ -45,7 +51,7 @@ compile amd64 linux
compile ppc64 linux
compile ppc64le linux
compile aarch64 linux
-compile mips64 linux
+#compile mips64 linux
compile loongarch64 linux
compile amd64 freebsd "cc"
compile i386 freebsd "cc -m32 -march=i486 -mfancy-math-387"
=====================================
src/main/java/com/github/luben/zstd/BaseZstdBufferDecompressingStreamNoFinalizer.java
=====================================
@@ -105,6 +105,9 @@ public abstract class BaseZstdBufferDecompressingStreamNoFinalizer implements Cl
if (closed) {
throw new IOException("Stream closed");
}
+ if (target.isReadOnly()) {
+ throw new IllegalArgumentException("Target buffer should be writable");
+ }
if (streamEnd) {
return 0;
}
@@ -170,7 +173,7 @@ public abstract class BaseZstdBufferDecompressingStreamNoFinalizer implements Cl
* @param target buffer to store the read bytes from uncompressed stream.
* @return the number of bytes read into the target buffer.
* @throws ZstdIOException if an error occurs while reading.
- * @throws IllegalArgumentException if provided source or target buffers are incorrectly configured.
+ * @throws IllegalArgumentException if provided source or target buffers are incorrectly configured, or the target is read-only.
* @throws IOException if the stream is closed before reading.
*/
public abstract int read(@NotNull ByteBuffer target) throws IOException;
=====================================
src/main/java/com/github/luben/zstd/Zstd.java
=====================================
@@ -982,6 +982,16 @@ public class Zstd {
if (samples.length <= 10) {
throw new ZstdException(Zstd.errGeneric(), "nb of samples too low");
}
+ // FASTCOVER trains on the first ~75% of samples (d defaults to 8); if those sum to
+ // fewer than 8 bytes, nbDmers underflows in the vendored fastcover.c (meta/zstd#4499).
+ if (!legacy) {
+ int nbTrain = (int) (samples.length * 0.75);
+ long trainSize = 0;
+ for (int i = 0; i < nbTrain; i++) trainSize += samples[i].length;
+ if (trainSize < 8) {
+ throw new ZstdException(Zstd.errGeneric(), "training samples too small");
+ }
+ }
return trainFromBuffer0(samples, dictBuffer, legacy, compressionLevel);
}
private static native long trainFromBuffer0(byte @NotNull [][] samples, byte @NotNull [] dictBuffer, boolean legacy, int compressionLevel);
@@ -1018,6 +1028,16 @@ public class Zstd {
if (sampleSizes.length <= 10) {
throw new ZstdException(Zstd.errGeneric(), "nb of samples too low");
}
+ // FASTCOVER trains on the first ~75% of samples (d defaults to 8); if those sum to
+ // fewer than 8 bytes, nbDmers underflows in the vendored fastcover.c (meta/zstd#4499).
+ if (!legacy) {
+ int nbTrain = (int) (sampleSizes.length * 0.75);
+ long trainSize = 0;
+ for (int i = 0; i < nbTrain; i++) trainSize += sampleSizes[i];
+ if (trainSize < 8) {
+ throw new ZstdException(Zstd.errGeneric(), "training samples too small");
+ }
+ }
return trainFromBufferDirect0(samples, sampleSizes, dictBuffer, legacy, compressionLevel);
}
=====================================
src/main/java/com/github/luben/zstd/ZstdCompressCtx.java
=====================================
@@ -451,10 +451,25 @@ public class ZstdCompressCtx extends AutoCloseBase {
*/
@NotNull
public ZstdCompressCtx loadDict(byte @Nullable [] dict) {
+ return loadDict(dict, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Load compression dictionary to be used for subsequently compressed frames,
+ * interpreting its content as {@code type} says.
+ * A {@link ZstdDictContentType#FULL_DICT} that is not a valid dictionary is reported
+ * when compressing with it.
+ *
+ * @param dict the dictionary or `null` to remove loaded dictionary
+ * @param type how to interpret the content of the dictionary
+ */
+ @NotNull
+ public ZstdCompressCtx loadDict(byte @Nullable [] dict, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
ensureOpen();
acquireSharedLock();
try {
- long result = loadCDict0(nativePtr, dict);
+ long result = loadCDict0(nativePtr, dict, type.value());
if (Zstd.isError(result)) {
throw new ZstdException(result);
}
@@ -467,7 +482,7 @@ public class ZstdCompressCtx extends AutoCloseBase {
}
return this;
}
- private native long loadCDict0(long ptr, byte @Nullable [] dict);
+ private native long loadCDict0(long ptr, byte @Nullable [] dict, int dictContentType);
/**
* Tells how much data has been ingested (read from input),
=====================================
src/main/java/com/github/luben/zstd/ZstdDecompressCtx.java
=====================================
@@ -59,6 +59,30 @@ public class ZstdDecompressCtx extends AutoCloseBase {
return this;
}
+ /**
+ * Set the maximum window size the decompressor accepts, as a power of 2.
+ * Frames that need a larger window are rejected instead of decoded, which
+ * bounds the memory a frame header can make the decompressor allocate.
+ * Cleared by {@link #reset()}.
+ *
+ * @param windowLogMax Maximum window size, expressed as power of 2,
+ * default: 27 (ZSTD_WINDOWLOG_LIMIT_DEFAULT)
+ */
+ @NotNull
+ public ZstdDecompressCtx setLongMax(int windowLogMax) {
+ ensureOpen();
+ acquireSharedLock();
+ try {
+ long result = Zstd.setDecompressionLongMax(nativePtr, windowLogMax);
+ if (Zstd.isError(result)) {
+ throw new ZstdException(result);
+ }
+ } finally {
+ releaseSharedLock();
+ }
+ return this;
+ }
+
/**
* Load decompression dictionary
*
@@ -96,10 +120,22 @@ public class ZstdDecompressCtx extends AutoCloseBase {
*/
@NotNull
public ZstdDecompressCtx loadDict(byte @Nullable [] dict) {
+ return loadDict(dict, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Load decompression dictionary, interpreting its content as {@code type} says.
+ *
+ * @param dict the dictionary or `null` to remove loaded dictionary
+ * @param type how to interpret the content of the dictionary
+ */
+ @NotNull
+ public ZstdDecompressCtx loadDict(byte @Nullable [] dict, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
ensureOpen();
acquireSharedLock();
try {
- long result = loadDDict0(nativePtr, dict);
+ long result = loadDDict0(nativePtr, dict, type.value());
if (Zstd.isError(result)) {
throw new ZstdException(result);
}
@@ -113,7 +149,7 @@ public class ZstdDecompressCtx extends AutoCloseBase {
return this;
}
- private static native long loadDDict0(long nativePtr, byte @Nullable [] dict);
+ private static native long loadDDict0(long nativePtr, byte @Nullable [] dict, int dictContentType);
/**
* Clear all state and parameters from the decompression context. This leaves the object in a
=====================================
src/main/java/com/github/luben/zstd/ZstdDictCompress.java
=====================================
@@ -19,9 +19,10 @@ public class ZstdDictCompress extends SharedDictBase {
private int level = Zstd.defaultCompressionLevel();
- private native void init(byte @NotNull [] dict, int dict_offset, int dict_size, int level);
+ private native void init(byte @NotNull [] dict, int dict_offset, int dict_size, int level, int dictContentType);
- private native void initDirect(@NotNull ByteBuffer dict, int dict_offset, int dict_size, int level, int byReference);
+ private native void initDirect(@NotNull ByteBuffer dict, int dict_offset, int dict_size, int level, int byReference,
+ int dictContentType);
private native void free();
@@ -42,6 +43,17 @@ public class ZstdDictCompress extends SharedDictBase {
this(dict, 0, dict.length, level);
}
+ /**
+ * Convenience constructor to create a new dictionary for use with fast compress
+ *
+ * @param dict buffer containing dictionary to load/parse with exact length
+ * @param level compression level
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(byte @NotNull [] dict, int level, @NotNull ZstdDictContentType type) {
+ this(dict, 0, dict.length, level, type);
+ }
+
/**
* Create a new dictionary for use with fast compress
*
@@ -51,6 +63,24 @@ public class ZstdDictCompress extends SharedDictBase {
* @param level compression level
*/
public ZstdDictCompress(byte @NotNull [] dict, int offset, int length, int level) {
+ this(dict, offset, length, level, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast compress, interpreting its content as {@code type} says.
+ * A {@link ZstdDictContentType#RAW_CONTENT} dictionary that starts with the dictionary magic number
+ * is created with libzstd's advanced API, which fixes the compression parameters for {@code level}
+ * when the dictionary is created rather than adjusting them to the size of each input.
+ *
+ * @param dict buffer containing dictionary
+ * @param offset the offset into the buffer to read from
+ * @param length number of bytes to use from the buffer
+ * @param level compression level
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(byte @NotNull [] dict, int offset, int length, int level,
+ @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
this.level = level;
if (dict.length - offset < 0) {
throw new IllegalArgumentException("Dictionary buffer is too short");
@@ -58,7 +88,7 @@ public class ZstdDictCompress extends SharedDictBase {
if (offset < 0 || length < 0 || length > dict.length - offset) {
throw new IllegalArgumentException("Invalid offset/length for dictionary buffer");
}
- init(dict, offset, length, level);
+ init(dict, offset, length, level, type.value());
if (0 == nativePtr) {
throw new IllegalStateException("ZSTD_createCDict failed");
@@ -87,6 +117,24 @@ public class ZstdDictCompress extends SharedDictBase {
* @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
*/
public ZstdDictCompress(@NotNull ByteBuffer dict, int level, boolean byReference) {
+ this(dict, level, byReference, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast compress, interpreting its content as {@code type} says.
+ * If byReference is true, then the native code does not copy the data but keeps a reference to the byte buffer, which must then not be modified before this context has been closed.
+ * A {@link ZstdDictContentType#RAW_CONTENT} dictionary that starts with the dictionary magic number
+ * is created with libzstd's advanced API, which fixes the compression parameters for {@code level}
+ * when the dictionary is created rather than adjusting them to the size of each input.
+ *
+ * @param dict Direct ByteBuffer containing dictionary using position and limit to define range in buffer.
+ * @param level compression level
+ * @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(@NotNull ByteBuffer dict, int level, boolean byReference,
+ @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
this.level = level;
int length = dict.limit() - dict.position();
if (!dict.isDirect()) {
@@ -95,7 +143,7 @@ public class ZstdDictCompress extends SharedDictBase {
if (length < 0) {
throw new IllegalArgumentException("dict cannot be empty.");
}
- initDirect(dict, dict.position(), length, level, byReference ? 1 : 0);
+ initDirect(dict, dict.position(), length, level, byReference ? 1 : 0, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createCDict failed");
=====================================
src/main/java/com/github/luben/zstd/ZstdDictContentType.java
=====================================
@@ -0,0 +1,38 @@
+package com.github.luben.zstd;
+
+/**
+ * How the bytes of a dictionary are interpreted, mirroring libzstd's {@code ZSTD_dictContentType_e}.
+ *
+ * @see ZstdCompressCtx#loadDict(byte[], ZstdDictContentType)
+ * @see ZstdDecompressCtx#loadDict(byte[], ZstdDictContentType)
+ * @see ZstdDictCompress#ZstdDictCompress(byte[], int, int, int, ZstdDictContentType)
+ * @see ZstdDictDecompress#ZstdDictDecompress(byte[], int, int, ZstdDictContentType)
+ */
+public enum ZstdDictContentType {
+ /**
+ * The dictionary is a full Zstandard dictionary when it starts with the dictionary magic number
+ * ({@code 0xEC30A437}), and raw content otherwise. This is the default.
+ */
+ AUTO(0),
+ /**
+ * The dictionary is always raw content, even when it starts with the dictionary magic number.
+ * Use this when the dictionary is arbitrary data, such as a previously served resource
+ * (for example the {@code dcz} content coding of RFC 9842).
+ */
+ RAW_CONTENT(1),
+ /**
+ * The dictionary must be a full Zstandard dictionary, starting with the dictionary magic number.
+ * Anything else is rejected.
+ */
+ FULL_DICT(2);
+
+ private final int value;
+
+ ZstdDictContentType(int value) {
+ this.value = value;
+ }
+
+ int value() {
+ return value;
+ }
+}
=====================================
src/main/java/com/github/luben/zstd/ZstdDictDecompress.java
=====================================
@@ -17,9 +17,10 @@ public class ZstdDictDecompress extends SharedDictBase {
private ByteBuffer sharedDict = null;
- private native void init(byte @NotNull [] dict, int dict_offset, int dict_size);
+ private native void init(byte @NotNull [] dict, int dict_offset, int dict_size, int dictContentType);
- private native void initDirect(@NotNull ByteBuffer dict, int dict_offset, int dict_size, int byReference);
+ private native void initDirect(@NotNull ByteBuffer dict, int dict_offset, int dict_size, int byReference,
+ int dictContentType);
private native void free();
@@ -39,6 +40,16 @@ public class ZstdDictDecompress extends SharedDictBase {
this(dict, 0, dict.length);
}
+ /**
+ * Convenience constructor to create a new dictionary for use with fast decompress
+ *
+ * @param dict buffer containing dictionary to load/parse with exact length
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(byte @NotNull [] dict, @NotNull ZstdDictContentType type) {
+ this(dict, 0, dict.length, type);
+ }
+
/**
* Create a new dictionary for use with fast decompress
*
@@ -47,10 +58,23 @@ public class ZstdDictDecompress extends SharedDictBase {
* @param length number of bytes to use from the buffer
*/
public ZstdDictDecompress(byte @NotNull [] dict, int offset, int length) {
+ this(dict, offset, length, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast decompress, interpreting its content as {@code type} says.
+ *
+ * @param dict buffer containing dictionary
+ * @param offset the offset into the buffer to read from
+ * @param length number of bytes to use from the buffer
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(byte @NotNull [] dict, int offset, int length, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
if (offset < 0 || length < 0 || length > dict.length - offset) {
throw new IllegalArgumentException("Invalid offset/length for dictionary buffer");
}
- init(dict, offset, length);
+ init(dict, offset, length, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createDDict failed");
@@ -78,6 +102,19 @@ public class ZstdDictDecompress extends SharedDictBase {
* @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
*/
public ZstdDictDecompress(@NotNull ByteBuffer dict, boolean byReference) {
+ this(dict, byReference, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast decompress, interpreting its content as {@code type} says.
+ * If byReference is true, then the native code does not copy the data but keeps a reference to the byte buffer, which must then not be modified before this context has been closed.
+ *
+ * @param dict Direct ByteBuffer containing dictionary using position and limit to define range in buffer.
+ * @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(@NotNull ByteBuffer dict, boolean byReference, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
int length = dict.limit() - dict.position();
if (!dict.isDirect()) {
@@ -86,7 +123,7 @@ public class ZstdDictDecompress extends SharedDictBase {
if (length < 0) {
throw new IllegalArgumentException("dict cannot be empty.");
}
- initDirect(dict, dict.position(), length, byReference ? 1 : 0);
+ initDirect(dict, dict.position(), length, byReference ? 1 : 0, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createDDict failed");
=====================================
src/main/java/com/github/luben/zstd/ZstdInputStream.java
=====================================
@@ -122,6 +122,36 @@ public class ZstdInputStream extends FilterInputStream {
return inner.markSupported();
}
+ /**
+ * Reset the decompression stream to read from a new {@link InputStream}.
+ *
+ * This reuses the existing native {@code ZSTD_DStream} context, including its
+ * internal window buffer and any previously loaded dictionary. The native context
+ * is reset via {@code ZSTD_DCtx_reset} with {@code ZSTD_reset_session_only},
+ * which resets the session state without freeing or reallocating the window buffer
+ * and without clearing loaded dictionaries or parameters.
+ * If the next frame's window size fits within the existing buffer, no native memory
+ * allocation occurs at all.
+ *
+ * Previously configured settings such as {@link #setContinuous(boolean)} and
+ * loaded dictionaries are preserved across the reset.
+ *
+ * The previous {@link InputStream} is not closed; the caller is responsible
+ * for its lifecycle.
+ *
+ * This is intended for pooling: instead of creating a new
+ * {@code ZstdInputStream} (which calls {@code ZSTD_createDStream} +
+ * {@code malloc}) for each compressed stream and then closing it (which calls
+ * {@code ZSTD_freeDStream} + {@code free}), callers can keep a single instance
+ * and call {@code reset()} with each new input stream.
+ *
+ * @param newInput the new compressed input stream to decompress
+ * @return the old input stream
+ * @throws IOException if the stream has been closed or the native reset fails
+ */
+ public synchronized InputStream resetSession(@NotNull InputStream newInput) throws IOException {
+ return inner.resetSession(newInput);
+ }
public void close() throws IOException {
inner.close();
=====================================
src/main/java/com/github/luben/zstd/ZstdInputStreamNoFinalizer.java
=====================================
@@ -9,6 +9,7 @@ import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
+import java.util.LinkedList;
/**
* InputStream filter that decompresses the data provided
@@ -39,8 +40,9 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
private boolean isContinuous = false;
private boolean frameFinished = true;
private boolean isClosed = false;
- // keep the active dict alive
- private @Nullable ZstdDictDecompress active_dict;
+ private boolean isMultiDict = false;
+ // keep the active dict(s) alive
+ private LinkedList<ZstdDictDecompress> active_dicts = new LinkedList<ZstdDictDecompress>();
/* JNI methods */
public static native long recommendedDInSize();
@@ -115,12 +117,12 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
}
throw new ZstdIOException(size);
}
- // release the shared lock on the previously used dict (if any)
- if (active_dict != null) {
- active_dict.releaseSharedLock();
+ // release the shared lock on the previously used dict if not using mulitple dicts (if any)
+ if (!active_dicts.isEmpty() && !isMultiDict) {
+ active_dicts.removeLast().releaseSharedLock();
}
// keep the dict alive so it's not garbage collected
- active_dict = dict;
+ active_dicts.addFirst(dict);
return this;
}
@@ -143,6 +145,13 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
if (Zstd.isError(size)) {
throw new ZstdIOException(size);
}
+ // if we disable the multi-dict support, release all but the last registered dict
+ if (!useMultiple) {
+ while (active_dicts.size() > 1) {
+ active_dicts.removeLast().releaseSharedLock();
+ }
+ }
+ isMultiDict = useMultiple;
return this;
}
@@ -203,6 +212,11 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
}
}
+ // Input left over after a finished frame is the start of the next one.
+ if (srcPos < srcSize) {
+ frameFinished = false;
+ }
+
lastDstPos = dstPos;
long size = decompressStream(stream, dst, dstSize, src, (int) srcSize);
@@ -213,7 +227,7 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
// we have completed a frame
if (size == 0) {
frameFinished = true;
- // we need to read from the upstream only if we have not consumed
+ // we need to read from the upstream only if we have consumed
// fully the source buffer
needRead = srcPos == srcSize;
return (int)(dstPos - offset);
@@ -335,9 +349,8 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
if (isClosed) {
return;
}
- if (active_dict != null) {
- active_dict.releaseSharedLock();
- active_dict = null;
+ while (active_dicts.size() > 0) {
+ active_dicts.removeLast().releaseSharedLock();
}
isClosed = true;
bufferPool.release(srcByteBuffer);
=====================================
src/main/java22/com/github/luben/zstd/Zstd.java
=====================================
@@ -1210,6 +1210,16 @@ public class Zstd {
if (samples.length <= 10) {
throw new ZstdException(Zstd.errGeneric(), "nb of samples too low");
}
+ // FASTCOVER trains on the first ~75% of samples (d defaults to 8); if those sum to
+ // fewer than 8 bytes, nbDmers underflows in the vendored fastcover.c (meta/zstd#4499).
+ if (!legacy) {
+ int nbTrain = (int) (samples.length * 0.75);
+ long trainSize = 0;
+ for (int i = 0; i < nbTrain; i++) trainSize += samples[i].length;
+ if (trainSize < 8) {
+ throw new ZstdException(Zstd.errGeneric(), "training samples too small");
+ }
+ }
return trainFromBuffer0(samples, dictBuffer, legacy, compressionLevel);
}
private static long trainFromBuffer0(byte @NotNull [][] samples, byte @NotNull [] dictBuffer, boolean legacy, int compressionLevel) {
@@ -1271,6 +1281,16 @@ public class Zstd {
if (sampleSizes.length <= 10) {
throw new ZstdException(Zstd.errGeneric(), "nb of samples too low");
}
+ // FASTCOVER trains on the first ~75% of samples (d defaults to 8); if those sum to
+ // fewer than 8 bytes, nbDmers underflows in the vendored fastcover.c (meta/zstd#4499).
+ if (!legacy) {
+ int nbTrain = (int) (sampleSizes.length * 0.75);
+ long trainSize = 0;
+ for (int i = 0; i < nbTrain; i++) trainSize += sampleSizes[i];
+ if (trainSize < 8) {
+ throw new ZstdException(Zstd.errGeneric(), "training samples too small");
+ }
+ }
return trainFromBufferDirect0(samples, sampleSizes, dictBuffer, legacy, compressionLevel);
}
=====================================
src/main/java22/com/github/luben/zstd/ZstdBinding.java
=====================================
@@ -214,6 +214,9 @@ final class ZstdBinding {
static final int ZSTD_PS_ENABLE = readConstant("ps_enable");
static final int ZSTD_PS_DISABLE = readConstant("ps_disable");
+ /* ZSTD_dictLoadMethod_e */
+ static final int ZSTD_DLM_BY_COPY = readConstant("dlm_byCopy");
+
private static final MethodHandle ZSTD_DCtx_setParameter =
downcall("ZSTD_DCtx_setParameter",
FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
@@ -254,34 +257,44 @@ final class ZstdBinding {
FunctionDescriptor.of(ValueLayout.JAVA_INT),
MethodType.methodType(int.class));
- /* Copying dictionary creation accepts heap segments under critical, matching
- * JNI's GetPrimitiveArrayCritical. By-reference creation accepts only native
- * segments: the dictionary keeps the pointer after the downcall returns. */
- private static final MethodHandle ZSTD_createCDict =
- downcallCritical(
- "ZSTD_createCDict",
- FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T, ValueLayout.JAVA_INT),
- MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class, int.class));
- private static final MethodHandle ZSTD_createCDict_byReference =
- downcall(
- "ZSTD_createCDict_byReference",
- FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T, ValueLayout.JAVA_INT),
- MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class, int.class));
private static final MethodHandle ZSTD_freeCDict =
downcall(
"ZSTD_freeCDict",
FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS),
MethodType.methodType(long.class, MemorySegment.class));
- private static final MethodHandle ZSTD_createDDict =
+ /* Dictionary creation goes through ffm_zstd.c helpers, shared with the JNI code,
+ * which take a ZSTD_dictContentType_e. Copying creation accepts heap segments
+ * under critical, matching JNI's GetPrimitiveArrayCritical. By-reference creation
+ * accepts only native segments: the dictionary keeps the pointer after the
+ * downcall returns. */
+ private static final MethodHandle zstd_java_createCDict =
+ downcallCritical(
+ "zstd_java_createCDict",
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class, int.class));
+ private static final MethodHandle zstd_java_createCDict_byReference =
+ downcall(
+ "zstd_java_createCDict",
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class, int.class));
+ private static final MethodHandle zstd_java_createDDict =
downcallCritical(
- "ZSTD_createDDict",
- FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T),
- MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class));
- private static final MethodHandle ZSTD_createDDict_byReference =
+ "zstd_java_createDDict",
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class));
+ private static final MethodHandle zstd_java_createDDict_byReference =
downcall(
- "ZSTD_createDDict_byReference",
- FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T),
- MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class));
+ "zstd_java_createDDict",
+ FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
+ MethodType.methodType(MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class));
private static final MethodHandle ZSTD_freeDDict =
downcall(
"ZSTD_freeDDict",
@@ -329,6 +342,15 @@ final class ZstdBinding {
"ZSTD_CCtx_loadDictionary",
FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T),
MethodType.methodType(long.class, MemorySegment.class, MemorySegment.class, long.class));
+ /* critical and copying (ZSTD_dlm_byCopy), as ZSTD_CCtx_loadDictionary. */
+ private static final MethodHandle ZSTD_CCtx_loadDictionary_advanced =
+ downcallCritical(
+ "ZSTD_CCtx_loadDictionary_advanced",
+ FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, // ZSTD_dictLoadMethod_e
+ ValueLayout.JAVA_INT), // ZSTD_dictContentType_e
+ MethodType.methodType(long.class, MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class));
private static final MethodHandle ZSTD_CCtx_refCDict =
downcall(
"ZSTD_CCtx_refCDict",
@@ -503,6 +525,15 @@ final class ZstdBinding {
"ZSTD_DCtx_loadDictionary",
FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T),
MethodType.methodType(long.class, MemorySegment.class, MemorySegment.class, long.class));
+ /* critical and copying (ZSTD_dlm_byCopy), as ZSTD_DCtx_loadDictionary. */
+ private static final MethodHandle ZSTD_DCtx_loadDictionary_advanced =
+ downcallCritical(
+ "ZSTD_DCtx_loadDictionary_advanced",
+ FunctionDescriptor.of(C_SIZE_T, ValueLayout.ADDRESS, ValueLayout.ADDRESS, C_SIZE_T,
+ ValueLayout.JAVA_INT, // ZSTD_dictLoadMethod_e
+ ValueLayout.JAVA_INT), // ZSTD_dictContentType_e
+ MethodType.methodType(long.class, MemorySegment.class, MemorySegment.class, long.class,
+ int.class, int.class));
private static final MethodHandle ZSTD_DCtx_refDDict =
downcall(
"ZSTD_DCtx_refDDict",
@@ -935,6 +966,17 @@ final class ZstdBinding {
}
}
+ /** {@link #loadDictionary} with a ZSTD_dictContentType_e; the dictionary is copied. */
+ static long loadDictionaryAdvanced(@NotNull MemorySegment cctx, @NotNull MemorySegment dict, long dictSize,
+ int dictContentType) {
+ try {
+ return (long) ZSTD_CCtx_loadDictionary_advanced.invokeExact(cctx, dict, dictSize,
+ ZSTD_DLM_BY_COPY, dictContentType);
+ } catch (Throwable t) {
+ throw new AssertionError("Call to ZSTD_CCtx_loadDictionary_advanced failed", t);
+ }
+ }
+
static long refCDict(@NotNull MemorySegment cctx, @NotNull MemorySegment cdict) {
try {
return (long) ZSTD_CCtx_refCDict.invokeExact(cctx, cdict);
@@ -1158,6 +1200,17 @@ final class ZstdBinding {
}
}
+ /** {@link #loadDDictionary} with a ZSTD_dictContentType_e; the dictionary is copied. */
+ static long loadDDictionaryAdvanced(@NotNull MemorySegment dctx, @NotNull MemorySegment dict, long dictSize,
+ int dictContentType) {
+ try {
+ return (long) ZSTD_DCtx_loadDictionary_advanced.invokeExact(dctx, dict, dictSize,
+ ZSTD_DLM_BY_COPY, dictContentType);
+ } catch (Throwable t) {
+ throw new AssertionError("Call to ZSTD_DCtx_loadDictionary_advanced failed", t);
+ }
+ }
+
static long refDDict(@NotNull MemorySegment dctx, @NotNull MemorySegment ddict) {
try {
return (long) ZSTD_DCtx_refDDict.invokeExact(dctx, ddict);
@@ -1192,19 +1245,24 @@ final class ZstdBinding {
}
}
- static @NotNull MemorySegment createCDict(@NotNull MemorySegment dict, long dictSize, int level) {
+ /** zstd_java_createCDict (ffm_zstd.c), copying the dictionary. */
+ static @NotNull MemorySegment createCDict(@NotNull MemorySegment dict, long dictSize, int level,
+ int dictContentType) {
try {
- return (MemorySegment) ZSTD_createCDict.invokeExact(dict, dictSize, level);
+ return (MemorySegment) zstd_java_createCDict.invokeExact(dict, dictSize, 0, dictContentType, level);
} catch (Throwable t) {
- throw new AssertionError("Call to ZSTD_createCDict failed", t);
+ throw new AssertionError("Call to zstd_java_createCDict failed", t);
}
}
- static @NotNull MemorySegment createCDictByReference(@NotNull MemorySegment dict, long dictSize, int level) {
+ /** zstd_java_createCDict (ffm_zstd.c) by reference; `dict` must be a native segment. */
+ static @NotNull MemorySegment createCDictByReference(@NotNull MemorySegment dict, long dictSize, int level,
+ int dictContentType) {
try {
- return (MemorySegment) ZSTD_createCDict_byReference.invokeExact(dict, dictSize, level);
+ return (MemorySegment) zstd_java_createCDict_byReference.invokeExact(
+ dict, dictSize, 1, dictContentType, level);
} catch (Throwable t) {
- throw new AssertionError("Call to ZSTD_createCDict_byReference failed", t);
+ throw new AssertionError("Call to zstd_java_createCDict failed", t);
}
}
@@ -1216,19 +1274,22 @@ final class ZstdBinding {
}
}
- static @NotNull MemorySegment createDDict(@NotNull MemorySegment dict, long dictSize) {
+ /** zstd_java_createDDict (ffm_zstd.c), copying the dictionary. */
+ static @NotNull MemorySegment createDDict(@NotNull MemorySegment dict, long dictSize, int dictContentType) {
try {
- return (MemorySegment) ZSTD_createDDict.invokeExact(dict, dictSize);
+ return (MemorySegment) zstd_java_createDDict.invokeExact(dict, dictSize, 0, dictContentType);
} catch (Throwable t) {
- throw new AssertionError("Call to ZSTD_createDDict failed", t);
+ throw new AssertionError("Call to zstd_java_createDDict failed", t);
}
}
- static @NotNull MemorySegment createDDictByReference(@NotNull MemorySegment dict, long dictSize) {
+ /** zstd_java_createDDict (ffm_zstd.c) by reference; `dict` must be a native segment. */
+ static @NotNull MemorySegment createDDictByReference(@NotNull MemorySegment dict, long dictSize,
+ int dictContentType) {
try {
- return (MemorySegment) ZSTD_createDDict_byReference.invokeExact(dict, dictSize);
+ return (MemorySegment) zstd_java_createDDict_byReference.invokeExact(dict, dictSize, 1, dictContentType);
} catch (Throwable t) {
- throw new AssertionError("Call to ZSTD_createDDict_byReference failed", t);
+ throw new AssertionError("Call to zstd_java_createDDict failed", t);
}
}
=====================================
src/main/java22/com/github/luben/zstd/ZstdCompressCtx.java
=====================================
@@ -503,10 +503,25 @@ public class ZstdCompressCtx extends AutoCloseBase {
*/
@NotNull
public ZstdCompressCtx loadDict(byte @Nullable [] dict) {
+ return loadDict(dict, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Load compression dictionary to be used for subsequently compressed frames,
+ * interpreting its content as {@code type} says.
+ * A {@link ZstdDictContentType#FULL_DICT} that is not a valid dictionary is reported
+ * when compressing with it.
+ *
+ * @param dict the dictionary or `null` to remove loaded dictionary
+ * @param type how to interpret the content of the dictionary
+ */
+ @NotNull
+ public ZstdCompressCtx loadDict(byte @Nullable [] dict, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
ensureOpen();
acquireSharedLock();
try {
- long result = loadCDict0(dict);
+ long result = loadCDict0(dict, type.value());
if (Zstd.isError(result)) {
throw new ZstdException(result);
}
@@ -526,12 +541,12 @@ public class ZstdCompressCtx extends AutoCloseBase {
* the empty-array case was checked to produce the same frames as JNI.
* JNI could return a memory-allocation error when acquiring the array pointer;
* MemorySegment.ofArray needs no equivalent error check. */
- private long loadCDict0(byte @Nullable [] dict) {
+ private long loadCDict0(byte @Nullable [] dict, int dictContentType) {
if (dict == null) {
// remove dictionary
return ZstdBinding.loadDictionary(cctx, MemorySegment.NULL, 0);
}
- return ZstdBinding.loadDictionary(cctx, MemorySegment.ofArray(dict), dict.length);
+ return ZstdBinding.loadDictionaryAdvanced(cctx, MemorySegment.ofArray(dict), dict.length, dictContentType);
}
/**
=====================================
src/main/java22/com/github/luben/zstd/ZstdDecompressCtx.java
=====================================
@@ -80,6 +80,30 @@ public class ZstdDecompressCtx extends AutoCloseBase {
return this;
}
+ /**
+ * Set the maximum window size the decompressor accepts, as a power of 2.
+ * Frames that need a larger window are rejected instead of decoded, which
+ * bounds the memory a frame header can make the decompressor allocate.
+ * Cleared by {@link #reset()}.
+ *
+ * @param windowLogMax Maximum window size, expressed as power of 2,
+ * default: 27 (ZSTD_WINDOWLOG_LIMIT_DEFAULT)
+ */
+ @NotNull
+ public ZstdDecompressCtx setLongMax(int windowLogMax) {
+ ensureOpen();
+ acquireSharedLock();
+ try {
+ long result = Zstd.setDecompressionLongMax(nativePtr, windowLogMax);
+ if (Zstd.isError(result)) {
+ throw new ZstdException(result);
+ }
+ } finally {
+ releaseSharedLock();
+ }
+ return this;
+ }
+
/**
* Load decompression dictionary
*
@@ -129,10 +153,22 @@ public class ZstdDecompressCtx extends AutoCloseBase {
*/
@NotNull
public ZstdDecompressCtx loadDict(byte @Nullable [] dict) {
+ return loadDict(dict, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Load decompression dictionary, interpreting its content as {@code type} says.
+ *
+ * @param dict the dictionary or `null` to remove loaded dictionary
+ * @param type how to interpret the content of the dictionary
+ */
+ @NotNull
+ public ZstdDecompressCtx loadDict(byte @Nullable [] dict, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
ensureOpen();
acquireSharedLock();
try {
- long result = loadDDict0(dict);
+ long result = loadDDict0(dict, type.value());
if (Zstd.isError(result)) {
throw new ZstdException(result);
}
@@ -149,12 +185,12 @@ public class ZstdDecompressCtx extends AutoCloseBase {
/* Replaces jni_fast_zstd.c:691-705. The critical downcall passes the heap array
* directly to libzstd, which copies it and retains no pointer. JNI could return a
* memory-allocation error when acquiring the array; MemorySegment.ofArray cannot fail. */
- private long loadDDict0(byte @Nullable [] dict) {
+ private long loadDDict0(byte @Nullable [] dict, int dictContentType) {
if (dict == null) {
// remove dictionary
return ZstdBinding.loadDDictionary(dctx, MemorySegment.NULL, 0);
}
- return ZstdBinding.loadDDictionary(dctx, MemorySegment.ofArray(dict), dict.length);
+ return ZstdBinding.loadDDictionaryAdvanced(dctx, MemorySegment.ofArray(dict), dict.length, dictContentType);
}
/**
=====================================
src/main/java22/com/github/luben/zstd/ZstdDictCompress.java
=====================================
@@ -22,17 +22,18 @@ public class ZstdDictCompress extends SharedDictBase {
private int level = Zstd.defaultCompressionLevel();
- private void init(byte @NotNull [] dict, int dict_offset, int dict_size, int level) {
+ private void init(byte @NotNull [] dict, int dict_offset, int dict_size, int level, int dictContentType) {
nativePtr = ZstdBinding.createCDict(
- MemorySegment.ofArray(dict).asSlice(dict_offset, dict_size), dict_size, level).address();
+ MemorySegment.ofArray(dict).asSlice(dict_offset, dict_size), dict_size, level, dictContentType)
+ .address();
}
- private void initDirect(@NotNull ByteBuffer dict, int dict_size, int level, int byReference) {
+ private void initDirect(@NotNull ByteBuffer dict, int dict_size, int level, int byReference, int dictContentType) {
// ofBuffer already covers [position, limit), the range supplied by the constructor.
MemorySegment segment = MemorySegment.ofBuffer(dict);
nativePtr = (byReference == 0
- ? ZstdBinding.createCDict(segment, dict_size, level)
- : ZstdBinding.createCDictByReference(segment, dict_size, level)).address();
+ ? ZstdBinding.createCDict(segment, dict_size, level, dictContentType)
+ : ZstdBinding.createCDictByReference(segment, dict_size, level, dictContentType)).address();
}
private void free() {
@@ -56,6 +57,17 @@ public class ZstdDictCompress extends SharedDictBase {
this(dict, 0, dict.length, level);
}
+ /**
+ * Convenience constructor to create a new dictionary for use with fast compress
+ *
+ * @param dict buffer containing dictionary to load/parse with exact length
+ * @param level compression level
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(byte @NotNull [] dict, int level, @NotNull ZstdDictContentType type) {
+ this(dict, 0, dict.length, level, type);
+ }
+
/**
* Create a new dictionary for use with fast compress
*
@@ -65,6 +77,24 @@ public class ZstdDictCompress extends SharedDictBase {
* @param level compression level
*/
public ZstdDictCompress(byte @NotNull [] dict, int offset, int length, int level) {
+ this(dict, offset, length, level, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast compress, interpreting its content as {@code type} says.
+ * A {@link ZstdDictContentType#RAW_CONTENT} dictionary that starts with the dictionary magic number
+ * is created with libzstd's advanced API, which fixes the compression parameters for {@code level}
+ * when the dictionary is created rather than adjusting them to the size of each input.
+ *
+ * @param dict buffer containing dictionary
+ * @param offset the offset into the buffer to read from
+ * @param length number of bytes to use from the buffer
+ * @param level compression level
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(byte @NotNull [] dict, int offset, int length, int level,
+ @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
this.level = level;
if (dict.length - offset < 0) {
throw new IllegalArgumentException("Dictionary buffer is too short");
@@ -72,7 +102,7 @@ public class ZstdDictCompress extends SharedDictBase {
if (offset < 0 || length < 0 || length > dict.length - offset) {
throw new IllegalArgumentException("Invalid offset/length for dictionary buffer");
}
- init(dict, offset, length, level);
+ init(dict, offset, length, level, type.value());
if (0 == nativePtr) {
throw new IllegalStateException("ZSTD_createCDict failed");
@@ -101,6 +131,24 @@ public class ZstdDictCompress extends SharedDictBase {
* @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
*/
public ZstdDictCompress(@NotNull ByteBuffer dict, int level, boolean byReference) {
+ this(dict, level, byReference, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast compress, interpreting its content as {@code type} says.
+ * If byReference is true, then the native code does not copy the data but keeps a reference to the byte buffer, which must then not be modified before this context has been closed.
+ * A {@link ZstdDictContentType#RAW_CONTENT} dictionary that starts with the dictionary magic number
+ * is created with libzstd's advanced API, which fixes the compression parameters for {@code level}
+ * when the dictionary is created rather than adjusting them to the size of each input.
+ *
+ * @param dict Direct ByteBuffer containing dictionary using position and limit to define range in buffer.
+ * @param level compression level
+ * @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictCompress(@NotNull ByteBuffer dict, int level, boolean byReference,
+ @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
this.level = level;
int length = dict.limit() - dict.position();
if (!dict.isDirect()) {
@@ -109,7 +157,7 @@ public class ZstdDictCompress extends SharedDictBase {
if (length < 0) {
throw new IllegalArgumentException("dict cannot be empty.");
}
- initDirect(dict, length, level, byReference ? 1 : 0);
+ initDirect(dict, length, level, byReference ? 1 : 0, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createCDict failed");
=====================================
src/main/java22/com/github/luben/zstd/ZstdDictDecompress.java
=====================================
@@ -20,17 +20,17 @@ public class ZstdDictDecompress extends SharedDictBase {
private ByteBuffer sharedDict = null;
- private void init(byte @NotNull [] dict, int dict_offset, int dict_size) {
+ private void init(byte @NotNull [] dict, int dict_offset, int dict_size, int dictContentType) {
nativePtr = ZstdBinding.createDDict(
- MemorySegment.ofArray(dict).asSlice(dict_offset, dict_size), dict_size).address();
+ MemorySegment.ofArray(dict).asSlice(dict_offset, dict_size), dict_size, dictContentType).address();
}
- private void initDirect(@NotNull ByteBuffer dict, int dict_size, int byReference) {
+ private void initDirect(@NotNull ByteBuffer dict, int dict_size, int byReference, int dictContentType) {
// ofBuffer already covers [position, limit), the range supplied by the constructor.
MemorySegment segment = MemorySegment.ofBuffer(dict);
nativePtr = (byReference == 0
- ? ZstdBinding.createDDict(segment, dict_size)
- : ZstdBinding.createDDictByReference(segment, dict_size)).address();
+ ? ZstdBinding.createDDict(segment, dict_size, dictContentType)
+ : ZstdBinding.createDDictByReference(segment, dict_size, dictContentType)).address();
}
private void free() {
@@ -53,6 +53,16 @@ public class ZstdDictDecompress extends SharedDictBase {
this(dict, 0, dict.length);
}
+ /**
+ * Convenience constructor to create a new dictionary for use with fast decompress
+ *
+ * @param dict buffer containing dictionary to load/parse with exact length
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(byte @NotNull [] dict, @NotNull ZstdDictContentType type) {
+ this(dict, 0, dict.length, type);
+ }
+
/**
* Create a new dictionary for use with fast decompress
*
@@ -61,10 +71,23 @@ public class ZstdDictDecompress extends SharedDictBase {
* @param length number of bytes to use from the buffer
*/
public ZstdDictDecompress(byte @NotNull [] dict, int offset, int length) {
+ this(dict, offset, length, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast decompress, interpreting its content as {@code type} says.
+ *
+ * @param dict buffer containing dictionary
+ * @param offset the offset into the buffer to read from
+ * @param length number of bytes to use from the buffer
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(byte @NotNull [] dict, int offset, int length, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
if (offset < 0 || length < 0 || length > dict.length - offset) {
throw new IllegalArgumentException("Invalid offset/length for dictionary buffer");
}
- init(dict, offset, length);
+ init(dict, offset, length, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createDDict failed");
@@ -92,6 +115,19 @@ public class ZstdDictDecompress extends SharedDictBase {
* @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
*/
public ZstdDictDecompress(@NotNull ByteBuffer dict, boolean byReference) {
+ this(dict, byReference, ZstdDictContentType.AUTO);
+ }
+
+ /**
+ * Create a new dictionary for use with fast decompress, interpreting its content as {@code type} says.
+ * If byReference is true, then the native code does not copy the data but keeps a reference to the byte buffer, which must then not be modified before this context has been closed.
+ *
+ * @param dict Direct ByteBuffer containing dictionary using position and limit to define range in buffer.
+ * @param byReference tell the native part to use the byte buffer directly and not copy the data when true.
+ * @param type how to interpret the content of the dictionary
+ */
+ public ZstdDictDecompress(@NotNull ByteBuffer dict, boolean byReference, @NotNull ZstdDictContentType type) {
+ java.util.Objects.requireNonNull(type, "type");
int length = dict.limit() - dict.position();
if (!dict.isDirect()) {
@@ -100,7 +136,7 @@ public class ZstdDictDecompress extends SharedDictBase {
if (length < 0) {
throw new IllegalArgumentException("dict cannot be empty.");
}
- initDirect(dict, length, byReference ? 1 : 0);
+ initDirect(dict, length, byReference ? 1 : 0, type.value());
if (nativePtr == 0L) {
throw new IllegalStateException("ZSTD_createDDict failed");
=====================================
src/main/java22/com/github/luben/zstd/ZstdInputStreamNoFinalizer.java
=====================================
@@ -10,6 +10,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.foreign.MemorySegment;
import java.nio.ByteBuffer;
+import java.util.LinkedList;
/**
* InputStream filter that decompresses the data provided
@@ -56,8 +57,9 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
private boolean isContinuous = false;
private boolean frameFinished = true;
private boolean isClosed = false;
- // keep the active dict alive
- private @Nullable ZstdDictDecompress active_dict;
+ private boolean isMultiDict = false;
+ // keep the active dict(s) alive
+ private LinkedList<ZstdDictDecompress> active_dicts = new LinkedList<ZstdDictDecompress>();
/* The destination is the caller's array, and a reader that asks for small
* chunks hands over the same one on every call. Wrapping it fresh each time
@@ -170,12 +172,13 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
}
throw new ZstdIOException(size);
}
- // release the shared lock on the previously used dict (if any)
- if (active_dict != null) {
- active_dict.releaseSharedLock();
+ // release the shared lock on the previously used dict if not using mulitple dicts (if any)
+ if (!active_dicts.isEmpty() && !isMultiDict) {
+ active_dicts.removeFirst().releaseSharedLock();
}
// keep the dict alive so it's not garbage collected
- active_dict = dict;
+ active_dicts.addFirst(dict);
+
return this;
}
@@ -198,6 +201,13 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
if (Zstd.isError(size)) {
throw new ZstdIOException(size);
}
+ // if we disable the multi-dict support, release all but the last registered dict
+ if (!useMultiple) {
+ while (active_dicts.size() > 1) {
+ active_dicts.removeLast().releaseSharedLock();
+ }
+ }
+ isMultiDict = useMultiple;
return this;
}
@@ -244,6 +254,8 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
srcPos.set(0);
if (srcSize < 0) {
srcSize = 0;
+ lastDstArray = null;
+ lastDstSegment = null;
if (frameFinished) {
return -1;
} else if (isContinuous) {
@@ -262,10 +274,17 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
}
}
+ // Input left over after a finished frame is the start of the next one.
+ if (srcPos.get() < srcSize) {
+ frameFinished = false;
+ }
+
lastDstPos = dstPosition;
long size = decompressStream(dstSegment, dstSize, srcSize);
if (Zstd.isError(size)) {
+ lastDstArray = null;
+ lastDstSegment = null;
throw new ZstdIOException(size);
}
dstPosition = dstPos.get();
@@ -273,9 +292,13 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
// we have completed a frame
if (size == 0) {
frameFinished = true;
- // we need to read from the upstream only if we have not consumed
+ // we need to read from the upstream only if we have consumed
// fully the source buffer
needRead = srcPos.get() == srcSize;
+ if (needRead) {
+ lastDstArray = null;
+ lastDstSegment = null;
+ }
return (int)(dstPosition - offset);
} else {
// size > 0, so more input is required but there is data left in
@@ -388,6 +411,8 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
this.srcSize = 0;
this.needRead = true;
this.frameFinished = true;
+ this.lastDstArray = null;
+ this.lastDstSegment = null;
return oldInputStream;
}
@@ -395,9 +420,8 @@ public class ZstdInputStreamNoFinalizer extends FilterInputStream {
if (isClosed) {
return;
}
- if (active_dict != null) {
- active_dict.releaseSharedLock();
- active_dict = null;
+ while (active_dicts.size() > 0) {
+ active_dicts.removeLast().releaseSharedLock();
}
isClosed = true;
bufferPool.release(srcByteBuffer);
=====================================
src/main/native/ffm_zstd.c
=====================================
@@ -289,6 +289,10 @@ ZSTD_JAVA_API int zstd_java_ps_disable(void) {
return (int) ZSTD_ps_disable;
}
+ZSTD_JAVA_API int zstd_java_dlm_byCopy(void) {
+ return (int) ZSTD_dlm_byCopy;
+}
+
/* JNI_ZSTD_decompressedSize (jni_zstd.c) verbatim, for FFM. The frame header
* lives on the C stack, so Java needs no struct layout or buffer, and the
@@ -305,3 +309,45 @@ ZSTD_JAVA_API size_t zstd_java_decompressedSize(const void* buf, size_t bufSize,
return ZSTD_getFrameContentSize(buf, bufSize);
}
+
+/* Dictionary creation with a ZSTD_dictContentType_e, shared by the JNI code
+ * (jni_fast_zstd.c) and FFM. byReference selects ZSTD_dlm_byRef. */
+
+static int zstd_java_startsWithDictMagic(const void* dict, size_t dictSize) {
+ const unsigned char* const p = (const unsigned char*) dict;
+ if (dict == NULL || dictSize < 8) return 0; /* libzstd loads shorter dicts as raw content */
+ return ((unsigned) p[0] | ((unsigned) p[1] << 8) | ((unsigned) p[2] << 16) | ((unsigned) p[3] << 24))
+ == ZSTD_MAGIC_DICTIONARY;
+}
+
+/* ZSTD_createCDict_advanced* mark the CDict as created by the advanced API, so it
+ * keeps the parameters chosen at creation for every input size, while
+ * ZSTD_createCDict records the level and re-derives them for large inputs. To stay
+ * identical to ZSTD_createCDict wherever the content type changes nothing, only a
+ * raw-content dict that starts with the magic number takes the advanced path. */
+ZSTD_JAVA_API ZSTD_CDict* zstd_java_createCDict(const void* dict, size_t dictSize,
+ int byReference, int dictContentType, int level) {
+ int const magic = zstd_java_startsWithDictMagic(dict, dictSize);
+ if (dictContentType == ZSTD_dct_rawContent && magic) {
+ ZSTD_CDict* cdict = NULL;
+ ZSTD_CCtx_params* const params = ZSTD_createCCtxParams();
+ if (params == NULL) return NULL;
+ if (!ZSTD_isError(ZSTD_CCtxParams_init(params, level))) {
+ cdict = ZSTD_createCDict_advanced2(dict, dictSize,
+ byReference ? ZSTD_dlm_byRef : ZSTD_dlm_byCopy, ZSTD_dct_rawContent,
+ params, ZSTD_defaultCMem);
+ }
+ ZSTD_freeCCtxParams(params);
+ return cdict;
+ }
+ if (dictContentType == ZSTD_dct_fullDict && !magic) return NULL;
+ return byReference ? ZSTD_createCDict_byReference(dict, dictSize, level)
+ : ZSTD_createCDict(dict, dictSize, level);
+}
+
+ZSTD_JAVA_API ZSTD_DDict* zstd_java_createDDict(const void* dict, size_t dictSize,
+ int byReference, int dictContentType) {
+ return ZSTD_createDDict_advanced(dict, dictSize,
+ byReference ? ZSTD_dlm_byRef : ZSTD_dlm_byCopy,
+ (ZSTD_dictContentType_e) dictContentType, ZSTD_defaultCMem);
+}
=====================================
src/main/native/jni_fast_zstd.c
=====================================
@@ -10,20 +10,26 @@
static jfieldID compress_dict = 0;
static jfieldID decompress_dict = 0;
+/* Defined in ffm_zstd.c, which FFM calls directly. */
+ZSTD_CDict* zstd_java_createCDict(const void* dict, size_t dictSize,
+ int byReference, int dictContentType, int level);
+ZSTD_DDict* zstd_java_createDDict(const void* dict, size_t dictSize,
+ int byReference, int dictContentType);
+
/*
* Class: com_github_luben_zstd_ZstdDictCompress
* Method: init
- * Signature: ([BIII)V
+ * Signature: ([BIIII)V
*/
JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictCompress_init
- (JNIEnv *env, jobject obj, jbyteArray dict, jint dict_offset, jint dict_size, jint level)
+ (JNIEnv *env, jobject obj, jbyteArray dict, jint dict_offset, jint dict_size, jint level, jint dict_content_type)
{
jclass clazz = (*env)->GetObjectClass(env, obj);
compress_dict = (*env)->GetFieldID(env, clazz, "nativePtr", "J");
if (NULL == dict) return;
void *dict_buff = (*env)->GetPrimitiveArrayCritical(env, dict, NULL);
if (NULL == dict_buff) return;
- ZSTD_CDict* cdict = ZSTD_createCDict(((char *)dict_buff) + dict_offset, dict_size, level);
+ ZSTD_CDict* cdict = zstd_java_createCDict(((char *)dict_buff) + dict_offset, dict_size, 0, dict_content_type, level);
(*env)->ReleasePrimitiveArrayCritical(env, dict, dict_buff, JNI_ABORT);
if (NULL == cdict) return;
(*env)->SetLongField(env, obj, compress_dict, (jlong)(intptr_t) cdict);
@@ -32,22 +38,18 @@ JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictCompress_init
/*
* Class: com_github_luben_zstd_ZstdDictCompress
* Method: init
- * Signature: (Ljava/nio/ByteBuffer;IIII)V
+ * Signature: (Ljava/nio/ByteBuffer;IIIII)V
*/
JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictCompress_initDirect
- (JNIEnv *env, jobject obj, jobject dict, jint dict_offset, jint dict_size, jint level, jint byReference)
+ (JNIEnv *env, jobject obj, jobject dict, jint dict_offset, jint dict_size, jint level, jint byReference, jint dict_content_type)
{
jclass clazz = (*env)->GetObjectClass(env, obj);
compress_dict = (*env)->GetFieldID(env, clazz, "nativePtr", "J");
if (NULL == dict) return;
void *dict_buff = (*env)->GetDirectBufferAddress(env, dict);
if (NULL == dict_buff) return;
- ZSTD_CDict* cdict = NULL;
- if (byReference == 0) {
- cdict = ZSTD_createCDict(((char *)dict_buff) + dict_offset, dict_size, level);
- } else {
- cdict = ZSTD_createCDict_byReference(((char *)dict_buff) + dict_offset, dict_size, level);
- }
+ ZSTD_CDict* cdict = zstd_java_createCDict(((char *)dict_buff) + dict_offset, dict_size,
+ byReference != 0, dict_content_type, level);
if (NULL == cdict) return;
(*env)->SetLongField(env, obj, compress_dict, (jlong)(intptr_t) cdict);
}
@@ -69,10 +71,10 @@ JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictCompress_free
/*
* Class: com_github_luben_zstd_ZstdDictDecompress
* Method: init
- * Signature: ([BII)V
+ * Signature: ([BIII)V
*/
JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictDecompress_init
- (JNIEnv *env, jobject obj, jbyteArray dict, jint dict_offset, jint dict_size)
+ (JNIEnv *env, jobject obj, jbyteArray dict, jint dict_offset, jint dict_size, jint dict_content_type)
{
jclass clazz = (*env)->GetObjectClass(env, obj);
decompress_dict = (*env)->GetFieldID(env, clazz, "nativePtr", "J");
@@ -80,7 +82,7 @@ JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictDecompress_init
void *dict_buff = (*env)->GetPrimitiveArrayCritical(env, dict, NULL);
if (NULL == dict_buff) return;
- ZSTD_DDict* ddict = ZSTD_createDDict(((char *)dict_buff) + dict_offset, dict_size);
+ ZSTD_DDict* ddict = zstd_java_createDDict(((char *)dict_buff) + dict_offset, dict_size, 0, dict_content_type);
(*env)->ReleasePrimitiveArrayCritical(env, dict, dict_buff, JNI_ABORT);
if (NULL == ddict) return;
@@ -90,22 +92,18 @@ JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictDecompress_init
/*
* Class: com_github_luben_zstd_ZstdDictDecompress
* Method: initDirect
- * Signature: (Ljava/nio/ByteBuffer;III)V
+ * Signature: (Ljava/nio/ByteBuffer;IIII)V
*/
JNIEXPORT void JNICALL Java_com_github_luben_zstd_ZstdDictDecompress_initDirect
- (JNIEnv *env, jobject obj, jobject dict, jint dict_offset, jint dict_size, jint byReference)
+ (JNIEnv *env, jobject obj, jobject dict, jint dict_offset, jint dict_size, jint byReference, jint dict_content_type)
{
jclass clazz = (*env)->GetObjectClass(env, obj);
decompress_dict = (*env)->GetFieldID(env, clazz, "nativePtr", "J");
if (NULL == dict) return;
void *dict_buff = (*env)->GetDirectBufferAddress(env, dict);
- ZSTD_DDict* ddict = NULL;
- if (byReference == 0) {
- ddict = ZSTD_createDDict(((char *)dict_buff) + dict_offset, dict_size);
- } else {
- ddict = ZSTD_createDDict_byReference(((char *)dict_buff) + dict_offset, dict_size);
- }
+ ZSTD_DDict* ddict = zstd_java_createDDict(((char *)dict_buff) + dict_offset, dict_size,
+ byReference != 0, dict_content_type);
if (NULL == ddict) return;
(*env)->SetLongField(env, obj, decompress_dict, (jlong)(intptr_t) ddict);
@@ -338,10 +336,10 @@ JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdCompressCtx_loadCDictFast
/*
* Class: com_github_luben_zstd_ZstdCompressCtx
* Method: loadCDict0
- * Signature: (J[B)J
+ * Signature: (J[BI)J
*/
JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdCompressCtx_loadCDict0
- (JNIEnv *env, jclass clazz, jlong ptr, jbyteArray dict)
+ (JNIEnv *env, jclass clazz, jlong ptr, jbyteArray dict, jint dict_content_type)
{
ZSTD_CCtx* cctx = (ZSTD_CCtx*)(intptr_t) ptr;
if (dict == NULL) {
@@ -351,7 +349,8 @@ JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdCompressCtx_loadCDict0
jsize dict_size = (*env)->GetArrayLength(env, dict);
void *dict_buff = (*env)->GetPrimitiveArrayCritical(env, dict, NULL);
if (dict_buff == NULL) return -ZSTD_error_memory_allocation;
- size_t result = ZSTD_CCtx_loadDictionary(cctx, dict_buff, dict_size);
+ size_t result = ZSTD_CCtx_loadDictionary_advanced(cctx, dict_buff, dict_size,
+ ZSTD_dlm_byCopy, (ZSTD_dictContentType_e) dict_content_type);
(*env)->ReleasePrimitiveArrayCritical(env, dict, dict_buff, JNI_ABORT);
return result;
}
@@ -683,10 +682,10 @@ JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDictFa
/*
* Class: com_github_luben_zstd_ZstdDecompressCtx
* Method: loadDDict0
- * Signature: (J[B)J
+ * Signature: (J[BI)J
*/
JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDict0
- (JNIEnv *env, jclass clazz, jlong ptr, jbyteArray dict)
+ (JNIEnv *env, jclass clazz, jlong ptr, jbyteArray dict, jint dict_content_type)
{
ZSTD_DCtx* dctx = (ZSTD_DCtx*)(intptr_t)ptr;
if (dict == NULL) {
@@ -696,7 +695,8 @@ JNIEXPORT jlong JNICALL Java_com_github_luben_zstd_ZstdDecompressCtx_loadDDict0
jsize dict_size = (*env)->GetArrayLength(env, dict);
void *dict_buff = (*env)->GetPrimitiveArrayCritical(env, dict, NULL);
if (dict_buff == NULL) return -ZSTD_error_memory_allocation;
- size_t result = ZSTD_DCtx_loadDictionary(dctx, dict_buff, dict_size);
+ size_t result = ZSTD_DCtx_loadDictionary_advanced(dctx, dict_buff, dict_size,
+ ZSTD_dlm_byCopy, (ZSTD_dictContentType_e) dict_content_type);
(*env)->ReleasePrimitiveArrayCritical(env, dict, dict_buff, JNI_ABORT);
return result;
}
=====================================
src/main/native/jni_zdict.c
=====================================
@@ -22,7 +22,7 @@ JNIEXPORT jlong Java_com_github_luben_zstd_Zstd_trainFromBuffer0
for (int i = 0; i < num_samples; i++) {
jbyteArray sample = (*env)->GetObjectArrayElement(env, samples, i);
if (sample == NULL) {
- goto E3;
+ goto E2;
}
jsize length = (*env)->GetArrayLength(env, sample);
(*env)->DeleteLocalRef(env, sample);
@@ -39,6 +39,12 @@ JNIEXPORT jlong Java_com_github_luben_zstd_Zstd_trainFromBuffer0
for (int i = 0; i < num_samples; i++) {
jbyteArray sample = (*env)->GetObjectArrayElement(env, samples, i);
jsize length = (*env)->GetArrayLength(env, sample);
+ // sample concurrently modified in place - guard agains buffer overflow
+ if (length + cursor > samples_buffer_size) {
+ jclass eClass = (*env)->FindClass(env, "java/lang/RuntimeException");
+ (*env)->ThrowNew(env, eClass, "concurrent modification of samples");
+ goto E3;
+ }
(*env)->GetByteArrayRegion(env, sample, 0, length, (jbyte*)(((char *)samples_buffer) + cursor));
(*env)->DeleteLocalRef(env, sample);
cursor += length;
=====================================
version
=====================================
@@ -1 +1 @@
-1.5.7-23
+1.5.7-26
View it on GitLab: https://salsa.debian.org/java-team/zstd-jni-java/-/compare/0d1c63a742531c6484d8105b3f6accfb78337bd9...c47df355098c037ad2b5ce0ef30e5225c2792264
--
View it on GitLab: https://salsa.debian.org/java-team/zstd-jni-java/-/compare/0d1c63a742531c6484d8105b3f6accfb78337bd9...c47df355098c037ad2b5ce0ef30e5225c2792264
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261111/42a8c9c4/attachment.htm>
More information about the pkg-java-commits
mailing list