Copilot commented on code in PR #2409:
URL: https://github.com/apache/pekko/pull/2409#discussion_r2472100795


##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdCompressor.scala:
##########
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import com.github.luben.zstd.{ Zstd, ZstdDictCompress, 
ZstdDirectBufferCompressingStreamNoFinalizer }
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.util.ByteString
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdCompressor(
+    compressionLevel: Int =
+      Zstd.defaultCompressionLevel(), dictionary: Option[ZstdDictCompress] = 
None) extends Compressor {
+
+  private val targetBuffer = ByteBuffer.allocateDirect(65536)
+  private val compressingStream = new 
ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, compressionLevel)
+
+  dictionary.foreach(compressingStream.setDict)
+
+  override def compress(input: ByteString): ByteString = {
+    val inputBB = ByteBuffer.allocateDirect(input.size)
+    inputBB.put(input.toArrayUnsafe())
+    inputBB.flip()
+    compressingStream.compress(input.asByteBuffer)
+    val result = ByteString.fromByteBuffer(targetBuffer)
+    targetBuffer.flip()
+    result
+  }
+
+  override def flush(): ByteString = {
+    targetBuffer.flip()
+    val result = ByteString.fromByteBuffer(targetBuffer)
+    targetBuffer.clear()
+    compressingStream.flush()

Review Comment:
   The flush operation calls `compressingStream.flush()` after extracting the 
result from the buffer. The flush result is discarded. The correct order should 
be: flip buffer, flush stream (which may write more data to buffer), extract 
result, then clear buffer.
   ```suggestion
       compressingStream.flush()
       val result = ByteString.fromByteBuffer(targetBuffer)
       targetBuffer.clear()
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdCompressor.scala:
##########
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import com.github.luben.zstd.{ Zstd, ZstdDictCompress, 
ZstdDirectBufferCompressingStreamNoFinalizer }
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.util.ByteString
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdCompressor(
+    compressionLevel: Int =
+      Zstd.defaultCompressionLevel(), dictionary: Option[ZstdDictCompress] = 
None) extends Compressor {
+
+  private val targetBuffer = ByteBuffer.allocateDirect(65536)
+  private val compressingStream = new 
ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, compressionLevel)
+
+  dictionary.foreach(compressingStream.setDict)
+
+  override def compress(input: ByteString): ByteString = {
+    val inputBB = ByteBuffer.allocateDirect(input.size)
+    inputBB.put(input.toArrayUnsafe())
+    inputBB.flip()

Review Comment:
   Unused variable `inputBB` created but never used. The compress operation 
uses `input.asByteBuffer` instead. Either remove lines 39-41 or use `inputBB` 
in line 42 instead of `input.asByteBuffer`.
   ```suggestion
   
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/javadsl/Compression.scala:
##########
@@ -81,4 +87,25 @@ object Compression {
   def deflate(level: Int, nowrap: Boolean): Flow[ByteString, ByteString, 
NotUsed] =
     scaladsl.Compression.deflate(level, nowrap).asJava
 
+  /**
+   * @since 2.0.0
+   */
+  def zstd: Flow[ByteString, ByteString, NotUsed] =
+    scaladsl.Compression.zstd.asJava
+
+  /**
+   * Same as [[zstd]] with a custom level and an optional dictionary.
+   * @param level The compression level, must be greater or equal to 
[[Zstd.minCompressionLevel]] and less than or equal
+   *              to [[Zstd.maxCompressionLevel]]
+   * @param dictionary An optional dictionary that can be used for compression
+   * @since 2.0.0
+   */
+  def zstd(level: Int, dictionary: Optional[ZstdDictCompress]): 
Flow[ByteString, ByteString, NotUsed] =
+    scaladsl.Compression.zstd(level, dictionary.toScala).asJava
+
+  /**

Review Comment:
   Missing scaladoc description and parameter documentation. This should 
include a description and document the `maxBytesPerChunk` parameter, consistent 
with other decompression methods.
   ```suggestion
     /**
      * Creates a Flow that decompresses Zstandard-compressed stream of data.
      *
      * @param maxBytesPerChunk Maximum length of the output 
[[pekko.util.ByteString]] chunk.
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdDecompressor.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.Attributes
+import pekko.stream.impl.fusing.GraphStages.SimpleLinearGraphStage
+import pekko.stream.stage.{ GraphStageLogic, InHandler, OutHandler }
+import pekko.util.ByteString
+
+import com.github.luben.zstd.ZstdDirectBufferDecompressingStreamNoFinalizer
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdDecompressor(maxBytesPerChunk: Int) 
extends SimpleLinearGraphStage[ByteString] {
+
+  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 
{
+    new GraphStageLogic(shape) with InHandler with OutHandler {
+
+      private val sourceBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+
+      // This is initialized here to avoid an allocation per onPush, remember 
to clear before using
+      private val outputBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+      private val decompressingStream = new 
ZstdDirectBufferDecompressingStreamNoFinalizer(sourceBuffer)
+
+      override def onPush(): Unit = {
+        sourceBuffer.clear()
+        val inputArray = grab(in).toArrayUnsafe()
+        sourceBuffer.put(inputArray)
+        sourceBuffer.flip()
+        if (sourceBuffer.hasRemaining) {
+          var result = ByteString.empty
+          while (sourceBuffer.hasRemaining) {
+            outputBuffer.clear()
+            decompressingStream.read(outputBuffer)
+            outputBuffer.flip()
+            val outputArray = new Array[Byte](outputBuffer.limit())
+            outputBuffer.get(outputArray)
+            result = result.concat(ByteString.fromArrayUnsafe(outputArray))
+          }
+
+          // Fencepost case, it's possible to still have 
sourceBuffer.hasRemaining and yet compression result

Review Comment:
   Comment refers to 'compression result' but this is decompression code. 
Should be 'decompression result'.



##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdDecompressor.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.Attributes
+import pekko.stream.impl.fusing.GraphStages.SimpleLinearGraphStage
+import pekko.stream.stage.{ GraphStageLogic, InHandler, OutHandler }
+import pekko.util.ByteString
+
+import com.github.luben.zstd.ZstdDirectBufferDecompressingStreamNoFinalizer
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdDecompressor(maxBytesPerChunk: Int) 
extends SimpleLinearGraphStage[ByteString] {
+
+  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 
{
+    new GraphStageLogic(shape) with InHandler with OutHandler {
+
+      private val sourceBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+
+      // This is initialized here to avoid an allocation per onPush, remember 
to clear before using
+      private val outputBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+      private val decompressingStream = new 
ZstdDirectBufferDecompressingStreamNoFinalizer(sourceBuffer)
+
+      override def onPush(): Unit = {
+        sourceBuffer.clear()
+        val inputArray = grab(in).toArrayUnsafe()
+        sourceBuffer.put(inputArray)
+        sourceBuffer.flip()
+        if (sourceBuffer.hasRemaining) {
+          var result = ByteString.empty
+          while (sourceBuffer.hasRemaining) {
+            outputBuffer.clear()
+            decompressingStream.read(outputBuffer)
+            outputBuffer.flip()
+            val outputArray = new Array[Byte](outputBuffer.limit())
+            outputBuffer.get(outputArray)
+            result = result.concat(ByteString.fromArrayUnsafe(outputArray))
+          }
+
+          // Fencepost case, it's possible to still have 
sourceBuffer.hasRemaining and yet compression result
+          // not output anything
+          if (result.nonEmpty)
+            push(out, result)
+          else
+            pull(in)
+        } else pull(in)
+        sourceBuffer.flip()

Review Comment:
   The sourceBuffer is flipped after the while loop completes, but at this 
point sourceBuffer.hasRemaining is already false (the loop just exited). This 
flip operation serves no purpose and leaves the buffer in an incorrect state. 
It should be removed.
   ```suggestion
   
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdCompressor.scala:
##########
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import com.github.luben.zstd.{ Zstd, ZstdDictCompress, 
ZstdDirectBufferCompressingStreamNoFinalizer }
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.util.ByteString
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdCompressor(
+    compressionLevel: Int =
+      Zstd.defaultCompressionLevel(), dictionary: Option[ZstdDictCompress] = 
None) extends Compressor {
+
+  private val targetBuffer = ByteBuffer.allocateDirect(65536)
+  private val compressingStream = new 
ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, compressionLevel)
+
+  dictionary.foreach(compressingStream.setDict)
+
+  override def compress(input: ByteString): ByteString = {
+    val inputBB = ByteBuffer.allocateDirect(input.size)
+    inputBB.put(input.toArrayUnsafe())
+    inputBB.flip()
+    compressingStream.compress(input.asByteBuffer)
+    val result = ByteString.fromByteBuffer(targetBuffer)
+    targetBuffer.flip()

Review Comment:
   The targetBuffer should be flipped before reading from it with 
`fromByteBuffer`, not after. The current code reads from an unflipped buffer 
(in write mode) and then flips it, leaving the buffer in an incorrect state for 
subsequent operations.
   ```suggestion
       targetBuffer.flip()
       val result = ByteString.fromByteBuffer(targetBuffer)
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/scaladsl/Compression.scala:
##########
@@ -85,4 +87,28 @@ object Compression {
    */
   def inflate(maxBytesPerChunk: Int, nowrap: Boolean): Flow[ByteString, 
ByteString, NotUsed] =
     Flow[ByteString].via(new DeflateDecompressor(maxBytesPerChunk, 
nowrap)).named("inflate")
+
+  /**
+   * @since 2.0.0
+   */
+  def zstd: Flow[ByteString, ByteString, NotUsed] = 
zstd(Zstd.defaultCompressionLevel())
+
+  /**
+   * Same as [[zstd]] with a custom level and an optional dictionary.
+   * @param level The compression level, must be greater or equal to 
[[Zstd.minCompressionLevel]] and less than or equal
+   *              to [[Zstd.maxCompressionLevel]]
+   * @param dictionary An optional dictionary that can be used for compression
+   * @since 2.0.0
+   */
+  def zstd(level: Int, dictionary: Option[ZstdDictCompress] = None): 
Flow[ByteString, ByteString, NotUsed] = {
+    require(level <= Zstd.maxCompressionLevel() && level >= 
Zstd.minCompressionLevel())
+    CompressionUtils.compressorFlow(() => new ZstdCompressor(level, 
dictionary))
+  }
+
+  /**
+   * @since 2.0.0
+   */

Review Comment:
   Missing scaladoc description and parameter documentation. Following the 
pattern of `gzipDecompress` and `inflate`, this should include a description 
such as 'Creates a Flow that decompresses a zstd-compressed stream of data.' 
and document the `maxBytesPerChunk` parameter.
   ```suggestion
      */
     /**
      * Creates a Flow that decompresses a zstd-compressed stream of data.
      *
      * @param maxBytesPerChunk Maximum length of an output 
[[pekko.util.ByteString]] chunk.
      * @since 2.0.0
      */
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/javadsl/Compression.scala:
##########
@@ -81,4 +87,25 @@ object Compression {
   def deflate(level: Int, nowrap: Boolean): Flow[ByteString, ByteString, 
NotUsed] =
     scaladsl.Compression.deflate(level, nowrap).asJava
 
+  /**

Review Comment:
   Missing scaladoc description. This should include a description consistent 
with the Scala version, such as 'Creates a flow that zstd-compresses a stream 
of ByteStrings.'
   ```suggestion
     /**
      * Creates a flow that zstd-compresses a stream of ByteStrings.
      *
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/scaladsl/Compression.scala:
##########
@@ -85,4 +87,28 @@ object Compression {
    */
   def inflate(maxBytesPerChunk: Int, nowrap: Boolean): Flow[ByteString, 
ByteString, NotUsed] =
     Flow[ByteString].via(new DeflateDecompressor(maxBytesPerChunk, 
nowrap)).named("inflate")
+
+  /**
+   * @since 2.0.0
+   */
+  def zstd: Flow[ByteString, ByteString, NotUsed] = 
zstd(Zstd.defaultCompressionLevel())
+
+  /**
+   * Same as [[zstd]] with a custom level and an optional dictionary.
+   * @param level The compression level, must be greater or equal to 
[[Zstd.minCompressionLevel]] and less than or equal
+   *              to [[Zstd.maxCompressionLevel]]
+   * @param dictionary An optional dictionary that can be used for compression
+   * @since 2.0.0
+   */
+  def zstd(level: Int, dictionary: Option[ZstdDictCompress] = None): 
Flow[ByteString, ByteString, NotUsed] = {
+    require(level <= Zstd.maxCompressionLevel() && level >= 
Zstd.minCompressionLevel())

Review Comment:
   The require statement lacks a descriptive error message. Add a message 
explaining the valid compression level range, e.g., `require(level <= 
Zstd.maxCompressionLevel() && level >= Zstd.minCompressionLevel(), 
s\"Compression level must be between \${Zstd.minCompressionLevel()} and 
\${Zstd.maxCompressionLevel()}, but was $level\")`.
   ```suggestion
       require(
         level <= Zstd.maxCompressionLevel() && level >= 
Zstd.minCompressionLevel(),
         s"Compression level must be between ${Zstd.minCompressionLevel()} and 
${Zstd.maxCompressionLevel()}, but was $level"
       )
   ```



##########
stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/ZstdDecompressor.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.pekko.stream.impl.io.compression
+
+import java.nio.ByteBuffer
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.Attributes
+import pekko.stream.impl.fusing.GraphStages.SimpleLinearGraphStage
+import pekko.stream.stage.{ GraphStageLogic, InHandler, OutHandler }
+import pekko.util.ByteString
+
+import com.github.luben.zstd.ZstdDirectBufferDecompressingStreamNoFinalizer
+
+/** INTERNAL API */
+@InternalApi private[pekko] class ZstdDecompressor(maxBytesPerChunk: Int) 
extends SimpleLinearGraphStage[ByteString] {
+
+  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 
{
+    new GraphStageLogic(shape) with InHandler with OutHandler {
+
+      private val sourceBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+
+      // This is initialized here to avoid an allocation per onPush, remember 
to clear before using
+      private val outputBuffer = ByteBuffer.allocateDirect(maxBytesPerChunk)
+      private val decompressingStream = new 
ZstdDirectBufferDecompressingStreamNoFinalizer(sourceBuffer)
+
+      override def onPush(): Unit = {
+        sourceBuffer.clear()
+        val inputArray = grab(in).toArrayUnsafe()
+        sourceBuffer.put(inputArray)
+        sourceBuffer.flip()
+        if (sourceBuffer.hasRemaining) {
+          var result = ByteString.empty
+          while (sourceBuffer.hasRemaining) {
+            outputBuffer.clear()
+            decompressingStream.read(outputBuffer)
+            outputBuffer.flip()
+            val outputArray = new Array[Byte](outputBuffer.limit())
+            outputBuffer.get(outputArray)
+            result = result.concat(ByteString.fromArrayUnsafe(outputArray))
+          }
+
+          // Fencepost case, it's possible to still have 
sourceBuffer.hasRemaining and yet compression result
+          // not output anything
+          if (result.nonEmpty)
+            push(out, result)
+          else
+            pull(in)
+        } else pull(in)
+        sourceBuffer.flip()
+      }
+
+      override def onPull(): Unit = pull(in)
+
+      override def onUpstreamFinish(): Unit = {
+        sourceBuffer.flip()
+        if (sourceBuffer.hasRemaining) {
+          var result = ByteString.empty
+          while (sourceBuffer.hasRemaining) {
+            outputBuffer.clear()
+            decompressingStream.read(outputBuffer)
+            outputBuffer.flip()
+            val outputArray = new Array[Byte](outputBuffer.limit())
+            outputBuffer.get(outputArray)
+            result = result.concat(ByteString.fromArrayUnsafe(outputArray))
+          }
+          decompressingStream.close()
+
+          // Fencepost case, it's possible to still have 
sourceBuffer.hasRemaining and yet compression result

Review Comment:
   Comment refers to 'compression result' but this is decompression code. 
Should be 'decompression result'.



##########
stream/src/main/scala/org/apache/pekko/stream/scaladsl/Compression.scala:
##########
@@ -85,4 +87,28 @@ object Compression {
    */
   def inflate(maxBytesPerChunk: Int, nowrap: Boolean): Flow[ByteString, 
ByteString, NotUsed] =
     Flow[ByteString].via(new DeflateDecompressor(maxBytesPerChunk, 
nowrap)).named("inflate")
+
+  /**

Review Comment:
   Missing scaladoc description. Following the pattern of other methods in this 
file (like `gzip` and `deflate`), this should include a description such as 
'Creates a flow that zstd-compresses a stream of ByteStrings.'
   ```suggestion
     /**
      * Creates a flow that zstd-compresses a stream of ByteStrings using the 
default compression level.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to