scoop:scoop.regex:0.1.0
src/callbacks.scoop
Selected production source · src/callbacks.scoop
1
package scoop.regex3
/**4
* Replaces every match with a callback result. Callbacks run after the native match and borrow5
* have ended; exceptions propagate without returning partial output.6
*/7
public fun Regex.replace(input: String, transform: (MatchResult) -> String): String =8
callbackReplacement(this, input, false, transform)10
/** Replaces the first match with a callback result, after ending the native input borrow. */11
public fun Regex.replaceFirst(input: String, transform: (MatchResult) -> String): String =12
callbackReplacement(this, input, true, transform)14
private fun callbackReplacement(regex: Regex, input: String, first: Boolean, transform: (MatchResult) -> String): String {15
val output = StringBuilder()16
var position = 0L17
var replaced = false18
for (match in regex.findAll(input)) {19
output.append(regexSlice(input, position, match.byteStart))20
output.append(transform(match))21
position = match.byteEnd22
replaced = true23
if (first) break24
}25
if (!replaced) return input26
output.append(regexSlice(input, position, input.byteLength))27
return output.toString()28
}30
internal fun regexSlice(input: String, start: Long, end: Long): String {31
@Unsafe {32
return input.withUtf8Bytes { bytes, _ ->33
@Unsafe { return@withUtf8Bytes String.fromUtf8(bytes + start, end - start) }34
}35
}36
}