This is an automated email from the ASF dual-hosted git repository.

pjfanning pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/pekko.git


The following commit(s) were added to refs/heads/main by this push:
     new 3183f6d5f4 improve ByteString slice method (#3428)
3183f6d5f4 is described below

commit 3183f6d5f4030e051f150774c13f70139f3da86c
Author: PJ Fanning <[email protected]>
AuthorDate: Sat Aug 15 13:32:00 2026 +0100

    improve ByteString slice method (#3428)
---
 .../scala/org/apache/pekko/util/ByteString.scala   | 32 +++++++++++++++++++---
 1 file changed, 28 insertions(+), 4 deletions(-)

diff --git a/actor/src/main/scala/org/apache/pekko/util/ByteString.scala 
b/actor/src/main/scala/org/apache/pekko/util/ByteString.scala
index 39035af217..bf551fe380 100644
--- a/actor/src/main/scala/org/apache/pekko/util/ByteString.scala
+++ b/actor/src/main/scala/org/apache/pekko/util/ByteString.scala
@@ -1576,10 +1576,34 @@ object ByteString {
       dropRightWithFullDropsAndRemainig(0, n)
     }
 
-    override def slice(from: Int, until: Int): ByteString =
-      if (from <= 0 && until >= length) this
-      else if (from > length || until <= from) ByteString.empty
-      else drop(from).dropRight(length - until)
+    override def slice(from: Int, until: Int): ByteString = {
+      val lo = math.max(from, 0)
+      val hi = math.min(until, length)
+      if (lo >= hi) ByteString.empty
+      else if (lo == 0 && hi == length) this
+      else {
+        // locate start fragment
+        var fragIdx = 0
+        var fragOff = lo
+        while (fragOff >= bytestrings(fragIdx).length) {
+          fragOff -= bytestrings(fragIdx).length
+          fragIdx += 1
+        }
+        val builder = new VectorBuilder[ByteString1]
+        var remaining = hi - lo
+        var firstOff = fragOff
+        while (remaining > 0) {
+          val frag = bytestrings(fragIdx)
+          val take = math.min(remaining, frag.length - firstOff)
+          builder += (if (firstOff == 0 && take == frag.length) frag
+                      else frag.drop1(firstOff).take1(take))
+          remaining -= take
+          fragIdx += 1
+          firstOff = 0
+        }
+        ByteStrings(builder.result(), hi - lo)
+      }
+    }
 
     override def drop(n: Int): ByteString =
       if (n <= 0) this


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

Reply via email to