Skip to content

Commit

Permalink
Deduplicate code
Browse files Browse the repository at this point in the history
  • Loading branch information
satabin committed Jan 31, 2024
1 parent e5ed37a commit 1f10182
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 50 deletions.
50 changes: 1 addition & 49 deletions json/src/main/scala/fs2/data/json/internal/Renderer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,9 @@ package data
package json
package internals

import scala.annotation.{switch, tailrec}

private[json] class Renderer(pretty: Boolean, resetOnChunk: Boolean, indent: String)
extends Collector.Builder[Token, String] {

import Renderer._

private val builder = new StringBuilder

private var level = 0
Expand All @@ -41,51 +37,9 @@ private[json] class Renderer(pretty: Boolean, resetOnChunk: Boolean, indent: Str
}

private def jsonString(s: String, key: Boolean): Unit = {
@tailrec
def loop(idx: Int): Unit =
if (idx < s.length) {
val nextEscape = s.indexWhere(c => c > 127 || Character.isISOControl(c) || "\\/\b\f\n\r\t\"".contains(c), idx)
if (nextEscape >= 0) {
if (nextEscape > 0) {
builder.append(s.substring(idx, nextEscape))
}
val c = s(nextEscape)
(c: @switch) match {
case '\\' =>
builder.append("\\\\")
case '/' =>
builder.append("\\/")
case '\b' =>
builder.append("\\b")
case '\f' =>
builder.append("\\f")
case '\n' =>
builder.append("\\n")
case '\r' =>
builder.append("\\r")
case '\t' =>
builder.append("\\t")
case '"' =>
builder.append("\\\"")
case _ =>
// escape non ascii or control characters
builder
.append("\\u")
.append(hex((c >> 12) & 0x0f))
.append(hex((c >> 8) & 0x0f))
.append(hex((c >> 4) & 0x0f))
.append(hex(c & 0x0f))
}
loop(nextEscape + 1)
} else {
// append the rest of the string and we are done
builder.append(s.substring(idx))
}
}

prefixValue()
builder.append('"')
loop(0)
Token.renderString(s, 0, builder)
builder.append('"')

if (key) {
Expand Down Expand Up @@ -172,8 +126,6 @@ private[json] class Renderer(pretty: Boolean, resetOnChunk: Boolean, indent: Str

private[json] object Renderer {

private val hex = "0123456789abcdef"

def pipe[F[_]](pretty: Boolean, indent: String): Pipe[F, Token, String] =
in =>
Stream.suspend(Stream.emit(new Renderer(pretty, true, indent))).flatMap { builder =>
Expand Down
2 changes: 1 addition & 1 deletion json/src/main/scala/fs2/data/json/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ package object json {
*/
@deprecated(message = "Consider using `fs2.data.json.render.prettyPrint` instead.", since = "fs2-data 1.11.0")
def pretty[F[_]](indent: String = " "): Pipe[F, Token, String] =
_.through(fs2.data.text.render.pretty(width = 0)(Token.compact))
Renderer.pipe[F](true, indent)

/** Renders a pretty-printed representation of the token stream with the given
* indentation size and page width.
Expand Down

0 comments on commit 1f10182

Please sign in to comment.