Skip to main content

Fs2 v2 text

Get extras-fs2-v2-text

It's only for Fs2 v2 so if you use v3, please use extras-fs2-v3-text.

"io.kevinlee" %% "extras-fs2-v2-text" % "0.44.0"

Stream[F, Byte].utf8String

Stream[F, Byte].utf8String // F[String]
import cats.effect._
import extras.fs2.text.syntax._
import fs2.Stream

import java.nio.charset.StandardCharsets

Stream[IO, Byte]("blah blah".getBytes(StandardCharsets.UTF_8).toList: _*)
.utf8String // IO[String]
.unsafeRunSync()
// res1: String = "blah blah"
import cats.effect._
import fs2.Stream

import java.nio.charset.StandardCharsets

def toByteStream[F[*]](s: String): Stream[F, Byte] =
Stream[F, Byte](s.getBytes(StandardCharsets.UTF_8).toList: _*)

def bytesToString[F[*]: Sync](stream: Stream[F, Byte]): F[String] = {
import extras.fs2.text.syntax._
stream.utf8String
}

val s = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
// s: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
val byteStream = toByteStream[IO](s)
// byteStream: Stream[IO, Byte] = Stream(..)

bytesToString[IO](byteStream)
.unsafeRunSync()
// res3: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."

utf8String for http4s

import org.http4s.dsl.io._
val response = Ok("Hello world!")
// response: cats.effect.IO[org.http4s.Response[cats.effect.IO]] = Pure(
// a = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Type: text/plain; charset=UTF-8, Content-Length: 12),
// = Stream(..),
// = org.typelevel.vault.Vault@3e78837
// )
// )
val responseToString = response
.flatMap { response =>
import extras.fs2.text.syntax._
response
.body
.utf8String
}
// responseToString: cats.effect.IO[String] = Bind(
// source = Pure(
// a = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Type: text/plain; charset=UTF-8, Content-Length: 12),
// = Stream(..),
// = org.typelevel.vault.Vault@3e78837
// ...
responseToString.unsafeRunSync()
// res5: String = "Hello world!"