Scoop API

scoop:scoop.std:0.1.0

src/text/replace.scoop

Selected production source · src/text/replace.scoop

1package scoop.text
3private class ReplacementOutput {
4 private val chars: ArrayList<Char> = ArrayList<Char>()
5 private var bytes: Long = 0L
7 fun add(value: Char) {
8 bytes = checkedTextSum(bytes, charByteLength(value))
9 chars.add(value)
10 }
12 fun addRange(source: List<Char>, start: Long, end: Long) {
13 var index = start
14 while (index < end) { add(source[index]); index += 1L }
15 }
17 fun build(): String = String.fromChars(chars)
20private fun String.replaceText(oldValue: String, newValue: String, firstOnly: Boolean): String {
21 if (oldValue == newValue) return this
22 val chars = toCharArray()
23 val replacement = newValue.toCharArray()
24 val pattern = TextPattern(oldValue)
25 val output = ReplacementOutput()
26 if (pattern.size == 0L) {
27 output.addRange(replacement, 0L, replacement.size)
28 for (value in chars) {
29 output.add(value)
30 if (!firstOnly) output.addRange(replacement, 0L, replacement.size)
31 }
32 return output.build()
33 }
34 var start = 0L
35 var index = 0L
36 var matched = 0L
37 while (index < chars.size) {
38 matched = pattern.advance(matched, chars[index])
39 index += 1L
40 if (matched == pattern.size) {
41 output.addRange(chars, start, index - pattern.size)
42 output.addRange(replacement, 0L, replacement.size)
43 start = index
44 matched = 0L
45 if (firstOnly) break
46 }
47 }
48 if (start == 0L) return this
49 output.addRange(chars, start, chars.size)
50 return output.build()
53/**
54 * Replaces all nonoverlapping literal matches; this operation does not interpret a regular
55 * expression.
56 */
57public fun String.replace(oldValue: String, newValue: String): String = replaceText(oldValue, newValue, false)
58/**
59 * Replaces the first literal match, leaving later matches unchanged.
60 */
61public fun String.replaceFirst(oldValue: String, newValue: String): String = replaceText(oldValue, newValue, true)
62/**
63 * Replaces all nonoverlapping literal matches; this operation does not interpret a regular
64 * expression.
65 */
66public fun String.replace(oldValue: Char, newValue: Char): String = replace(oldValue.toString(), newValue.toString())
67/**
68 * Replaces the first literal match, leaving later matches unchanged.
69 */
70public fun String.replaceFirst(oldValue: Char, newValue: Char): String = replaceFirst(oldValue.toString(), newValue.toString())