summaryrefslogtreecommitdiff
path: root/src/main/scala/spray/json/JsonPrinter.scala
blob: bc1e37590434e0bc9befba5e3db8141cbc001e17 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
 * Copyright (C) 2009-2011 Mathias Doenitz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package spray.json

import annotation.tailrec
import java.lang.StringBuilder

/**
  * A JsonPrinter serializes a JSON AST to a String.
 */
trait JsonPrinter extends (JsValue => String) {

  def apply(x: JsValue): String = apply(x, None)

  def apply(x: JsValue, jsonpCallback: String): String = apply(x, Some(jsonpCallback))

  def apply(x: JsValue, jsonpCallback: Option[String]): String = {
    val sb = new StringBuilder
    jsonpCallback match {
      case Some(callback) => {
        sb.append(callback).append('(')
        print(x, sb)
        sb.append(')');
      }
      case None => print(x, sb)
    }
    sb.toString
  }
  
  def print(x: JsValue, sb: StringBuilder)
  
  protected def printLeaf(x: JsValue, sb: StringBuilder) {
    x match {
      case JsNull      => sb.append("null")
      case JsTrue      => sb.append("true")
      case JsFalse     => sb.append("false")
      case JsNumber(x) => sb.append(x)
      case JsString(x) => printString(x, sb)
      case _           => throw new IllegalStateException
    }
  }

  protected def printString(s: String, sb: StringBuilder) {
    import JsonPrinter._
    @tailrec def firstToBeEncoded(ix: Int = 0): Int =
      if (ix == s.length) -1 else if (requiresEncoding(s.charAt(ix))) ix else firstToBeEncoded(ix + 1)

    sb.append('"')
    firstToBeEncoded() match {
      case -1  sb.append(s)
      case first 
        sb.append(s, 0, first)
        @tailrec def append(ix: Int): Unit =
          if (ix < s.length) {
            s.charAt(ix) match {
              case c if !requiresEncoding(c) => sb.append(c)
              case '"' => sb.append("\\\"")
              case '\\' => sb.append("\\\\")
              case '\b' => sb.append("\\b")
              case '\f' => sb.append("\\f")
              case '\n' => sb.append("\\n")
              case '\r' => sb.append("\\r")
              case '\t' => sb.append("\\t")
              case x if x <= 0xF => sb.append("\\u000").append(Integer.toHexString(x))
              case x if x <= 0xFF => sb.append("\\u00").append(Integer.toHexString(x))
              case x if x <= 0xFFF => sb.append("\\u0").append(Integer.toHexString(x))
              case x => sb.append("\\u").append(Integer.toHexString(x))
            }
            append(ix + 1)
          }
        append(first)
    }
    sb.append('"')
  }
  
  protected def printSeq[A](iterable: Iterable[A], printSeparator: => Unit)(f: A => Unit) {
    var first = true
    iterable.foreach { a =>
      if (first) first = false else printSeparator
      f(a)
    }
  }
}

object JsonPrinter {
  private[this] val mask = new Array[Int](4)
  private[this] def ascii(c: Char): Int = c & ((c - 127) >> 31) // branchless for `if (c <= 127) c else 0`
  private[this] def mark(c: Char): Unit = {
    val b = ascii(c)
    mask(b >> 5) |= 1 << (b & 0x1F)
  }
  private[this] def mark(range: scala.collection.immutable.NumericRange[Char]): Unit = range foreach (mark)

  mark('\u0000' to '\u001f')
  mark('\u007f')
  mark('"')
  mark('\\')

  def requiresEncoding(c: Char): Boolean = {
    val b = ascii(c)
    (mask(b >> 5) & (1 << (b & 0x1F))) != 0
  }
}