summaryrefslogtreecommitdiff
path: root/examples/scala-js/library/src/main/scala/scala/scalajs/runtime/RuntimeString.scala
blob: f65b1b59ebe8fe8947e0fc00cb53ad2b4b4dbe88 (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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package scala.scalajs.runtime

import scala.scalajs.js
import scala.scalajs.js.prim.{String => jsString}

import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.util.regex._

/** Implementation for methods on java.lang.String.
 *
 *  Strings are represented at runtime by JavaScript strings, but they have
 *  a lot of methods. The compiler forwards methods on java.lang.String to the
 *  methods in the object, passing `this` as the first argument, that we
 *  consistently call `thiz` in this object.
 */
private[runtime] object RuntimeString {

  @inline
  def charAt(thiz: String, index: Int): Char =
    (thiz: jsString).charCodeAt(index).asInstanceOf[Int].toChar

  def codePointAt(thiz: String, index: Int): Int = {
    val high = thiz.charAt(index)
    if (index+1 < thiz.length) {
      val low = thiz.charAt(index+1)
      if (Character.isSurrogatePair(high, low))
        Character.toCodePoint(high, low)
      else
        high.toInt
    } else {
      high.toInt
    }
  }

  def hashCode(thiz: String): Int = {
    var res = 0
    var mul = 1 // holds pow(31, length-i-1)
    var i = thiz.length-1
    while (i >= 0) {
      res += thiz.charAt(i) * mul
      mul *= 31
      i -= 1
    }
    res
  }

  @inline
  def compareTo(thiz: String, anotherString: String): Int = {
    if (thiz.equals(anotherString)) 0
    else if ((thiz: jsString) < (anotherString: jsString)) -1
    else 1
  }

  def compareToIgnoreCase(thiz: String, str: String): Int =
    thiz.toLowerCase().compareTo(str.toLowerCase())

  @inline
  def equalsIgnoreCase(thiz: String, that: String): Boolean =
    thiz.toLowerCase() == (if (that == null) null else that.toLowerCase())

  @inline
  def concat(thiz: String, s: String): String =
    checkNull(thiz) + s

  @inline
  def contains(thiz: String, s: CharSequence): Boolean =
    thiz.indexOf(s.toString) != -1

  def endsWith(thiz: String, suffix: String): Boolean =
    ((thiz: jsString).substring(thiz.length - suffix.length): String) == suffix

  def getBytes(thiz: String): Array[Byte] =
    thiz.getBytes(Charset.defaultCharset)

  def getBytes(thiz: String, charsetName: String): Array[Byte] =
    thiz.getBytes(Charset.forName(charsetName))

  def getBytes(thiz: String, charset: Charset): Array[Byte] =
    charset.encode(thiz).array()

  def getChars(thiz: String, srcBegin: Int, srcEnd: Int,
      dst: Array[Char], dstBegin: Int): Unit = {
    if (srcEnd   > thiz.length || // first test uses thiz
        srcBegin < 0 ||
        srcEnd   < 0 ||
        srcBegin > srcEnd) {
      throw new StringIndexOutOfBoundsException("Index out of Bound")
    }

    val offset = dstBegin - srcBegin
    var i = srcBegin
    while (i < srcEnd) {
      dst(i+offset) = thiz.charAt(i)
      i += 1
    }
  }

  def indexOf(thiz: String, ch: Int): Int =
    thiz.indexOf(fromCodePoint(ch))

  def indexOf(thiz: String, ch: Int, fromIndex: Int): Int =
    thiz.indexOf(fromCodePoint(ch), fromIndex)

  @inline
  def indexOf(thiz: String, str: String): Int =
    (thiz: jsString).indexOf(str).asInstanceOf[Int]

  @inline
  def indexOf(thiz: String, str: String, fromIndex: Int): Int =
    (thiz: jsString).indexOf(str, fromIndex).asInstanceOf[Int]

  /* Just returning this string is a valid implementation for `intern` in
   * JavaScript, since strings are primitive values. Therefore, value equality
   * and reference equality is the same.
   */
  @inline
  def intern(thiz: String): String =
    checkNull(thiz)

  @inline
  def isEmpty(thiz: String): Boolean =
    checkNull(thiz) == ""

  def lastIndexOf(thiz: String, ch: Int): Int =
    thiz.lastIndexOf(fromCodePoint(ch))

  def lastIndexOf(thiz: String, ch: Int, fromIndex: Int): Int =
    thiz.lastIndexOf(fromCodePoint(ch), fromIndex)

  @inline
  def lastIndexOf(thiz: String, str: String): Int =
    (thiz: jsString).lastIndexOf(str).asInstanceOf[Int]

  @inline
  def lastIndexOf(thiz: String, str: String, fromIndex: Int): Int =
    (thiz: jsString).lastIndexOf(str, fromIndex).asInstanceOf[Int]

  @inline
  def length(thiz: String): Int =
    (thiz: jsString).length.asInstanceOf[Int]

  @inline
  def matches(thiz: String, regex: String): Boolean = {
    checkNull(thiz)
    Pattern.matches(regex, thiz)
  }

  @inline
  def replace(thiz: String, oldChar: Char, newChar: Char): String =
    (thiz: String).replace(oldChar.toString, newChar.toString)

  @inline
  def replace(thiz: String, target: CharSequence, replacement: CharSequence): String =
    (thiz: jsString).split(target.toString).join(replacement.toString)

  def replaceAll(thiz: String, regex: String, replacement: String): String = {
    checkNull(thiz)
    Pattern.compile(regex).matcher(thiz).replaceAll(replacement)
  }

  def replaceFirst(thiz: String, regex: String, replacement: String): String = {
    checkNull(thiz)
    Pattern.compile(regex).matcher(thiz).replaceFirst(replacement)
  }

  @inline
  def split(thiz: String, regex: String): Array[String] =
    thiz.split(regex, 0)

  def split(thiz: String, regex: String, limit: Int): Array[String] = {
    checkNull(thiz)
    Pattern.compile(regex).split(thiz, limit)
  }

  @inline
  def startsWith(thiz: String, prefix: String): Boolean =
    thiz.startsWith(prefix, 0)

  @inline
  def startsWith(thiz: String, prefix: String, toffset: Int): Boolean =
    ((thiz: jsString).substring(toffset, prefix.length): String) == prefix

  @inline
  def subSequence(thiz: String, beginIndex: Int, endIndex: Int): CharSequence =
    thiz.substring(beginIndex, endIndex)

  @inline
  def substring(thiz: String, beginIndex: Int): String =
    (thiz: jsString).substring(beginIndex)

  @inline
  def substring(thiz: String, beginIndex: Int, endIndex: Int): String =
    (thiz: jsString).substring(beginIndex, endIndex)

  def toCharArray(thiz: String): Array[Char] = {
    val length = thiz.length
    val result = new Array[Char](length)
    var i = 0
    while (i < length) {
      result(i) = thiz.charAt(i)
      i += 1
    }
    result
  }

  @inline
  def toLowerCase(thiz: String): String =
    (thiz: jsString).toLowerCase()

  @inline
  def toUpperCase(thiz: String): String =
    (thiz: jsString).toUpperCase()

  @inline
  def trim(thiz: String): String =
    (thiz: jsString).trim()

  // Constructors

  def newString(): String = ""

  def newString(value: Array[Char]): String =
    newString(value, 0, value.length)

  def newString(value: Array[Char], offset: Int, count: Int): String = {
    val end = offset + count
    if (offset < 0 || end < offset || end > value.length)
      throw new StringIndexOutOfBoundsException

    val charCodes = new js.Array[Int]
    var i = offset
    while (i != end) {
      charCodes += value(i).toInt
      i += 1
    }
    js.String.fromCharCode(charCodes: _*)
  }

  def newString(bytes: Array[Byte]): String =
    newString(bytes, Charset.defaultCharset)

  def newString(bytes: Array[Byte], charsetName: String): String =
    newString(bytes, Charset.forName(charsetName))

  def newString(bytes: Array[Byte], charset: Charset): String =
    charset.decode(ByteBuffer.wrap(bytes)).toString()

  def newString(bytes: Array[Byte], offset: Int, length: Int): String =
    newString(bytes, offset, length, Charset.defaultCharset)

  def newString(bytes: Array[Byte], offset: Int, length: Int,
      charsetName: String): String =
    newString(bytes, offset, length, Charset.forName(charsetName))

  def newString(bytes: Array[Byte], offset: Int, length: Int,
      charset: Charset): String =
    charset.decode(ByteBuffer.wrap(bytes, offset, length)).toString()

  def newString(codePoints: Array[Int], offset: Int, count: Int): String = {
    val end = offset + count
    if (offset < 0 || end < offset || end > codePoints.length)
      throw new StringIndexOutOfBoundsException

    val charCodes = new js.Array[Int]
    var i = offset
    while (i != end) {
      val cp = codePoints(i)
      if (cp < 0 || cp > Character.MAX_CODE_POINT)
        throw new IllegalArgumentException
      if (cp <= Character.MAX_VALUE) {
        charCodes += cp
      } else {
        val offsetCp = cp - 0x10000
        charCodes += (offsetCp >> 10) | 0xd800
        charCodes += (offsetCp & 0x3ff) | 0xdc00
      }
      i += 1
    }
    js.String.fromCharCode(charCodes: _*)
  }

  def newString(original: String): String =
    checkNull(original)

  def newString(buffer: java.lang.StringBuffer): String =
    buffer.toString

  def newString(builder: java.lang.StringBuilder): String =
    builder.toString

  // Static methods (aka methods on the companion object)

  def valueOf(value: Boolean): String = value.toString()
  def valueOf(value: Char): String    = value.toString()
  def valueOf(value: Byte): String    = value.toString()
  def valueOf(value: Short): String   = value.toString()
  def valueOf(value: Int): String     = value.toString()
  def valueOf(value: Long): String    = value.toString()
  def valueOf(value: Float): String   = value.toString()
  def valueOf(value: Double): String  = value.toString()

  def valueOf(value: Object): String =
    if (value eq null) "null" else value.toString()

  def valueOf(data: Array[Char]): String =
    valueOf(data, 0, data.length)

  def valueOf(data: Array[Char], offset: Int, count: Int): String =
    newString(data, offset, count)

  def format(format: String, args: Array[AnyRef]): String = {
    val frm = new java.util.Formatter()
    val res = frm.format(format, args: _*).toString()
    frm.close()
    res
  }

  // Helpers

  @inline
  private def checkNull(s: String): s.type =
    if (s == null) throw new NullPointerException()
    else s

  private def fromCodePoint(codePoint: Int): String = {
    if ((codePoint & ~Character.MAX_VALUE) == 0)
      js.String.fromCharCode(codePoint)
    else if (codePoint < 0 || codePoint > Character.MAX_CODE_POINT)
      throw new IllegalArgumentException
    else {
      val offsetCp = codePoint - 0x10000
      js.String.fromCharCode(
          (offsetCp >> 10) | 0xd800, (offsetCp & 0x3ff) | 0xdc00)
    }
  }

}