Skip to content

Commit

Permalink
use optimised ByteString.asInputStream
Browse files Browse the repository at this point in the history
Update Http2FrameHpackSupport.scala

Update ByteStringInputStream.scala

revert Http2FrameHpackSupport change

Update ByteStringInputStream.scala

Update ByteStringInputStream.scala
  • Loading branch information
pjfanning committed Apr 19, 2024
1 parent 9505d4e commit 246f4f8
Showing 1 changed file with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
package org.apache.pekko.http.impl.engine.http2.hpack

import java.io.{ ByteArrayInputStream, InputStream }
import java.lang.invoke.{ MethodHandles, MethodType }

import scala.util.Try

import org.apache.pekko
import pekko.annotation.InternalApi
Expand All @@ -24,10 +27,22 @@ import pekko.util.ByteString.ByteString1C
@InternalApi
private[http2] object ByteStringInputStream {

private lazy val byteStringInputStreamMethodTypeOpt = Try {
val lookup = MethodHandles.publicLookup()
val inputStreamMethodType = MethodType.methodType(classOf[InputStream])
lookup.findVirtual(classOf[ByteString], "asInputStream", inputStreamMethodType)
}.toOption

def apply(bs: ByteString): InputStream =
byteStringInputStreamMethodTypeOpt.map { mh =>
mh.invoke(bs).asInstanceOf[InputStream]
}.getOrElse {
legacyConvert(bs)
}

private def legacyConvert(bs: ByteString): InputStream =
bs match {
case cs: ByteString1C =>
// TODO optimise, ByteString needs to expose InputStream (esp if array backed, nice!)
new ByteArrayInputStream(cs.toArrayUnsafe())
case _ =>
// NOTE: We actually measured recently, and compact + use array was pretty good usually
Expand Down

0 comments on commit 246f4f8

Please sign in to comment.