Skip to content

Commit

Permalink
use ByteStringInputStream
Browse files Browse the repository at this point in the history
  • Loading branch information
pjfanning committed May 20, 2024
1 parent 2ef115e commit 2e99d68
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/

/*
* Copyright (C) 2009-2022 Lightbend Inc. <https://www.lightbend.com>
*/

package org.apache.pekko.grpc.internal

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

import scala.util.Try

import org.apache.pekko
import pekko.annotation.InternalApi
import pekko.util.ByteString
import pekko.util.ByteString.ByteString1C

/** INTERNAL API */
@InternalApi
private[internal] object ByteStringInputStream {

private 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 = bs match {
case cs: ByteString1C =>
getInputStreamUnsafe(cs)
case _ =>
if (byteStringInputStreamMethodTypeOpt.isDefined) {
byteStringInputStreamMethodTypeOpt.get.invoke(bs).asInstanceOf[InputStream]
} else {
legacyConvert(bs.compact)
}
}

private def legacyConvert(bs: ByteString): InputStream = bs match {
case cs: ByteString1C =>
getInputStreamUnsafe(cs)
case _ =>
// NOTE: We actually measured recently, and compact + use array was pretty good usually
legacyConvert(bs.compact)
}

private def getInputStreamUnsafe(bs: ByteString): InputStream =
new ByteArrayInputStream(bs.toArrayUnsafe())

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ object Gzip extends Codec {
}

override def uncompress(compressed: ByteString): ByteString = {
val gzis = new GZIPInputStream(new ByteArrayInputStream(compressed.toArrayUnsafe()))
val gzis = new GZIPInputStream(ByteStringInputStream(compressed))

val baos = new ByteArrayOutputStream(compressed.size)
val buffer = new Array[Byte](32 * 1024)
Expand Down

0 comments on commit 2e99d68

Please sign in to comment.