scoop:scoop.regex:0.1.0
src/replacement.scoop
Selected production source · src/replacement.scoop
1
package scoop.regex3
@CLayout internal struct NativeRegexText(4
val data: Ptr<UInt8>?, val length: Long, val code: Int, val offset: Long, val replacementError: Boolean5
)7
@Extern(name = "scoop_regex_substitute")8
private fun regexSubstitute(handle: ULong, input: Ptr<UInt8>, inputLength: Long,9
replacement: Ptr<UInt8>, replacementLength: Long, first: Boolean, literal: Boolean): NativeRegexText10
@Extern(name = "scoop_regex_text_free") private fun regexTextFree(data: Ptr<UInt8>?)12
/** Replaces every match with literal text. Dollar signs and backslashes are not template syntax. */13
public fun Regex.replace(input: String, replacement: String): String =14
substitute(this, input, replacement, false, true)16
/** Replaces the first match with literal text. */17
public fun Regex.replaceFirst(input: String, replacement: String): String =18
substitute(this, input, replacement, true, true)20
/** Replaces every match using PCRE2's default template syntax, including $1, ${name}, and $$. */21
public fun Regex.replaceTemplate(input: String, replacement: String): String =22
substitute(this, input, replacement, false, false)24
/** Replaces the first match using PCRE2's default template syntax. */25
public fun Regex.replaceFirstTemplate(input: String, replacement: String): String =26
substitute(this, input, replacement, true, false)28
private fun substitute(regex: Regex, input: String, replacement: String, first: Boolean, literal: Boolean): String {29
val owned = regex.checkedHandle()30
@Unsafe {31
return input.withUtf8Bytes { subject, subjectLength ->32
@Unsafe {33
return@withUtf8Bytes replacement.withUtf8Bytes { text, textLength ->34
@Unsafe {35
val output = regexSubstitute(owned, subject, subjectLength, text, textLength, first, literal)36
try {37
if (output.code < 0) {38
if (!output.replacementError) throw matchFailure(output.code)39
val offset = if (output.offset < 0L) None else40
Some(RegexInput(replacement).scalarOffset(output.offset, text, textLength))41
throw RegexReplacementException(output.code, regexDetail(output.code), offset)42
}43
if (output.code == 0) return@withUtf8Bytes input44
return@withUtf8Bytes String.fromUtf8(output.data!!, output.length)45
} finally { regexTextFree(output.data) }46
}47
}48
}49
}50
}51
}