You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CaseMapping.kt 1.4KB

1234567891011121314151617181920212223242526272829303132333435
  1. package com.dmdirc.ktirc.io
  2. /**
  3. * Supported options for mapping between uppercase and lowercase characters.
  4. */
  5. enum class CaseMapping(private val lowerToUpperMapping: Pair<IntRange, IntRange>) {
  6. /** Standard ASCII mapping, `a-z` is mapped to `A-Z`. */
  7. Ascii(97..122 to 65..90),
  8. /** Mapping probably intended by RFC14159, `a-z{|}~` is mapped to `A-Z[\]^`. */
  9. Rfc(97..126 to 65..94),
  10. /** Mapping according to a strict interpretation of RFC14159, `a-z{|}` is mapped to `A-Z[\]]`. */
  11. RfcStrict(97..125 to 65..93);
  12. companion object {
  13. internal fun fromName(name: String) = when(name.toLowerCase()) {
  14. "ascii" -> Ascii
  15. "rfc1459" -> Rfc
  16. "rfc1459-strict" -> RfcStrict
  17. else -> Rfc
  18. }
  19. }
  20. /**
  21. * Determines if the two strings are equivalent under the casemapping rules.
  22. */
  23. fun areEquivalent(string1: String, string2: String): Boolean {
  24. return string1.length == string2.length
  25. && string1.zip(string2).all { (c1, c2) -> areEquivalent(c1, c2) }
  26. }
  27. private fun areEquivalent(char1: Char, char2: Char) = char1 == char2 || char1.toUpper() == char2.toUpper()
  28. private fun Char.toUpper() = this + if (this.toInt() in lowerToUpperMapping.first) lowerToUpperMapping.second.start - lowerToUpperMapping.first.start else 0
  29. }