scoop:scoop.std:0.1.0
src/text/replace.scoop
Selected production source · src/text/replace.scoop
1
package scoop.text3
private class ReplacementOutput {4
private val chars: ArrayList<Char> = ArrayList<Char>()5
private var bytes: Long = 0L7
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 = start14
while (index < end) { add(source[index]); index += 1L }15
}17
fun build(): String = String.fromChars(chars)18
}20
private fun String.replaceText(oldValue: String, newValue: String, firstOnly: Boolean): String {21
if (oldValue == newValue) return this22
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 = 0L35
var index = 0L36
var matched = 0L37
while (index < chars.size) {38
matched = pattern.advance(matched, chars[index])39
index += 1L40
if (matched == pattern.size) {41
output.addRange(chars, start, index - pattern.size)42
output.addRange(replacement, 0L, replacement.size)43
start = index44
matched = 0L45
if (firstOnly) break46
}47
}48
if (start == 0L) return this49
output.addRange(chars, start, chars.size)50
return output.build()51
}53
/**54
* Replaces all nonoverlapping literal matches; this operation does not interpret a regular55
* expression.56
*/57
public fun String.replace(oldValue: String, newValue: String): String = replaceText(oldValue, newValue, false)58
/**59
* Replaces the first literal match, leaving later matches unchanged.60
*/61
public 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 regular64
* expression.65
*/66
public 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
*/70
public fun String.replaceFirst(oldValue: Char, newValue: Char): String = replaceFirst(oldValue.toString(), newValue.toString())