Scoop API

scoop:scoop.regex:0.1.0

src/replacement.scoop

Selected production source · src/replacement.scoop

1package scoop.regex
3@CLayout internal struct NativeRegexText(
4 val data: Ptr<UInt8>?, val length: Long, val code: Int, val offset: Long, val replacementError: Boolean
5)
7@Extern(name = "scoop_regex_substitute")
8private fun regexSubstitute(handle: ULong, input: Ptr<UInt8>, inputLength: Long,
9 replacement: Ptr<UInt8>, replacementLength: Long, first: Boolean, literal: Boolean): NativeRegexText
10@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. */
13public fun Regex.replace(input: String, replacement: String): String =
14 substitute(this, input, replacement, false, true)
16/** Replaces the first match with literal text. */
17public 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 $$. */
21public 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. */
25public fun Regex.replaceFirstTemplate(input: String, replacement: String): String =
26 substitute(this, input, replacement, true, false)
28private 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 else
40 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 input
44 return@withUtf8Bytes String.fromUtf8(output.data!!, output.length)
45 } finally { regexTextFree(output.data) }
46 }
47 }
48 }
49 }
50 }