
commonMain.io.ktor.util.Text.kt Maven / Gradle / Ivy
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
/**
* Escapes the characters in a String using HTML entities
*/
fun String.escapeHTML(): String {
val text = this@escapeHTML
if (text.isEmpty()) return text
return buildString(length) {
for (idx in 0 until text.length) {
val ch = text[idx]
when (ch) {
'\'' -> append("'")
'\"' -> append(""")
'&' -> append("&")
'<' -> append("<")
'>' -> append(">")
else -> append(ch)
}
}
}
}
/**
* Splits the given string into two parts before and after separator.
*
* Useful together with destructuring declarations
*/
inline fun String.chomp(separator: String, onMissingDelimiter: () -> Pair): Pair {
val idx = indexOf(separator)
return when (idx) {
-1 -> onMissingDelimiter()
else -> substring(0, idx) to substring(idx + 1)
}
}
internal fun String.caseInsensitive(): CaseInsensitiveString = CaseInsensitiveString(this)
internal class CaseInsensitiveString(val content: String) {
private val hash = content.toLowerCase().hashCode()
override fun equals(other: Any?): Boolean =
(other as? CaseInsensitiveString)?.content?.equals(content, ignoreCase = true) == true
override fun hashCode(): Int = hash
override fun toString(): String = content
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy