-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
runtime/src/main/scala/org/apache/pekko/grpc/internal/ByteStringInputStream.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters