Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more delimited IO helpers #30

Merged
merged 1 commit into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion stream/src/main/scala/eu/ostrzyciel/jelly/stream/JellyIo.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import eu.ostrzyciel.jelly.core.proto.v1.RdfStreamFrame
import org.apache.pekko.{Done, NotUsed}
import org.apache.pekko.stream.scaladsl.*

import java.io.OutputStream
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, OutputStream}
import scala.concurrent.Future

/**
Expand All @@ -29,6 +29,31 @@ object JellyIo:
def fromBytes: Flow[Array[Byte], RdfStreamFrame, NotUsed] =
Flow[Array[Byte]].map(RdfStreamFrame.parseFrom)

/**
* Convert a stream of Jelly frames into a stream of DELIMITED bytes.
*
* You can safely use this method to write to a file or socket.
* @return Pekko Flow
*/
def toBytesDelimited: Flow[RdfStreamFrame, Array[Byte], NotUsed] =
Flow[RdfStreamFrame].map(f => {
val os = ByteArrayOutputStream()
f.writeDelimitedTo(os)
os.toByteArray
})

/**
* Convert a stream of DELIMITED bytes into a stream of Jelly frames.
*
* You can safely use this method to read from a file or socket.
* @return Pekko Flow
*/
def fromBytesDelimited: Flow[Array[Byte], RdfStreamFrame, NotUsed] =
Flow[Array[Byte]].mapConcat(b => {
val is = ByteArrayInputStream(b)
RdfStreamFrame.parseDelimitedFrom(is)
})

/**
* Write a stream of Jelly frames to an output stream. The frames will be delimited.
*
Expand Down
13 changes: 13 additions & 0 deletions stream/src/test/scala/eu/ostrzyciel/jelly/stream/JellyIoSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ class JellyIoSpec extends AnyWordSpec, Matchers, ScalaFutures:
}
}

"toBytesDelimited and fromBytesDelimited" should {
for (name, testCase) <- cases do
s"work for $name" in {
val decoded = Source.fromIterator(() => testCase.iterator)
.via(JellyIo.toBytesDelimited)
.via(JellyIo.fromBytesDelimited)
.runWith(Sink.seq)
.futureValue

decoded shouldEqual testCase
}
}

"toIoStream and fromIoStream" should {
for (name, testCase) <- cases do
s"work for $name" in {
Expand Down