Skip to content
This repository has been archived by the owner on Mar 16, 2022. It is now read-only.

Commit

Permalink
Upgrading to the buildin Base64 encode/decode in ByteString (#348)
Browse files Browse the repository at this point in the history
  • Loading branch information
viktorklang authored Jun 5, 2020
1 parent 84b8e9b commit eaf46d6
Showing 1 changed file with 5 additions and 11 deletions.
16 changes: 5 additions & 11 deletions proxy/core/src/main/scala/io/cloudstate/proxy/GrpcWebSupport.scala
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ object GrpcWebSupport {
private def decodeText(newContentType: ContentType, entity: MessageEntity): MessageEntity =
entity match {
case HttpEntity.Strict(_, data) =>
HttpEntity.Strict(newContentType, base64Decode(data))
HttpEntity.Strict(newContentType, data.decodeBase64)
case streamed =>
HttpEntity.Chunked.fromData(newContentType, streamed.dataBytes.via(new Base64DecoderStage))
}
Expand All @@ -120,18 +120,12 @@ object GrpcWebSupport {
.get
entity match {
case HttpEntity.Strict(_, data) =>
HttpEntity.Strict(contentType, base64Encode(data))
HttpEntity.Strict(contentType, data.encodeBase64)
case streamed =>
HttpEntity.Chunked.fromData(contentType, streamed.dataBytes.map(base64Encode))
HttpEntity.Chunked.fromData(contentType, streamed.dataBytes.map(_.encodeBase64))
}
}

private def base64Encode(bytes: ByteString): ByteString =
ByteString(Base64.getEncoder.encode(bytes.asByteBuffer))

private def base64Decode(bytes: ByteString): ByteString =
ByteString(Base64.getDecoder.decode(bytes.asByteBuffer))

private class Base64DecoderStage extends GraphStage[FlowShape[ByteString, ByteString]] {

private val in = Inlet[ByteString]("Base64Decoder.in")
Expand Down Expand Up @@ -162,7 +156,7 @@ object GrpcWebSupport {
bytes.take(nextSize)
}

push(out, base64Decode(next))
push(out, next.decodeBase64)
}
}

Expand All @@ -171,7 +165,7 @@ object GrpcWebSupport {
if (carry.nonEmpty) {
carryOver = ByteString.empty // Clear this out to not retain it beyond this point
// This will fail, but we let it so we get the base64 error.
emit(out, base64Decode(carry), () => completeStage())
emit(out, carry.decodeBase64, () => completeStage())
} else {
completeStage()
}
Expand Down

0 comments on commit eaf46d6

Please sign in to comment.