Skip to main content

Fs2 v3 text

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

"io.kevinlee" %% "extras-fs2-v3-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

import cats.effect.unsafe.implicits.global

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

import cats.effect.unsafe.implicits.global

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._
import cats.effect.unsafe.implicits.global

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