package eu.friedcutlet.yokan.util private val htmlEntityRegex = Regex("&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);") private val namedHtmlEntities = mapOf( "nbsp" to " ", "amp" to "&", "lt" to "<", "gt" to ">", "quot" to "\"", "apos" to "'", "copy" to "©", "reg" to "®", "mdash" to "—", "ndash" to "–", "hellip" to "…", "rsquo" to "’", "lsquo" to "‘", "ldquo" to "“", "rdquo" to "”", "trade" to "™", ) /** * Decodes numeric (`'`, `'`) and common named HTML entities in one pass, so `&quot;` * stays `"`. Unknown or out-of-range entities are kept verbatim; ` ` becomes a plain space. */ internal fun decodeHtmlEntities(value: String): String { if ('&' !in value) return value return value.replace(htmlEntityRegex) { match -> val entity = match.groupValues[1] if (!entity.startsWith('#')) return@replace namedHtmlEntities[entity.lowercase()] ?: match.value val code = if (entity.startsWith("#x", ignoreCase = true)) entity.drop(2).toIntOrNull(16) else entity.drop(1).toIntOrNull() when { code == null || code !in 0..0x10FFFF -> match.value code <= Char.MAX_VALUE.code -> code.toChar().toString() else -> { val shifted = code - 0x10000 "${(0xD800 + (shifted shr 10)).toChar()}${(0xDC00 + (shifted and 0x3FF)).toChar()}" } } } }